4.6 Implementing Spell Checking in Your Windows and Web Apps with NetSpell
Like it or not, good spelling is a crucial part of written communication. Spelling mistakes reflect poorly on the writer and can create barriers just by making a negative impression on the reader. Why not ease your users’ spelling worries by wiring a simple, powerful spellchecking utility into your applications?
NetSpell, written by Paul Welter of LoreSoft, is a lightweight spellchecking library that can be added quickly to your .NET applications. It comes with dictionaries for several different languages and built-in controls for Windows Forms and web apps. NetSpell was written on the 1.1 Framework but wraps nicely into 2.0 applications.
Straight out of the box, NetSpell’s distribution gives you user interfaces for both Windows Forms and ASP.NET pages. The interface is a separate dialog for managing spellchecking of your text with standard buttons for ignoring, replacing, or adding words to the dictionary. Figure 4-15 shows NetSpell’s dialog in front of a Windows Form demo app.
Figure 4-15. NetSpell's dialog in front of a user-created Windows Form
NetSpell has several components you’ll need to work with when tying it into your application. If you’re working on a web application, copy the NetSpell.SpellChecker.dll assembly to the bin folder. If you’re working on a Windows Forms app, just reference it in your project.
Three additional files are required for web applications: spell.css, spell.js, and the SpellCheck.aspx control. Copy these to the same folder as the control in which you’re enabling spellchecking.
Finally, for both web apps and Windows Forms apps, you’ll need to place the distribution’s dic folder (which contains NetSpell’s dictionaries) in an accessible location. You’ll also need to reference the dic folder’s location in the web.config file for web applications. (Windows Forms apps won’t need that reference—you’ll configure the spelling control itself.) For example, if you’ve placed the dictionary folder under the application’s bin folder, your web.config should look like this:
NetSpell uses two classes to provide spellchecking:DictionaryandSpelling. TheDictionaryclass deals with the physical dictionary files and creates word lists for use in checking text. TheSpellingclass manages the spellchecking process and allows you to configure things such as ignoring HTML or forcing all capital letters.
For Windows Forms apps, start by dropping NetSpell.SpellChecker.dll on the General toolbar tab, which adds the Word Dictionary and Spelling controls to the toolbox. Next, drag both controls onto your form’s design surface. The Dictionary needs to know where the physical dictionary files are located, so point theDictionary.DictionaryFolderproperty to the folder holding the dictionary files (bin\dic in the web.config example).
The next step is to let the Spelling control know where its data source is. Open theSpellingobject’s property tab and set theDictionary property to theDictionaryobject you just configured.
Now it’s time to wire things together in code. The following example is adapted straight from Welter’s WinForms demo in NetSpell’s distribution. Upon a buttonclick event, text from aRichTextBoxis sent to theSpellingobject, an instantiation of theSpellCheckerclass. TheSpellCheck()method starts the checking process:
NetSpell works from an event-driven approach, so you’ll need to implement several event handlers to deal with replacing or dropping words kicked out during the spellchecking. Pull up the property sheet for theSpellingobject to see the exposed events.
At a minimum, you’ll need to implement handlers for theReplacedWordandDeletedWordevents. TheReplacedWordevent occurs when a misspelled word is called out, a word is listed in the Replace With field, and the Replace button is clicked. You must deal with substituting the misspelled word in the original text with the contents of the replacement word. NetSpell’s example, included in the distribution, shows one way to accomplish this:
private void spelling_ReplacedWord(object sender, NetSpell.SpellChecker.ReplaceWordEventArgs e) { int start = this.richTextBox.SelectionStart; int length = this.richTextBox.SelectionLength;
this.richTextBox.Select(e.TextIndex, e.Word.Length); // Replace selection with word from Replace With field this.richTextBox.SelectedText = e.ReplacementWord;
// Move selection point to next word if (start > this.richTextBox.Text.Length) start = this.richTextBox.Text.Length; if ((start + length) > this.richTextBox.Text.Length) length = 0; this.richTextBox.Select(start, length); }
DeletedWordevents are fired when a misspelled word is called out, the Replace With field is left blank, and the Replace button is clicked. You’ll need to clear the misspelled word from the original text:
private void spelling_DeletedWord(object sender, NetSpell.SpellChecker.SpellingEventArgs e) { int start = this.richTextBox.SelectionStart; int length = this.richTextBox.SelectionLength;
// Move selection point to next word if (start > this.richTextBox.Text.Length) start = this.richTextBox.Text.Length; if ((start + length) > this.richTextBox.Text.Length) length = 0; this.richTextBox.Select(start, length); }
The code to move the selection point is the same in all events and should be refactored out to a separate method. It’s left in this example for the sake of clarity.
Lastly, use theEndOfTextevent to perform any final steps. Notifying the user of the spellcheck’s completion is automatically handled by NetSpell, which launches a dialog box advising the user:
private void spelling_EndOfText(object sender, System.EventArgs e) { // Perform any cleanup tasks you might need }
Implementing NetSpell in ASP.NET is much the same. It’s even easier if you’re using FreeTextBox, an open source text-editing ASP control discussed in Chapter 1. NetSpell is integrated directly into FreeTextBox, saving you much of the implementation coding.
Getting Support
Support is available through dedicated forums on the tool’s home page as well as through a bug tracker available from SourceForge (http://sourceforge.net/projects/netspell/).
NetSpell in a Nutshell
NetSpell is a handy tool that you can quickly implement in your applications. Its documentation covers all the members of the various classes, but it has no implementation guidance. However, the two demo solutions included with the source download show skeletal implementations for ASP.NET and Windows Forms applications, which are enough to get developers pointed in the right direction.
NPlot is a flexible and simple-to-use open source charting library for the .NET Framework v2.0. NPlot’s ability to quickly create charts makes it an ideal tool for data inspection, debugging, or analysis purposes. The library’s flexibility also makes it a great choice for creating carefully tuned charts for publications or as part of your application’s interface.
NPlot at a Glance
Tool
NPlot
Version covered
0.9.9.3
Home page
http://www.netcontrols.org/nplot/
Power Tools page
http://www.windevpowertools.com/tools/147
Summary
A charting library for .NET 2.0 with a simple, flexible API
NPlot at a Glance (continued)
License type
Custom (effectively, a choice of GPL-compatible or BSD with an advertising
clause)
Online resources
Wiki
Supported Frameworks
.NET 2.0
Related tools in this book
WebChart
Getting Started
NPlot requires version 2.0 of the .NET Framework. You must also agree to the terms of its license. The license is very relaxed on the use of NPlot in other open source software or software written for personal use, but use of NPlot in a closed-source application requires that you advertise NPlot’s role in your application’s About box or documentation.
You can download the NPlot library from the Download Area link on the tool’s home page. NPlot is distributed in a .zip file that contains the assembly, complete C# source to the library, and a C# demo showing the library in action.
Using NPlot
To create a chart, the first thing you need to do is construct an instance of a PlotSurface2D class. The role of this object is to coordinate the display of the axes, title, and legend, as well as all the data-dependent elements of the chart. NPlot provides three such classes:
Windows.PlotSurface2D A Windows Forms control that implements plotting functionality and enables management of a user’s interaction with the chart.
Bitmap.PlotSurface2D A Windows Forms control that allows you to easily draw charts on aSystem.Drawing.Bitmapobject. This class is often used in web applications to generate dynamic charts and is also useful in debugging.
Web.PlotSurface2D An ASP.NET control that implements the IPlotSurface2Dfunctionality. The implementation of this control compromises performance, and its use is not recommended.
APlotSurface2D class that allows charts to be used in GTK# applications created with Mono (the free C# compiler/.NET implementation) under Linux has also been written for an older version of NPlot. This class is not currently maintained as part of the library, but it might be in the future.
Once you’ve created a PlotSurface2D, you’re ready to start charting some data. To do this, you first need to create an instance of one of NPlot’s classes that implements the IDrawable or IPlot interface. You then point this object to your data, optionally set a few display properties, and add it to your PlotSurface2D.
Plot classes wrap your data and provide functionality for drawing it against a pair of axes. The different plot classes display your data in different ways (for example, as a series of points or as a line). Plot classes can also draw representations of themselves in a plot surface legend if one is present and can suggest the axes against which they should optimally be drawn.
Several lightweight classes, includingTextItemandArrowItem, implement just theIDrawableinterface. These classes can’t draw representations of themselves in the legend or influence thePlotSurface2D’s selection of axes.
The most commonly used classes implementingIDrawableare:
ArrowItem Draws arrows pointing to a particular world coordinate
FilledRegion Creates a filled area between two line plots
Grid Adds gridlines that automatically align to axis tick positions
TextItem Places text at a specific world coordinate
The following are descriptions of some of NPlot’s available plot types:
LinePlot
Use a line plot (Figure 4-16) when it makes sense to connect successive data points. For example, you would use a line plot to graph measurements of the ambient temperature of a room at various times throughout a day. You can control the line in the plot by passing a configuredSystem.Drawing.Penclass to theLinePlot.
PointPlot
Use a point plot (scatter chart) when it does not make sense to connect successive data points. For example, if you wanted to visualize the heights and weights of a group of people on a chart, you could plot a point for each person with the x-position determined by the person’s weight and the y-position determined by the person’s height. Fifteen predefined marker styles, including the one shown in Figure 4-17, are available.
Figure 4-16. LinePlot graph
Figure 4-17.PointPlot graph
StepPlot
Step plots like the one in Figure 4-18 are useful for displaying sample-based data (such as PCM audio), where each value can be thought of as representing the value of the measured quantity over a specific time period. You can choose whether the horizontal sections of the step plot are centered on the abscissa values or drawn between successive abscissa values.
Figure 4-18. StepPlot graph
BarPlot
A bar plot (or histogram) is usually used to chart the number of data values belonging to one or more categories. The height of the bar represents the number of values in the given category. For example, if you had a collection of dogs and data on the breed of each, you could create a chart of the number of each type of breed.
You will often want to make the x-axis aLabelAxis(the names of the dog breeds, for instance). You can define fill patterns for the bars using HorizontalRectangleBrushand similar classes. Bar charts can also be stacked on top of each other, as shown in Figure 4-19. Horizontal bar plots are currently not supported by NPlot.
Figure 4-19. BarPlot graph
ImagePlot
Image plots (Figure 4-20) are often used to display the variation of a value over a spatial area. Each value in the region is mapped to a color. You can specify the color-to-value mapping using an object of any class that implementsIGradient, such asLinearGradient.
Figure 4-20. ImagePlot graph
If the built-inIPlotandIDrawableclasses don’t provide the functionality you require, creating your own class that implements one of these interfaces is straightforward. This is perhaps the most common way of extending NPlot.
You can add as many plots to aPlotSurface2Dobject as you like. The order in which they are drawn is configured with the z-order parameter of theAdd()method. Also, thePlotSurface2D classes define two independent x-axes and two independent y-axes. When you add an item, you can choose the x-and y-axes you would like it to be associated with.
Specifying data
The IPlot interface does not enforce how data associated with the specific plot classes should be represented. However, where it makes sense, these classes provide a consistent interface for this purpose. Data can be provided in one of two forms:
In an object of typeDataSet,DataTable, orDataViewfrom theSystem.Datanamespace
In any collection that implements theIEnumerableinterface where it is valid to cast each of the elements to typedouble
Examples of such collections are:
Double[]
System.Collections.ArrayList
System.Collections.Generic.List <System.Int16>
If you are working with very large data sets and efficiency is a concern, it is best to pass your data to NPlot via the built-in array typedouble[].
The following four properties are used to specify data:
DataSource
TheDataSet,DataTable, orDataViewobject you are using.
DataMember
A string containing the name of the sourceDataTablein aDataSet.
AbscissaData
The x-coordinates of the data to plot. This should be a string containing the name of the column to take the data from if the source is aDataTableorDataView. Otherwise, it can be set to any container that implements theIEnumerableinterface. This property is optional. If it is not specified (or is set tonull), the abscissa data will be assumed to be 0, 1, 2....
OrdinateData
The y-coordinates of the data to plot. This should be a string containing the name of the column to take the data from if data is being read from aDataTableorDataView. Otherwise, it can be set to any container that implements theIEnumerableinterface.
If these properties are not suitable for a particular plot type, the interface is as close to this as possible. For example,CandlePlotprovidesOpenData,LowData,HighData, andCloseDataproperties instead ofOrdinateData.
Axes. APlotSurface2Dobject automatically determines axes suitable for displaying the plot objects that you add to it. However, these are highly customizable. Some common things that you might wish to add or adjust are:
The angle of the text next to the ticks (using theTicksAngleproperty)
The pen used to draw the axis (using theAxisPenproperty)
World minimum and maximum values (using theWorldMinandWorldMaxproperties)
You can also replace the default axes with a completely different axis type. NPlot provides a number of axis types with individually configurable characteristics, includingLinearAxis,LogAxis,LabelAxis, andDateTimeAxis.
NPlot’s distribution includes a nice demo application that runs through many of NPlot’s chart types. The application demonstrates just how easy it is to feed data sources into a plot object and produce a detailed graph. Example 4-3 shows extracts from the demo app for creating a CandlePlot graph showing stock price data.
Example 4-3. Creating a CandlePlot from an XML file
// The plot surface to hold graphs. Note the surface is an // NPlot.Windows.PlotSurface2D class instead of // NPlot.PlotSurface2D. The utilized class derives from // Forms.UserControl and automatically paints itself. private NPlot.Windows.PlotSurface2D plotSurface; // obtain stock information from XML file DataSet ds = new DataSet(); System.IO.Stream file = Assembly.GetExecutingAssembly().GetManifestResourceStream( "NPlotDemo.resources.asx_jbh.xml" ); ds.ReadXml( file, System.Data.XmlReadMode.ReadSchema ); DataTable dt = ds.Tables[0]; // create CandlePlot CandlePlot cp = new CandlePlot(); cp.DataSource = dt; cp.AbscissaData = "Date"; cp.OpenData = "Open"; cp.LowData = "Low"; cp.HighData = "High"; cp.CloseData = "Close"; cp.BearishColor = Color.Red; cp.BullishColor = Color.Green; cp.StickWidth = 3; cp.Color = Color.DarkBlue;
plotSurface.Add( new Grid() ); plotSurface.Add( cp );
Figure 4-21 shows the graph produced by this code and data.
NPlot offers great flexibility for combining plot types, too. Figure 4-22 shows the power of NPlot by layering multiple y-axes, a dashed-line plot, and a histogram plot.
Getting Support
Support for NPlot is limited to submitting bug reports at its home page.
Figure 4-21.CandlePlot generated from example code
Figure 4-22. A complex graph using multiple types
NPlot in a Nutshell
The current version of NPlot is 0.9.9.3—-it has not yet reached version 1.0. This reflects the following facts:
Some functionality that many users expect from a charting library is still missing. NPlot is not yet considered basic-feature complete (though it is getting close).
The API is still subject to change without notice and without regard to backwardcompatibility. The focus remains on creating the best library design possible.
There are no separate development/stable branches of the code. A given release of NPlot may include both bug fixes and significant enhancements. The latter have the potential to break functionality that worked in previous releases.
That said, NPlot is known to be used reliably in several production systems.
NPlot is an easy-to-use, flexible charting library that has a wide range of applications. It is under active development, with particular focus on polishing the interface and achieving a very stable release for version 1.0.
—Matt Howell, creator of NPlot
Please check back tomorrow for the continuation of this article.