<?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>dotnet thoughts &#187; WPF</title>
	<atom:link href="http://www.dotnetthoughts.net/category/net/wpf/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dotnetthoughts.net</link>
	<description>a dotnet developer&#039;s technical blog</description>
	<lastBuildDate>Thu, 02 Feb 2012 03:18:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Introduction to Code First development with Entity Framework</title>
		<link>http://www.dotnetthoughts.net/2012/01/01/introduction-to-code-first-development-with-entity-framework/</link>
		<comments>http://www.dotnetthoughts.net/2012/01/01/introduction-to-code-first-development-with-entity-framework/#comments</comments>
		<pubDate>Sun, 01 Jan 2012 14:52:41 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 4.0]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[ASP.Net MVC]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Code First]]></category>
		<category><![CDATA[Entity Framework Code First]]></category>
		<category><![CDATA[Entity Framewrok]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=2194</guid>
		<description><![CDATA[The Database First approach is interesting when the database already exists. You use Visual Studio and the Entity Framework Designer to generate the C# and VB.NET classes which reflect the existing database model. You may then change relations using the &#8230; <a href="http://www.dotnetthoughts.net/2012/01/01/introduction-to-code-first-development-with-entity-framework/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">The Database First approach is interesting when the database already exists. You use Visual Studio and the Entity Framework Designer to generate the C# and VB.NET classes which reflect the existing database model. You may then change relations using the Designer (or the XML mapping files) later to further optimize the model. The priority is the database &#8211; the code and the model are only secondary. When your priority is the code and you want to begin from scratch without any existing schema or XML mapping files using source code, then the approach is called CodeFirst. Code-First enables an easy development workflow. It enables you to:</p>
<ol>
<li>Develop without opening the designer or mapping in XML files.</li>
<li>Define model objects by simply writing POCO(Plain old CLR object) with no base classes required</li>
<li>Use a &#8220;convention over configuration&#8221; approach that enables database persistence without explicitly configuring anything</li>
</ol>
<p>You can download the latest version of code first from this url : <a href="http://www.microsoft.com/download/en/details.aspx?id=26825">ADO.NET Entity Framework 4.1 &#8211; Update 1</a>. </p>
<p>You can also install via NuGet.</p>
<blockquote><p>install-package entityframework</p></blockquote>
<p><strong>Quick CRUD example with EF Code first.</strong></p>
<p>First we will create the model classes.</p>
<pre class="brush: csharp; title: ; notranslate">
public class Task
{
    public int TaskId { get; set; }
    public string TaskDescription { get; set; }
    public DateTime TaskDate { get; set; }
    public short TaskPriority { get; set; }
    public bool TaskIsDone { get; set; }
}
</pre>
<p>Now we need to create a Context for this. Context is required to use the POCO classes for DataAccess. It can be implemented by deriving it from DbContext class. The DbContext class is available under System.Data.Entity namespace.</p>
<pre class="brush: csharp; title: ; notranslate">
public class TaskContext : DbContext
{
    public DbSet Tasks { get; set; }
}
</pre>
<p>We are done. <img src='http://www.dotnetthoughts.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Now we can use this class for communicating to Database.</p>
<p>Inserting records to Database.</p>
<pre class="brush: csharp; title: ; notranslate">
using (TaskContext taskContext = new TaskContext())
{
    taskContext.Tasks.Add(new Task()
    {
        TaskDate = DateTime.Today,
        TaskDescription = &quot;Create a blog post&quot;,
        TaskIsDone = false,
        TaskPriority = 1
    });
    if (taskContext.SaveChanges() != 0)
    {
        Console.WriteLine(&quot;Task added.&quot;);
    }
}
</pre>
<p>Updating records, updating the first task from Tasks, if the Task date is today.</p>
<pre class="brush: csharp; title: ; notranslate">
using (TaskContext taskContext = new TaskContext())
{
    var currentTask = taskContext.Tasks.Where
		(task =&gt; task.TaskDate == DateTime.Today).FirstOrDefault();
	currentTask.TaskIsDone = true;
    if (taskContext.SaveChanges() != 0)
    {
        Console.WriteLine(&quot;Task updated.&quot;);
    }
}
</pre>
<p>Removing records, removing first task from Tasks, if the Task is completed.</p>
<pre class="brush: csharp; title: ; notranslate">
using (TaskContext taskContext = new TaskContext())
{
    var completedTask = taskContext.Tasks.Where
        (task =&gt; task.TaskIsDone == true).FirstOrDefault();
    taskContext.Tasks.Attach(completedTask);
    taskContext.Tasks.Remove(completedTask);
    if (taskContext.SaveChanges() != 0)
    {
        Console.WriteLine(&quot;Task Deleted.&quot;);
    }
}
</pre>
<p>And retriving records, retriving all the tasks.</p>
<pre class="brush: csharp; title: ; notranslate">
using (TaskContext taskContext = new TaskContext())
{
	var tasks = taskContext.Tasks.Where
		(task =&gt; task.TaskDate == DateTime.Today);
	tasks.ToList().ForEach(task =&gt;
        Console.WriteLine(&quot;Task : {0} IsCompleted : {1}&quot;,
        task.TaskDescription, task.TaskIsDone));
}
</pre>
<p>It is very easy right? Another interesting question is where this data is getting stored? Because we didn&#8217;t specified any Database, or Connection string. By default the database will be created on local instance of SQLEXPRESS (localhost\SqlExpress). The database is named after the fully qualified name of your derived context, in our case that it will be &#8220;EFCodeFirst.TaskContext&#8221;. You can control this by providing connection string or by setting DefaultConnectionFactory.</p>
<p>You can provide connectionstring either in App.Config / Web.Config file or in code.</p>
<p>If you are providing the connection string in config, file the name of the connection string element should be same as Context class name. Like this</p>
<pre class="brush: xml; title: ; notranslate">
&lt;connectionStrings&gt;
  &lt;add name=&quot;TaskContext&quot;
  connectionString=&quot;Server=.\SqlExpress; Integrated Security=SSPI; Database=TaskDb;&quot;
  providerName=&quot;System.Data.SqlClient&quot;/&gt;
&lt;/connectionStrings&gt;
</pre>
<p>And if you want to use your own connection string name, you can do this using CreateConnection() method of the DefaultConnectionFactory class. You can also specify the connection string. You need to provide this information before creating the instance of task context.</p>
<pre class="brush: csharp; title: ; notranslate">
Database.DefaultConnectionFactory.CreateConnection(&quot;TaskDbConnection&quot;);
using (TaskContext taskContext = new TaskContext())
{
	//Code.
}
</pre>
<p>Entity Framework also supports various databases also, like SQL CE, MySql etc. This can be achive either using the provider name is the config settings or by using DefaultConnectionFactory propery of Database class. Following statement helps to use SqlCe database instead of Sql Server</p>
<pre class="brush: csharp; title: ; notranslate">
Database.DefaultConnectionFactory =
	new SqlCeConnectionFactory(&quot;System.Data.SqlServerCe.4.0&quot;);
using (TaskContext taskContext = new TaskContext())
{
	//Code.
}
</pre>
<p>Model validations also supported by entity framework. I may cover them in another post.</p>
<p>Happy 2012 <img src='http://www.dotnetthoughts.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div class="betterrelated"><p><strong>Related content:</strong></p>
<ol><li> <a href="http://www.dotnetthoughts.net/2009/10/07/how-to-store-and-retrieve-files-from-sql-server-database/" title="Permanent link to How to Store and Retrieve files from SQL Server Database">How to Store and Retrieve files from SQL Server Database</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2011/06/30/how-to-use-taskdialog-api-in-c/" title="Permanent link to How to use TaskDialog API in C#">How to use TaskDialog API in C#</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2009/10/22/implementing-custom-paging-in-datarepeater-using-c-and-sql-server/" title="Permanent link to Implementing Custom Paging in DataRepeater using C# and SQL Server">Implementing Custom Paging in DataRepeater using C# and SQL Server</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2011/02/22/quick-introduction-to-sqlite-with-c/" title="Permanent link to Quick introduction to SQLite with C#">Quick introduction to SQLite with C#</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2010/11/25/raven-db-introduction/" title="Permanent link to Raven DB &#8211; Introduction">Raven DB &#8211; Introduction</a>  </li>
</ol></div>]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2012/01/01/introduction-to-code-first-development-with-entity-framework/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>How to use TaskDialog API in C#</title>
		<link>http://www.dotnetthoughts.net/2011/06/30/how-to-use-taskdialog-api-in-c/</link>
		<comments>http://www.dotnetthoughts.net/2011/06/30/how-to-use-taskdialog-api-in-c/#comments</comments>
		<pubDate>Thu, 30 Jun 2011 12:12:50 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[.Net 4.0]]></category>
		<category><![CDATA[Win 32 API]]></category>
		<category><![CDATA[Windows 7]]></category>
		<category><![CDATA[Windows Forms]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Task Dialog]]></category>
		<category><![CDATA[Task Dialog API]]></category>
		<category><![CDATA[WIN32 API]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=1730</guid>
		<description><![CDATA[The TaskDialog API replaces MessageBox. A message box is useful for prompting users for an acknowledgment, confirmation, or an answer to a yes or no question. Message boxes are popular because of the MessageBox function is convenient for developers to &#8230; <a href="http://www.dotnetthoughts.net/2011/06/30/how-to-use-taskdialog-api-in-c/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>The TaskDialog API replaces MessageBox. A message box is useful for prompting users for an acknowledgment, confirmation, or an answer to a yes or no question. Message boxes are popular because of the MessageBox function is convenient for developers to use. TaskDialog is the preferred API to use because it is similar to MessageBox but much more flexible. Previously, developers have created their own message box implementations when greater functionality was required. Unfortunately .Net framework doesn&#8217;t expose TaskDialog API directly; you need to use WIN32 api for it. Here is one Task dialog implementation in C#. Only limitation of Task Dialog API is it doesn&#8217;t supported by Windows operating systems less than Windows Vista.</p>
<p>Here is the API declarations.</p>
<pre class="brush: csharp; title: ; notranslate">
[DllImport(&quot;comctl32.dll&quot;, CharSet = CharSet.Unicode, EntryPoint = &quot;TaskDialog&quot;)]
static extern int TaskDialog(IntPtr hWndParent, IntPtr hInstance, String pszWindowTitle,
String pszMainInstruction, String pszContent, int dwCommonButtons,
IntPtr pszIcon, out TaskDialogResult pnButton);

//Dialog buttons
[Flags]
public enum TaskDialogButtons : int
{
    Ok = 0x0001,
    Cancel = 0x0008,
    Yes = 0x0002,
    No = 0x0004,
    Retry = 0x0010,
    Close = 0x0020
}

//Dialog Results
[Flags]
public enum TaskDialogResult : int
{
    IDOK = 1,
    IDCANCEL = 2,
    IDRETRY = 4,
    IDYES = 6,
    IDNO = 7,
    IDCLOSE = 8,
    NONE = 0
}

//Dialog Icons
[Flags]
public enum TaskDialogIcon
{
    Information = UInt16.MaxValue - 2,
    Warning = UInt16.MaxValue,
    Stop = UInt16.MaxValue - 1,
    Question = 0,
    SecurityWarning = UInt16.MaxValue - 5,
    SecurityError = UInt16.MaxValue - 6,
    SecuritySuccess = UInt16.MaxValue - 7,
    SecurityShield = UInt16.MaxValue - 3,
    SecurityShieldBlue = UInt16.MaxValue - 4,
    SecurityShieldGray = UInt16.MaxValue - 8
}
</pre>
<p>And here is my TaskDialog wrapper function.</p>
<pre class="brush: csharp; title: ; notranslate">
public static TaskDialogResult Show(IntPtr handle, string messageTitle, string mainTitle,
    string mainContent, TaskDialogButtons taskDialogButtons, TaskDialogIcon taskDialogIcon)
{
    TaskDialogResult buttonClicked = TaskDialogResult.IDCANCEL;
    TaskDialog(handle, IntPtr.Zero, messageTitle, mainTitle, mainContent,
        (int)taskDialogButtons, (IntPtr)(int)taskDialogIcon, out buttonClicked);
    return buttonClicked;
}
</pre>
<p>And here is the screen shot of Task Dialog running in my Windows 7 machine.</p>
<div id="attachment_1731" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.dotnetthoughts.net/wp-content/uploads/2011/06/taskdialog1.png"><img src="http://www.dotnetthoughts.net/wp-content/uploads/2011/06/taskdialog1-300x131.png" alt="Task Dialog - On Windows 7 machine" title="Task Dialog - On Windows 7 machine" width="300" height="131" class="size-medium wp-image-1731" /></a><p class="wp-caption-text">Task Dialog - On Windows 7 machine</p></div>
<div class="betterrelated"><p><strong>Related content:</strong></p>
<ol><li> <a href="http://www.dotnetthoughts.net/2010/08/25/how-to-disable-close-button-of-windows-forms-application/" title="Permanent link to How to disable Close button of Windows Forms Application">How to disable Close button of Windows Forms Application</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2010/09/26/how-to-make-a-form-stay-always-on-top/" title="Permanent link to How to make a form stay always on top">How to make a form stay always on top</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2010/06/21/custom-places-in-filedialog-box/" title="Permanent link to Custom Places in FileDialog box">Custom Places in FileDialog box</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2009/07/10/consuming-a-c-dll-in-c/" title="Permanent link to Consuming a C++ DLL in C#">Consuming a C++ DLL in C#</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2010/12/25/setting-an-application-on-top-other-windows-using-c/" title="Permanent link to Setting an application on top other windows using C#">Setting an application on top other windows using C#</a>  </li>
</ol></div>]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2011/06/30/how-to-use-taskdialog-api-in-c/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Developing a simple RSS Reader in C#.Net</title>
		<link>http://www.dotnetthoughts.net/2010/12/17/developing-a-simple-rss-reader-in-c-net/</link>
		<comments>http://www.dotnetthoughts.net/2010/12/17/developing-a-simple-rss-reader-in-c-net/#comments</comments>
		<pubDate>Sat, 18 Dec 2010 03:46:43 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[.Net 4.0]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[C#.Net]]></category>
		<category><![CDATA[RSS Reader]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=1286</guid>
		<description><![CDATA[Yesterday one of my ex-colleague asked me how RSS feeds works and how to parse it in .Net Framework. I think helped him to get an idea about how RSS works. For the second one I started searching and I &#8230; <a href="http://www.dotnetthoughts.net/2010/12/17/developing-a-simple-rss-reader-in-c-net/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">Yesterday one of my ex-colleague asked me how RSS feeds works and how to parse it in .Net Framework. I think helped him to get an idea about how RSS works. For the second one I started searching and I found the one way using XML document classes. Then I come to know the inbuilt classes for syndication in .Net Framework, which comes under the System.ServiceModel.Syndication namespace.(If you are using .Net 3.5, you need to add reference of System.ServiceModel.Web.dll to get the namespace, and in .Net 4.0 it is under System.ServiceModel.dll)</p>
<p style="text-align: justify;">Here is a sample implementation, which displaying RSS feeds in a WPF application.</p>
<pre class="brush: csharp; title: ; notranslate">
private void cmdRead_Click(object sender, RoutedEventArgs e)
{
    WebClient client = new WebClient();
    client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
    client.DownloadStringAsync(new Uri(this.txtUrl.Text));
}

private void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    XmlReader reader = XmlReader.Create(new StringReader(e.Result));
    SyndicationFeed feed = SyndicationFeed.Load(reader);
    this.lstBox.ItemsSource = feed.Items;
}

private void linkUrl_Click(object sender, RoutedEventArgs e)
{
    string url = (e.Source as Hyperlink).NavigateUri.AbsoluteUri;
    Process.Start(url);
}
</pre>
<p>And here is the WPF &#8211; XAML </p>
<pre class="brush: xml; title: ; notranslate">
&lt;Window x:Class=&quot;RssReader.MainWindow&quot;
        xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
        Title=&quot;MainWindow&quot; Height=&quot;350&quot; Width=&quot;525&quot;&gt;
    &lt;Grid&gt;
        &lt;Grid.RowDefinitions&gt;
            &lt;RowDefinition Height=&quot;Auto&quot; /&gt;
            &lt;RowDefinition Height=&quot;*&quot; /&gt;
            &lt;RowDefinition Height=&quot;Auto&quot; /&gt;
        &lt;/Grid.RowDefinitions&gt;
        &lt;Grid Grid.Row=&quot;0&quot;&gt;
            &lt;Grid.ColumnDefinitions&gt;
                &lt;ColumnDefinition Width=&quot;Auto&quot; /&gt;
                &lt;ColumnDefinition Width=&quot;*&quot; /&gt;
                &lt;ColumnDefinition Width=&quot;Auto&quot; /&gt;
            &lt;/Grid.ColumnDefinitions&gt;
            &lt;TextBlock Grid.Column=&quot;0&quot;&gt;URL&lt;/TextBlock&gt;
            &lt;TextBox Name=&quot;txtUrl&quot; Grid.Column=&quot;1&quot; /&gt;
            &lt;Button Content=&quot;Read&quot; Name=&quot;cmdRead&quot; Click=&quot;cmdRead_Click&quot; Grid.Column=&quot;2&quot; /&gt;
        &lt;/Grid&gt;
        &lt;ListBox Name=&quot;lstBox&quot; Grid.Row=&quot;1&quot;&gt;
            &lt;ListBox.ItemTemplate&gt;
                &lt;DataTemplate&gt;
                    &lt;StackPanel&gt;
                        &lt;TextBlock Text=&quot;{Binding Path=Title.Text}&quot; /&gt;
                        &lt;TextBlock TextAlignment=&quot;Justify&quot; Text=&quot;{Binding Path=Summary.Text}&quot; /&gt;

                        &lt;TextBlock&gt;
                            &lt;Hyperlink Name=&quot;linkUrl&quot; Click=&quot;linkUrl_Click&quot; NavigateUri=&quot;{Binding Path=Id}&quot;&gt;
                                &lt;Label Content=&quot;{Binding Path=Title.Text}&quot; &gt;&lt;/Label&gt;
                            &lt;/Hyperlink&gt;
                        &lt;/TextBlock&gt;
                    &lt;/StackPanel&gt;
                &lt;/DataTemplate&gt;
            &lt;/ListBox.ItemTemplate&gt;
        &lt;/ListBox&gt;
        &lt;StatusBar Grid.Row=&quot;2&quot;&gt;
            &lt;StatusBarItem Content=&quot;Welcome to RSS Reader&quot; /&gt;
        &lt;/StatusBar&gt;
    &lt;/Grid&gt;
&lt;/Window&gt;
</pre>
<p>This is a basic implementation, you can add more features like multiple urls, settings etc. You can developing a RSS client in silverlight with the same code, but the problem with silverlight is we require a crossdomainpolicy.xml file in the server. If the file is not found it will throw security exception. </p>
<p>Happy Programming.</p>
<div class="betterrelated"><p><strong>Related content:</strong></p>
<ol><li> <a href="http://www.dotnetthoughts.net/2008/04/22/hello-world-application-in-wpf/" title="Permanent link to Hello World Application in WPF">Hello World Application in WPF</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2008/12/08/gridsplitter-control-in-wpf/" title="Permanent link to Gridsplitter control in WPF">Gridsplitter control in WPF</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2008/06/23/menu-icons-in-wpf/" title="Permanent link to Menu Icons in WPF">Menu Icons in WPF</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2011/11/18/how-to-create-a-rss-feed-using-asp-net/" title="Permanent link to How to create a RSS feed using ASP.Net">How to create a RSS feed using ASP.Net</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2009/11/02/wpf-interoperability-with-windows-forms/" title="Permanent link to WPF interoperability with Windows Forms">WPF interoperability with Windows Forms</a>  </li>
</ol></div>]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2010/12/17/developing-a-simple-rss-reader-in-c-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Developing a Single Instance Application in C#</title>
		<link>http://www.dotnetthoughts.net/2010/10/05/developing-a-single-instance-application-in-c/</link>
		<comments>http://www.dotnetthoughts.net/2010/10/05/developing-a-single-instance-application-in-c/#comments</comments>
		<pubDate>Tue, 05 Oct 2010 10:09:10 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Windows Forms]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[C#.Net]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=1120</guid>
		<description><![CDATA[Sometimes you don’t want the user to run multiple instance of your application in the system. If you are using VB.Net, Visual Studio will give an option to do this in the Application Settings in Project properties. But this option &#8230; <a href="http://www.dotnetthoughts.net/2010/10/05/developing-a-single-instance-application-in-c/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Sometimes you don’t want the user to run multiple instance of your application in the system. </p>
<p>If you are using VB.Net, Visual Studio will give an option to do this in the Application Settings in Project properties.</p>
<div id="attachment_1124" class="wp-caption aligncenter" style="width: 397px"><a href="http://www.dotnetthoughts.net/wp-content/uploads/2010/10/VB_NET_SETTINGS.png"><img src="http://www.dotnetthoughts.net/wp-content/uploads/2010/10/VB_NET_SETTINGS.png" alt="VB NET Project Settings" title="VB NET Project Settings" width="387" height="203" class="size-full wp-image-1124" /></a><p class="wp-caption-text">VB NET Project Settings</p></div>
<p>But this option is not available in C#. This following small snippet will help you to avoid multiple instances running on the machine using C#.</p>
<pre class="brush: csharp; title: ; notranslate">
using System;
using System.Diagnostics;
using System.Windows.Forms;

namespace SampleApp
{
    static class Program
    {
        /// &lt;summary&gt;
        /// The main entry point for the application.
        /// &lt;/summary&gt;
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Process currentProcess = Process.GetCurrentProcess();
            Process[] processItems = Process.GetProcessesByName(currentProcess.ProcessName);
            foreach (Process item in processItems)
            {
                if (item.Id != currentProcess.Id)
                {
                    MessageBox.Show(&quot;Another instance running&quot;);
                    return;
                }
            }
            Application.Run(new Form1());
        }
    }
}
</pre>
<div class="betterrelated"><p><strong>Related content:</strong></p>
<ol><li> <a href="http://www.dotnetthoughts.net/2009/11/02/wpf-interoperability-with-windows-forms/" title="Permanent link to WPF interoperability with Windows Forms">WPF interoperability with Windows Forms</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2010/12/25/setting-an-application-on-top-other-windows-using-c/" title="Permanent link to Setting an application on top other windows using C#">Setting an application on top other windows using C#</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2010/09/01/create-uac-compatible-applications-in-net/" title="Permanent link to Create UAC Compatible applications in .NET">Create UAC Compatible applications in .NET</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2010/06/21/custom-places-in-filedialog-box/" title="Permanent link to Custom Places in FileDialog box">Custom Places in FileDialog box</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2011/11/12/how-redirect-output-from-a-console-application/" title="Permanent link to How redirect output from a console application">How redirect output from a console application</a>  </li>
</ol></div>]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2010/10/05/developing-a-single-instance-application-in-c/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 &#8230; <a href="http://www.dotnetthoughts.net/2010/06/22/customize-spellcheck-in-wpf-textbox/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></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; title: ; notranslate">
&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; title: ; notranslate">
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; title: ; notranslate">
//.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>
<div class="betterrelated"><p><strong>Related content:</strong></p>
<ol><li> <a href="http://www.dotnetthoughts.net/2008/06/24/context-menus-in-wpf/" title="Permanent link to Context menus in WPF">Context menus in WPF</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2008/06/23/shortcuts-keys-in-wpf-menu/" title="Permanent link to Shortcuts keys in WPF Menu">Shortcuts keys in WPF Menu</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2008/06/23/menu-icons-in-wpf/" title="Permanent link to Menu Icons in WPF">Menu Icons in WPF</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2008/04/22/hello-world-application-in-wpf/" title="Permanent link to Hello World Application in WPF">Hello World Application in WPF</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2007/04/17/font-enumeration-in-vbnet/" title="Permanent link to Font Enumeration in VB.Net">Font Enumeration in VB.Net</a>  </li>
</ol></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>

