<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Dot Net Thoughts &#187; .Net</title>
	<atom:link href="http://www.dotnetthoughts.net/tag/net/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dotnetthoughts.net</link>
	<description>thoughts about .Net, WPF, Sharepoint, Javascript and more.</description>
	<lastBuildDate>Wed, 28 Jul 2010 09:59:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>FileNot Found exception &#8211; Application_Error event in Global.asax</title>
		<link>http://www.dotnetthoughts.net/2010/07/28/filenot-found-exception-application_error-event-in-global-asax/</link>
		<comments>http://www.dotnetthoughts.net/2010/07/28/filenot-found-exception-application_error-event-in-global-asax/#comments</comments>
		<pubDate>Wed, 28 Jul 2010 09:59:26 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[Application_Error]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[File Not Found]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=1017</guid>
		<description><![CDATA[Today I got a problem from my colleague, that he is getting FileNot Found exception in Application Error event in Global.asax, which is used to log application errors. But the application was working fine and good. We thought it may be because of missing images that was referring in Stylesheets. But all the image references [...]]]></description>
			<content:encoded><![CDATA[<p>Today I got a problem from my colleague, that he is getting FileNot Found exception in Application Error event in Global.asax, which is used to log application errors. But the application was working fine and good. We thought it may be because of missing images that was referring in Stylesheets. But all the image references are valid and we couldn&#8217;t find any issue. We couldn&#8217;t find anything suspicious in stack trace.</p>
<p>Stack Trace from the exception</p>
<blockquote><p>   at System.Web.StaticFileHandler.GetFileInfo(String virtualPathWithPathInfo, String physicalPath, HttpResponse response)<br />
   at System.Web.StaticFileHandler.ProcessRequestInternal(HttpContext context)<br />
   at System.Web.DefaultHttpHandler.BeginProcessRequest(HttpContext context, AsyncCallback callback, Object state)<br />
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()<br />
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&#038; completedSynchronously)</p></blockquote>
<p>After doing some search we got an option where we can find the file causing the exception. We created a string variable and put a break point over there and debugged the code. It will display the filename causing the exception. In our case it was a HTML file which was used in a Javascript to set an IFRAME source, unfortunately the developer who copied the script missed the HTML and it was causing the exception. </p>
<p>Here is the code.</p>
<pre class="brush: csharp;">
void Application_Error(object sender, EventArgs e)
{
Exception err = Server.GetLastError();
//Insert a break point and run in debug mode.
string fileName = Context.Request.FilePath;
 Application[&quot;UnhandledException&quot;] = err;
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2010/07/28/filenot-found-exception-application_error-event-in-global-asax/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Selecting controls using LINQ</title>
		<link>http://www.dotnetthoughts.net/2010/07/19/selecting-controls-using-linq/</link>
		<comments>http://www.dotnetthoughts.net/2010/07/19/selecting-controls-using-linq/#comments</comments>
		<pubDate>Mon, 19 Jul 2010 09:35:01 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Windows Forms]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=1007</guid>
		<description><![CDATA[One of my colleague asked how to get all the text boxes with no text entered in Windows form without using a For Loop. I thought of writing it with LINQ. And here is my implementation. var controls = from control in this.Controls select control; But this will generate a compile time error &#8211; Could [...]]]></description>
			<content:encoded><![CDATA[<p>One of my colleague asked how to get all the text boxes with no text entered in Windows form without using a For Loop. I thought of writing it with LINQ. And here is my implementation. </p>
<pre class="brush: csharp;">
 var controls = from control in this.Controls
                           select control;
</pre>
<p>But this will generate a compile time error &#8211; <em>Could not find an implementation of the query pattern for source type &#8216;System.Windows.Forms.Control.ControlCollection&#8217;.  &#8216;Select&#8217; not found.  Consider explicitly specifying the type of the range variable &#8216;control&#8217;.</em> But the error was self explanatory, I need to specify the type of the control. And here is the modified version.</p>
<pre class="brush: csharp;">
var controls = from Control control in this.Controls
                           select control;
</pre>
<p>And if you want to select specific type of controls you need to apply a where condition.</p>
<pre class="brush: csharp;">
var textboxes = from Control textbox in this.Controls
                where textbox is TextBox
                select textbox;
</pre>
<p>There is some other inbuilt operators is also available to select specific controls, like OfType()</p>
<pre class="brush: csharp;">
var textboxes = from textbox in this.Controls.OfType&lt;TextBox&gt;()
                select textbox;
</pre>
<p>In this method we don&#8217;t need to specify the type of the control in the from statement. And one of interesting LINQ extension method is the Cast&lt;&gt; method, which helps to enable the standard query operators to be invoked on non-generic collections by supplying the necessary type information. You can get more information from <a target="_blank" href="http://msdn2.microsoft.com/en-us/library/bb341406.aspx">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2010/07/19/selecting-controls-using-linq/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dropdownlist FindByText Problem</title>
		<link>http://www.dotnetthoughts.net/2010/07/15/dropdownlist-findbytext-problem/</link>
		<comments>http://www.dotnetthoughts.net/2010/07/15/dropdownlist-findbytext-problem/#comments</comments>
		<pubDate>Thu, 15 Jul 2010 12:35:03 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C#.Net]]></category>
		<category><![CDATA[FindByText Problem]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=1001</guid>
		<description><![CDATA[Today one of my colleague talked about a simple basic issue with Dropdownlist, the FindByText() method works as case sensitive. Because of this issue, we are getting some exceptions. So I starting looking for alternatives and one way I found it looping the items and compare it. Like the following. this.ddlItems.SelectedIndex = -1; foreach (ListItem [...]]]></description>
			<content:encoded><![CDATA[<p>Today one of my colleague talked about a simple basic issue with Dropdownlist, the FindByText() method works as case sensitive. Because of this issue, we are getting some exceptions. So I starting looking for alternatives and one way I found it looping the items and compare it. Like the following.</p>
<pre class="brush: csharp;">
this.ddlItems.SelectedIndex = -1;
foreach (ListItem item in this.ddlItems.Items)
{
    if (item.Text.Equals(&quot;Item&quot;, StringComparison.CurrentCultureIgnoreCase))
    {
        item.Selected = true;
        break;
    }
}
</pre>
<p>It is a nice option, I rewrote it as an extension method and works fine. Later I thought of wrting more generic FindByTextMethod() and here the extension method.</p>
<pre class="brush: csharp;">
/// &lt;summary&gt;
/// Searches the Collection of ListItem with a ListItem.Text property contains the specified text
/// &lt;/summary&gt;
/// &lt;param name=&quot;items&quot;&gt;&lt;/param&gt;
/// &lt;param name=&quot;text&quot;&gt;The text to search for.&lt;/param&gt;
/// &lt;param name=&quot;stringComparison&quot;&gt;One of the System.StringComparison values.&lt;/param&gt;
/// &lt;returns&gt;ListItem if the collection contains the text, null otherwise.&lt;/returns&gt;
public static ListItem FindByText(this ListItemCollection items,
    string text,
    StringComparison comparisonType)
{
    ListItem result = items.OfType&lt;ListItem&gt;().
        FirstOrDefault(_string =&gt; _string.Text.Equals(text, comparisonType));
    return result;
}
</pre>
<p>And you can use it like this</p>
<pre class="brush: csharp;">
this.ddlItems.Items.FindByText(&quot;Item&quot;, StringComparison.CurrentCultureIgnoreCase).Selected = true;
</pre>
<p>Happy Coding <img src='http://www.dotnetthoughts.net/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2010/07/15/dropdownlist-findbytext-problem/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Implementing Print using C#</title>
		<link>http://www.dotnetthoughts.net/2010/07/08/implementing-print-using-c/</link>
		<comments>http://www.dotnetthoughts.net/2010/07/08/implementing-print-using-c/#comments</comments>
		<pubDate>Thu, 08 Jul 2010 20:43:35 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[Windows Forms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C# Printing]]></category>
		<category><![CDATA[C#.Net]]></category>
		<category><![CDATA[Print]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=989</guid>
		<description><![CDATA[The first assignment I got from my lead in my previous company was to create Print option to the accounting package we were working. The application was developed in VB 6.0. And we were used batch files and command prompt for printing accounting related documents from the application. Few days back one of colleague asked [...]]]></description>
			<content:encoded><![CDATA[<p>The first assignment I got from my lead in my previous company was to create Print option to the accounting package we were working. The application was developed in VB 6.0. And we were used batch files and command prompt for printing accounting related documents from the application. Few days back one of colleague asked how we can print from C#, he was developing an accounting package for his uncle. I said something like we need to use PrintDocument class for that, but I couldn’t give him a sample code. Today I got some free time in Office so I thought about implementing printing from C#. Here is a simple implementation, which displays a Print Dialog, and based on the settings, it will print the contents of the textbox.</p>
<p><del datetime="2010-07-10T13:53:05+00:00">I tried to print the document based on the ForeColor of the TextBox, but it was throwing some error, I couldn’t resolve it</del>Its fixed. <img src='http://www.dotnetthoughts.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Source code is pretty self-explanatory. Happy Printing.</p>
<pre class="brush: csharp;">
private int startIndex = 0;
private void printToolStripMenuItem_Click(object sender, EventArgs e)
{
    PrintDocument printDocument = new PrintDocument();
    //Print Options dialog.
    using (PrintDialog printDialog = new PrintDialog())
    {
        printDialog.ShowHelp = false;
        printDialog.ShowNetwork = false;
        printDialog.Document = printDocument;
        printDialog.AllowPrintToFile = true;
        //As its a simple text file, disabling the advanced options.
        printDialog.AllowCurrentPage = false;
        printDialog.AllowSelection = false;
        printDialog.AllowSomePages = false;
        //Display XP Style Print Dialog
        printDialog.UseEXDialog = true;
        if (printDialog.ShowDialog(this) == DialogResult.OK)
        {
            //Assigning the Printer settings to the Document.
            printDocument.PrinterSettings = printDialog.PrinterSettings;
            printDocument.PrintPage += new PrintPageEventHandler(printDocument_PrintPage);
            //Number of copies
            for (int i = 0; i &lt; printDialog.PrinterSettings.Copies; i++)
            {
                startIndex = 0;
                //Print method call.
                printDocument.Print();
            }
        }
    }
}
</pre>
<p>And here is the Print Page event.</p>
<pre class="brush: csharp;">
protected void printDocument_PrintPage(object sender, PrintPageEventArgs e)
{
    //Setting the color as Black.
    Brush brush = Brushes.Black;
    //Setting color dynamically
    //Brush brush = new SolidBrush(this.txtEditor.ForeColor);
    int lineCounter = 0;
    float lineTop = 0;
    //Looping throught each line in the textbox.
    for (int lineIndex = startIndex; lineIndex &lt; this.txtEditor.Lines.Length; lineIndex++)
    {
        string line = this.txtEditor.Lines[lineIndex];
        lineCounter++;
        //Writing the line to the document.
        lineTop = e.MarginBounds.Top + lineCounter * this.txtEditor.Font.Size;
        e.Graphics.DrawString(line,
            this.txtEditor.Font,
            brush,
            e.MarginBounds.Left,
            lineTop);
        //Checking for more pages.
        if (lineTop &gt; e.MarginBounds.Bottom)
        {
            startIndex = lineIndex;
            e.HasMorePages = true;
            return;
        }
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2010/07/08/implementing-print-using-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Implementing ASP.Net Forms Authentication with Active Directory Membership Provider</title>
		<link>http://www.dotnetthoughts.net/2010/06/29/implementing-asp-net-forms-authentication-with-active-directory-membership-provider/</link>
		<comments>http://www.dotnetthoughts.net/2010/06/29/implementing-asp-net-forms-authentication-with-active-directory-membership-provider/#comments</comments>
		<pubDate>Tue, 29 Jun 2010 07:52:28 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[Active Directory Authentication]]></category>
		<category><![CDATA[ASP.Net Handler]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=958</guid>
		<description><![CDATA[ActiveDirectoryMembership provider is used manage users against Active Directory, which helps to create Single Sign On for intranet application. Here is a basic implementation, which used to Authenticate users against Active Directory, using Login Control. We need to modify the web.config, like the implementation of Forms Authentication in ASP.Net. Create / Add a connection string [...]]]></description>
			<content:encoded><![CDATA[<p>ActiveDirectoryMembership provider is used manage users against Active Directory, which helps to create Single Sign On for intranet application. Here is a basic implementation, which used to Authenticate users against Active Directory, using Login Control.</p>
<p>We need to modify the web.config, like the implementation of Forms Authentication in ASP.Net.</p>
<p>Create / Add a connection string to active directory database.</p>
<pre class="brush: xml;">
&lt;connectionStrings&gt;
&lt;add name=&quot;ADConnectionString&quot; connectionString=&quot;LDAP://DOMAIN.SUBDOMAIN/DC=DOMAIN,DC= SUBDOMAIN &quot;/&gt;
&lt;/connectionStrings&gt;
</pre>
<p>Configure Membership node in the web.config with ActiveDirectoryMembershipProvider.</p>
<pre class="brush: xml;">
&lt;membership defaultProvider=&quot;MembershipADProvider&quot;&gt;
  &lt;providers&gt;
    &lt;add name=&quot;MembershipADProvider&quot;
         type=&quot;System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a&quot;
         applicationName=&quot;dotnetthoughts&quot;
         connectionStringName=&quot; ADConnectionString &quot;
         attributeMapUsername=&quot;sAMAccountName&quot;/&gt;
  &lt;/providers&gt;
&lt;/membership&gt;
</pre>
<p>You can also provide the Username / Password in this using connectionUsername , connectionPassword attributes.</p>
<p>Modify the Authentication mode and Authorization nodes for controlling the access permissions. Currently I am using Forms Authentication defaults. (default.aspx &#8211; Home Page, and Login.aspx &#8211; Login Page)</p>
<pre class="brush: xml;">
&lt;authentication mode=&quot;Forms&quot; /&gt;
&lt;authorization&gt;
    &lt;deny users=&quot;?&quot; /&gt;
    &lt;allow users=&quot;*&quot; /&gt;
&lt;/authorization&gt;
</pre>
<p>Almost done. Now drag and drop Login control from Toolbox > Login tab to Login.aspx. Run the application, say OK to the Debug mode confirmation from Visual Studio. As we are configured the Authentication provider we don’t need to write any Code to Authentication.</p>
<p>If you don&#8217;t want to use login control, you can do something like this in the code behind for the authentication.</p>
<pre class="brush: csharp;">
if (Membership.ValidateUser(this.txtUsername.Text, this.txtPassword.Text))
{
    FormsAuthentication.RedirectFromLoginPage(this.txtUsername.Text, false);
}
else
{
    Response.Write(&quot;Authentication failed.\nUsername / Password Invalid&quot;);
}
</pre>
<p>Thanks to Sreenaja for the initial implementation. Happy Coding <img src='http://www.dotnetthoughts.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2010/06/29/implementing-asp-net-forms-authentication-with-active-directory-membership-provider/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Customize SpellCheck in WPF textbox</title>
		<link>http://www.dotnetthoughts.net/2010/06/22/customize-spellcheck-in-wpf-textbox/</link>
		<comments>http://www.dotnetthoughts.net/2010/06/22/customize-spellcheck-in-wpf-textbox/#comments</comments>
		<pubDate>Tue, 22 Jun 2010 08:43:24 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C#.Net]]></category>
		<category><![CDATA[SpellCheck]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=936</guid>
		<description><![CDATA[While working on a personal project (fleetIt). I worked on Textbox spell check option. I enabled it, it was working fine, until I added a context menu to to the textbox, for custom commands of my application. It was displaying the spelling errors but the suggestions and correction options was not available. Then I tried [...]]]></description>
			<content:encoded><![CDATA[<p>While working on a personal project (fleetIt). I worked on Textbox spell check option. I enabled it, it was working fine, until I added a context menu to to the textbox, for custom commands of my application. It was displaying the spelling errors but the suggestions and correction options was not available. Then I tried to customize the context menu such a way that it can display both my custom options as well as the system default spell check options. Here is a simple implementation, which helps to customize the context menu and display the spell check suggestions options.</p>
<pre class="brush: xml;">
&lt;Window x:Class=&quot;dotnetthoughts.net.MainWindow&quot;
xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
        xmlns:sys=&quot;clr-namespace:System;assembly=System&quot;
Title=&quot;WPF SpellCheck Demo&quot; Height=&quot;350&quot; Width=&quot;525&quot; Loaded=&quot;Window_Loaded&quot;&gt;
&lt;DockPanel&gt;
&lt;TextBox Name=&quot;txtEdit&quot; SpellCheck.IsEnabled=&quot;True&quot;
                AcceptsReturn=&quot;True&quot;
ContextMenuOpening=&quot;txtEdit_ContextMenuOpening&quot;
                VerticalScrollBarVisibility=&quot;Visible&quot;&gt;
&lt;TextBox.ContextMenu&gt;
&lt;ContextMenu Name=&quot;ctxMenu&quot; /&gt;
&lt;/TextBox.ContextMenu&gt;
&lt;/TextBox&gt;
&lt;/DockPanel&gt;
&lt;/Window&gt;
</pre>
<p>And here is the code behind</p>
<pre class="brush: csharp;">
namespace dotnetthoughts.net
{
    using System;
    using System.IO;
using System.Linq;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Input;

public partial class MainWindow : Window
    {
public MainWindow()
        {
InitializeComponent();
        }

private void txtEdit_ContextMenuOpening(object sender, ContextMenuEventArgs e)
        {
            int index = 0;
this.txtEdit.ContextMenu.Items.Clear(); //Clearing the existing items
            //Getting the spellcheck suggestions.
SpellingError spellingError = this.txtEdit.GetSpellingError(this.txtEdit.CaretIndex);
if (spellingError != null &amp;&amp; spellingError.Suggestions.Count() &gt;= 1)
            {
                //Creating the suggestions menu items.
foreach (string suggestion in spellingError.Suggestions)
                {
MenuItem menuItem = new MenuItem();
                    menuItem.Header = suggestion;
menuItem.FontWeight = FontWeights.Bold;
menuItem.Command = EditingCommands.CorrectSpellingError;
                    menuItem.CommandParameter = suggestion;
menuItem.CommandTarget = this.txtEdit;
this.txtEdit.ContextMenu.Items.Insert(index, menuItem);
                    index++;
                }
Separator seperator = new Separator();
this.txtEdit.ContextMenu.Items.Insert(index, seperator);
                index++;
//Adding the IgnoreAll menu item
MenuItem IgnoreAllMenuItem = new MenuItem();
                IgnoreAllMenuItem.Header = &quot;Ignore All&quot;;
IgnoreAllMenuItem.Command = EditingCommands.IgnoreSpellingError;
IgnoreAllMenuItem.CommandTarget = this.txtEdit;
                this.txtEdit.ContextMenu.Items.Insert(index, IgnoreAllMenuItem);
                index++;
            }
            else
            {
//No Suggestions found, add a disabled NoSuggestions menuitem.
                MenuItem menuItem = new MenuItem();
menuItem.Header = &quot;No Suggestions&quot;;
                menuItem.IsEnabled = false;
this.txtEdit.ContextMenu.Items.Insert(index, menuItem);
                index++;
            }
//.Net 4.0 Supports CustomDictionaries, Option for Adding to dictionary.
int selectionStart = this.txtEdit.GetSpellingErrorStart(this.txtEdit.CaretIndex);
            if (selectionStart &gt;= 0)
            {
                Separator seperator1 = new Separator();
this.txtEdit.ContextMenu.Items.Insert(index, seperator1);
                index++;
MenuItem AddToDictionary = new MenuItem();
                AddToDictionary.Header = &quot;Add to Dictionary&quot;;
                //Getting the word to add
this.txtEdit.SelectionStart = selectionStart;
this.txtEdit.SelectionLength = this.txtEdit.GetSpellingErrorLength(this.txtEdit.CaretIndex);
                //Ignoring the added word.
AddToDictionary.Command = EditingCommands.IgnoreSpellingError;
AddToDictionary.CommandTarget = this.txtEdit;
AddToDictionary.Click += (object o, RoutedEventArgs rea) =&gt;
                {
this.AddToDictionary(this.txtEdit.SelectedText);
                };
this.txtEdit.ContextMenu.Items.Insert(index, AddToDictionary);
                index++;
            }

//Common Edit MenuItems.
            Separator seperator2 = new Separator();
this.txtEdit.ContextMenu.Items.Insert(index, seperator2);
            index++;
            //Cut
MenuItem cutMenuItem = new MenuItem();
cutMenuItem.Command = ApplicationCommands.Cut;
this.txtEdit.ContextMenu.Items.Insert(index, cutMenuItem);
            index++;
            //Copy
MenuItem copyMenuItem = new MenuItem();
copyMenuItem.Command = ApplicationCommands.Copy;
this.txtEdit.ContextMenu.Items.Insert(index, copyMenuItem);
            index++;
            //Paste
MenuItem pasteMenuItem = new MenuItem();
pasteMenuItem.Command = ApplicationCommands.Paste;
this.txtEdit.ContextMenu.Items.Insert(index, pasteMenuItem);
            index++;
            Separator seperator3 = new Separator();
this.txtEdit.ContextMenu.Items.Insert(index, seperator3);
            index++;
            //Delete
MenuItem deleteMenuItem = new MenuItem();
deleteMenuItem.Command = ApplicationCommands.Delete;
            this.txtEdit.ContextMenu.Items.Insert(index, deleteMenuItem);
            index++;
            Separator seperator4 = new Separator();
this.txtEdit.ContextMenu.Items.Insert(index, seperator4);
            index++;
            //Select All
MenuItem selectAllMenuItem = new MenuItem();
selectAllMenuItem.Command = ApplicationCommands.SelectAll;
            this.txtEdit.ContextMenu.Items.Insert(index, selectAllMenuItem);
            index++;
        }
        //Method to Add text to Dictionary
private void AddToDictionary(string entry)
        {
using (StreamWriter streamWriter = new StreamWriter(@&quot;D:\WPF\MyCustomDictionary.lex&quot;, true))
            {
streamWriter.WriteLine(entry);
            }
        }

private void Window_Loaded(object sender, RoutedEventArgs e)
        {
//Assigning custom Dictionary to TextBox
this.txtEdit.SpellCheck.CustomDictionaries.Add(new Uri(@&quot;D:\WPF\MyCustomDictionary.lex&quot;));
        }
    }
}
</pre>
<p>The .Net Framework 4.0 supports CustomDictionaries, which helps to create your own Dictionary.</p>
<pre class="brush: csharp;">
//.Net 4.0 Supports CustomDictionaries, Option for Adding to dictionary.
int selectionStart = this.txtEdit.GetSpellingErrorStart(this.txtEdit.CaretIndex);
if (selectionStart &gt;= 0)
{
    Separator seperator1 = new Separator();
this.txtEdit.ContextMenu.Items.Insert(index, seperator1);
    index++;
MenuItem AddToDictionary = new MenuItem();
    AddToDictionary.Header = &quot;Add to Dictionary&quot;;
    //Getting the word to add
this.txtEdit.SelectionStart = selectionStart;
this.txtEdit.SelectionLength = this.txtEdit.GetSpellingErrorLength(this.txtEdit.CaretIndex);
    //Ignoring the added word.
AddToDictionary.Command = EditingCommands.IgnoreSpellingError;
AddToDictionary.CommandTarget = this.txtEdit;
AddToDictionary.Click += (object o, RoutedEventArgs rea) =&gt;
    {
this.AddToDictionary(this.txtEdit.SelectedText);
    };
this.txtEdit.ContextMenu.Items.Insert(index, AddToDictionary);
    index++;
}
</pre>
<p>Here is the screenshot of Demo Application.</p>
<div id="attachment_938" class="wp-caption aligncenter" style="width: 502px"><a href="http://www.dotnetthoughts.net/wp-content/uploads/2010/06/SpellCheck.png"><img class="size-full wp-image-938" title="WPF Spell Check Demo - Screenshot" src="http://www.dotnetthoughts.net/wp-content/uploads/2010/06/SpellCheck.png" alt="WPF Spell Check Demo - Screenshot" width="492" height="287" /></a><p class="wp-caption-text">WPF Spell Check Demo - Screenshot</p></div>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2010/06/22/customize-spellcheck-in-wpf-textbox/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
