<?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; 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>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>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>
		<item>
		<title>Custom Places in FileDialog box</title>
		<link>http://www.dotnetthoughts.net/2010/06/21/custom-places-in-filedialog-box/</link>
		<comments>http://www.dotnetthoughts.net/2010/06/21/custom-places-in-filedialog-box/#comments</comments>
		<pubDate>Tue, 22 Jun 2010 04:06:18 +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[Windows 7]]></category>
		<category><![CDATA[Windows Forms]]></category>
		<category><![CDATA[C#.Net]]></category>
		<category><![CDATA[FileDialog]]></category>
		<category><![CDATA[VB.Net]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=925</guid>
		<description><![CDATA[If you ever tried to Open a File from Visual Studio, you may notice something like Projects Folder in the Open File Dialog. We can also implement the same functionality in our applications by using CustomPlaces collection property of FileDialog class. The OpenFileDialog and SaveFileDialog classes allow you to add folders to the CustomPlaces collection. [...]]]></description>
			<content:encoded><![CDATA[<p>If you ever tried to Open a File from Visual Studio, you may notice something like Projects Folder in the Open File Dialog.</p>
<div id="attachment_926" class="wp-caption aligncenter" style="width: 209px"><a href="http://www.dotnetthoughts.net/wp-content/uploads/2010/06/openfile_vs2010.png"><img class="size-full wp-image-926" title="Open File Dialog in Visual Studio" src="http://www.dotnetthoughts.net/wp-content/uploads/2010/06/openfile_vs2010.png" alt="Open File Dialog in Visual Studio" width="199" height="398" /></a><p class="wp-caption-text">Open File Dialog in Visual Studio</p></div>
<p>We can also implement the same functionality in our applications by using  CustomPlaces collection property of FileDialog class. The OpenFileDialog and SaveFileDialog classes allow you to add folders to the CustomPlaces collection.</p>
<pre class="brush: csharp;">
openFileDialog.CustomPlaces.Add(@&quot;C:\Users&quot;);
</pre>
<p>You can also specify GUID of Windows Vista known folder. Known Folder GUIDs are not case sensitive and are defined in the KnownFolders.h file in the Windows SDK. If the specified Known Folder is not present on the computer that is running the application, the Known Folder is not shown.</p>
<pre class="brush: csharp;">
openFileDialog.CustomPlaces.Add(@&quot;C:\Users&quot;);
//Desktop Folder
openFileDialog.CustomPlaces.Add(new Guid(&quot;B4BFCC3A-DB2C-424C-B029-7FE99A87C641&quot;));
//Downloads Folder
openFileDialog.CustomPlaces.Add(new Guid(&quot;374DE290-123F-4565-9164-39C4925E467B&quot;));
</pre>
<div id="attachment_929" class="wp-caption aligncenter" style="width: 417px"><a href="http://www.dotnetthoughts.net/wp-content/uploads/2010/06/openfile_custom.png"><img src="http://www.dotnetthoughts.net/wp-content/uploads/2010/06/openfile_custom.png" alt="Open File Dialog with Custom Places " title="Open File Dialog with Custom Places " width="407" height="479" class="size-full wp-image-929" /></a><p class="wp-caption-text">Open File Dialog with Custom Places </p></div>
<p>Note: This feature will not have any effect in Windows XP. Also you must set the AutoUpgradeEnabled to True(default) to enable this feature in Vista or Windows 7.</p>
<p>The following table lists few Windows Vista Known Folders and their associated Guid.  </p>
<ol>
<li>Contacts : 56784854-C6CB-462B-8169-88E350ACB882</li>
<li>ControlPanel : 82A74AEB-AEB4-465C-A014-D097EE346D63</li>
<li>Desktop : B4BFCC3A-DB2C-424C-B029-7FE99A87C641</li>
<li>Documents : FDD39AD0-238F-46AF-ADB4-6C85480369C7</li>
<li>Downloads : 374DE290-123F-4565-9164-39C4925E467B</li>
<li>Favorites : 1777F761-68AD-4D8A-87BD-30B759FA33DD</li>
<li>Fonts : FD228CB7-AE11-4AE3-864C-16F3910AB8FE</li>
<li>Music : 4BD8D571-6D19-48D3-BE97-422220080E43</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2010/06/21/custom-places-in-filedialog-box/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>System.InvalidOperationException – Cross-thread operation not valid</title>
		<link>http://www.dotnetthoughts.net/2010/02/05/system_invalidoperationexception_cross_thread_operation_not_valid/</link>
		<comments>http://www.dotnetthoughts.net/2010/02/05/system_invalidoperationexception_cross_thread_operation_not_valid/#comments</comments>
		<pubDate>Fri, 05 Feb 2010 19:54:58 +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[Windows Forms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Cross thread operation]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=763</guid>
		<description><![CDATA[System.InvalidOperationException &#8211; Cross-thread operation not valid: Control &#8216;xxxxx&#8217; accessed from a thread other than the thread it was created on. Normally we get this exception when we try to modify some control property from another thread. This is because when a program executes the operating system will assign a thread for the creation of UI [...]]]></description>
			<content:encoded><![CDATA[<p><em>System.InvalidOperationException &#8211; Cross-thread operation not valid: Control &#8216;xxxxx&#8217; accessed from a thread other than the thread it was created on</em>. Normally we get this exception when we try to modify some control property from another thread. This is because when a program executes the operating system will assign a thread for the creation of UI elements and for the changes of the UI. Only this thread has got the permission to change or control UI elements created. If you creates other threads with the help of Thread class from System.Threading namespace, doesn’t have enough privileges to change or control the UI elements of the Main thread. To resolve this issue, we need write delegates and need to invoke the methods from other threads using these delegates.</p>
<p>This sample code is doing some long operation in a separate thread and try to update the UI from the new thread.</p>
<pre class="brush: csharp;">

private void Form1_Load(object sender, EventArgs e)
{
    this.threadStart = new ThreadStart(LongProcess);
    this.thread = new Thread(this.threadStart);
    this.thread.Start();
}
private void LongProcess()
{
    for (int i = 0; i &lt; 100; i++)
    {
        Thread.Sleep(100);
        //This will throw an exception like this
        //System.InvalidOperationException - Cross-thread operation not valid:
        //Control 'textBox1' accessed from a thread other than the thread it was created on.
        this.textBox1.Text = i.ToString();
    }
}
</pre>
<p>And here is the source code which will fix the issue with delegates and Control.Invoke method</p>
<pre class="brush: csharp;">
private ThreadStart threadStart;
private Thread thread;
private delegate void UpdateTextDelegate(string text);
private void Form1_Load(object sender, EventArgs e)
{
    this.threadStart = new ThreadStart(LongProcess);
    this.thread = new Thread(this.threadStart);
    this.thread.Start();
}

private void LongProcess()
{
    for (int i = 0; i &lt; 100; i++)
    {
        Thread.Sleep(100);
        //This will resolve the cross thread invalid operation exception.
        this.UpdateText(i.ToString());
    }
}

private void UpdateText(string text)
{
    //Checks whether the called required to invoke the &quot;Invoke&quot; method.
    if (this.textBox1.InvokeRequired)
    {
        UpdateTextDelegate updateTextDelegate = new UpdateTextDelegate(UpdateText);
        //Calling the invoke method of the control with the parameter.
        this.textBox1.Invoke(updateTextDelegate, new object[] { text });
    }
    else
    {
        this.textBox1.Text = text;
    }
}
</pre>
<p>Thanks to Praveen for helping me out. Happing Coding <img src='http://www.dotnetthoughts.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>EDIT</strong>: In case WPF applications, we don&#8217;t have InvokeRequired property available for Controls. Instead we need to use Dispatcher.CheckAccess() method. We can rewrite the UpdateText method like the following</p>
<pre class="brush: csharp;">
private void UpdateText(string text)
{
if (this.textbox1.Dispatcher.CheckAccess())
{
    this.textbox1.Content = text;
}
else
{
UpdateTextDelegate updateTextHandler = new UpdateTextDelegate(UpdateText);
this.textbox1.Dispatcher.Invoke(updateTextHandler, new object[] { text });
}
}
</pre>
<p>Thanks to Sivadas for his valueable comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2010/02/05/system_invalidoperationexception_cross_thread_operation_not_valid/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>WPF interoperability with Windows Forms</title>
		<link>http://www.dotnetthoughts.net/2009/11/02/wpf-interoperability-with-windows-forms/</link>
		<comments>http://www.dotnetthoughts.net/2009/11/02/wpf-interoperability-with-windows-forms/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 16:33:51 +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[Windows Forms]]></category>
		<category><![CDATA[C#.Net]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=604</guid>
		<description><![CDATA[In October 24th 2009, I got a chance to attend MS Community Techdays at Trivandrum. One of the session was WPF interoperability with Windows Forms. By using this we can use WPF controls in Classic Windows based applications. For this you require a special control called &#8220;ElementHost&#8220;, if you developed any Windows based application in [...]]]></description>
			<content:encoded><![CDATA[<p>In October 24th 2009, I got a chance to attend MS Community Techdays at Trivandrum. One of the session was WPF interoperability with Windows Forms. By using this we can use WPF controls in Classic Windows based applications. For this you require a special control called &#8220;<strong>ElementHost</strong>&#8220;, if you developed any Windows based application in VS 2008, this control will be available under WPF interoperability tab. If you add this control to a Windows Form, Visual Studio will automatically updates the References list. It will add few more references like PresentationCore, PresentationFrameWork, UIAutomationProvider, WindowsBase, WindowsFormsIntegration. Then you can add a WPF User Control to a Windows Form.</p>
<ol>
<li> Create a Windows Application Project.</li>
<li>Right Click on the Project Node in the solution explorer, select Add New Item, and Select User Control(WPF) from Add New Item Dialog.</li>
<li>In the User Contol I wrote some code to change the Color on MouseMove and I wrote the click event in the Codebehind.</li>
<p>XAML Code</p>
<pre class="brush: xml;">
&lt;Grid&gt;
    &lt;Grid.Resources&gt;
        &lt;Style TargetType=&quot;Button&quot; x:Key=&quot;CustomButton&quot;&gt;
            &lt;Setter Property=&quot;FontSize&quot; Value=&quot;15&quot; /&gt;
            &lt;Style.Triggers&gt;
                &lt;Trigger Property=&quot;IsMouseOver&quot; Value=&quot;True&quot;&gt;
                    &lt;Setter Property=&quot;FontSize&quot; Value=&quot;20&quot; /&gt;
                &lt;/Trigger&gt;
            &lt;/Style.Triggers&gt;
        &lt;/Style&gt;
    &lt;/Grid.Resources&gt;
    &lt;Button Style=&quot;{StaticResource CustomButton}&quot;
            Content=&quot;Hello World&quot;
            Click=&quot;Button_Click&quot;&gt;
    &lt;/Button&gt;
&lt;/Grid&gt;
</pre>
<p>Code behind – C#</p>
<pre class="brush: csharp;">
private void Button_Click(object sender, RoutedEventArgs e)
{
	MessageBox.Show(&quot;WPF UserControl Event&quot;);
}
</pre>
<li>Build the Project.</li>
<li>Drag and Drop, ElementHost control from WPF interoperability tab.</li>
<li>You can Set the host the WPF usercontrol either by selecting Select Host Content from Smart Menu, or by Setting the Child Property in the Property List. (The control will be populated in the List only if you build the application, after you added the control.)</li>
<li>You can also do it in runtime by setting Child Property of the Element Host control.</li>
<pre class="brush: csharp;">
private void Form1_Load(object sender, EventArgs e)
{
        SampleWPFCtrl ctrl1 = new SampleWPFCtrl();
            this.elementHost1.Child = ctrl1;
}
</pre>
<div id="attachment_610" class="wp-caption alignnone" style="width: 311px"><img src="http://www.dotnetthoughts.net/wp-content/uploads/2009/11/wpf_screenshot.png" alt="WPF Usercontol Control in Windows Form" title="WPF Usercontol Control in Windows Form" width="301" height="301" class="size-full wp-image-610" /><p class="wp-caption-text">WPF Usercontol Control in Windows Form</p></div>
<p>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/2009/11/02/wpf-interoperability-with-windows-forms/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How to Store and Retrieve files from SQL Server Database</title>
		<link>http://www.dotnetthoughts.net/2009/10/07/how-to-store-and-retrieve-files-from-sql-server-database/</link>
		<comments>http://www.dotnetthoughts.net/2009/10/07/how-to-store-and-retrieve-files-from-sql-server-database/#comments</comments>
		<pubDate>Wed, 07 Oct 2009 07:41:48 +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[SQL Server]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Windows Forms]]></category>
		<category><![CDATA[C#.Net]]></category>
		<category><![CDATA[File to Database]]></category>
		<category><![CDATA[IIS 7]]></category>

		<guid isPermaLink="false">http://anuraj.wordpress.com/?p=417</guid>
		<description><![CDATA[The forum I joined recently got lot of queries like How to Save Images in the Database, How to save files in SQL Server, How read files from Database etc. So I thought of writing a post regarding this. Even though I am part of a Web project, I am doing some Windows applications for [...]]]></description>
			<content:encoded><![CDATA[<p>The forum I joined recently got lot of queries like How to Save Images in the Database, How to save files in SQL Server, How read files from Database etc. So I thought of writing a post regarding this. Even though I am part of a Web project, I am doing some Windows applications for the client. So I thought it will nice to brush-up the ASP.Net skills.</p>
<p>Here is the code. I am using SQL Server 2008, but I am not using FileStream for the current project, I already wrote a <a href="http://www.dotnetthoughts.net/2009/09/22/adding-and-reading-files-from-sql-server-2008-filestream/">post</a> to how to<br />
manage files with FileStream feature. In this post I am using nvarchar(MAX) datatype for storing the file content.</p>
<p><strong>Table Design</strong></p>
<pre class="brush: sql;">
CREATE TABLE [dbo].[tblFiles](
	[FileId] [uniqueidentifier] NOT NULL,
	[Filename] [nvarchar](255) NOT NULL,
	[FileContent] [varbinary](max) NULL
)
</pre>
<p>And the I set FileId default to newId() and FileContent default to NULL</p>
<pre class="brush: sql;">
ALTER TABLE [dbo].[tblFiles] ADD  CONSTRAINT [DF_tblFiles_FileId]  DEFAULT (newid()) FOR [FileId]
GO
ALTER TABLE [dbo].[tblFiles] ADD  CONSTRAINT [DF_tblFiles_FileContent]  DEFAULT (NULL) FOR [FileContent]
GO
</pre>
<p>I wrote the code in C#. I am having a Asp FileUpload control and a button to upload the file, and a Repeater control with two controls, a label for displaying the filename and hyper link control for downloading the file.</p>
<pre class="brush: xml;">
&lt;body&gt;
&lt;form runat=&quot;server&quot;&gt;
&lt;asp:FileUpload runat=&quot;server&quot; ID=&quot;fileUploadImage&quot; /&gt;
&lt;asp:Button runat=&quot;server&quot; ID=&quot;cmdUpload&quot; Text=&quot;Upload File&quot; OnClick=&quot;cmdUpload_Click&quot; /&gt;
&lt;asp:Repeater runat=&quot;server&quot; ID=&quot;rptrFiles&quot;&gt;
    &lt;HeaderTemplate&gt;
        &lt;table&gt;
    &lt;/HeaderTemplate&gt;
    &lt;ItemTemplate&gt;
        &lt;tr&gt;
            &lt;td&gt;
                &lt;asp:Label runat=&quot;server&quot; ID=&quot;lblFilename&quot; Text='&lt;%# Eval(&quot;FileName&quot;)%&gt;' /&gt;
            &lt;/td&gt;
            &lt;td&gt;
              &lt;asp:HyperLink runat=&quot;server&quot; Target=&quot;_blank&quot; ID=&quot;lbtDownload&quot; Text=&quot;Download&quot; NavigateUrl='&lt;%# &quot;Download.aspx?File=&quot;  + Eval(&quot;FileId&quot;).ToString() %&gt;' /&gt;
            &lt;/td&gt;
        &lt;/tr&gt;
    &lt;/ItemTemplate&gt;
    &lt;FooterTemplate&gt;
        &lt;/table&gt;
    &lt;/FooterTemplate&gt;
&lt;/asp:Repeater&gt;
&lt;/form&gt;
&lt;/body&gt;
</pre>
<p><strong>Uploading the File to the Database</strong><br />
Code behind</p>
<pre class="brush: csharp;">
protected void cmdUpload_Click(object sender, EventArgs e)
{
    string fileName = Path.GetFileName(this.fileUploadImage.FileName);
    byte[] fileContent = this.fileUploadImage.FileBytes;
    using (SqlConnection connection = new SqlConnection(&quot;Server=.\\SQLEXPRESS;User Id=sa;Password=sapassword;Database=sampledb&quot;))
    {
        connection.Open();
        using (SqlCommand command = new SqlCommand(&quot;INSERT INTO tblFiles(Filename, FileContent) VALUES(@Filename, @FileContent)&quot;, connection))
        {
            SqlParameter fileNameParameter = new SqlParameter(&quot;@Filename&quot;, System.Data.SqlDbType.NVarChar, 255);
            fileNameParameter.Value = fileName;
            SqlParameter fileContentParameter = new SqlParameter(&quot;@FileContent&quot;, System.Data.SqlDbType.VarBinary);
            fileContentParameter.Value = fileContent;
            command.Parameters.AddRange(new SqlParameter[] { fileNameParameter, fileContentParameter });
            command.ExecuteNonQuery();
        }
    }
}
</pre>
<p>And here is code to bind the repeater from the Database</p>
<pre class="brush: csharp;">
DataTable dtFiles = new DataTable(&quot;Files&quot;);
using (SqlDataAdapter adapter = new SqlDataAdapter(&quot;SELECT FileId, FileName FROM tblFiles&quot;, &quot;Server=.\\SQLEXPRESS;User Id=sa;Password=sapassword;Database=sampledb&quot;))
{
    adapter.Fill(dtFiles);
}
this.rptrFiles.DataSource = dtFiles;
this.rptrFiles.DataBind();
</pre>
<p><strong>Download / Read the file from Database</strong><br />
And to download / read the file from Database, I am passing the File unique id to another page(download.aspx).I this page I am checking for the File querysting and based on that reading filecontent from Sql and writing it to Asp.net output stream. You can get more information about how to download files from IIS in this <a href="http://www.dotnetthoughts.net/2007/05/06/download-files-from-iis-server-using-aspnet/">post</a>.</p>
<pre class="brush: csharp;">
protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString[&quot;File&quot;] != null)
    {
        string fileId = Request.QueryString[&quot;File&quot;];
        using (SqlConnection connection = new SqlConnection(&quot;Server=.\\SQLEXPRESS;User Id=sa;Password=sapassword;Database=Sample&quot;))
        {
            connection.Open();
            using (SqlCommand command = new SqlCommand(&quot;SELECT Filename, FileContent FROM tblFiles WHERE FileId = @FileId&quot;, connection))
            {
                command.Parameters.AddWithValue(&quot;@FileId&quot;, fileId);
                SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
                if (reader.HasRows)
                {
                    reader.Read();
                    byte[] content = reader[&quot;FileContent&quot;] as byte[];
                    string filename = reader[&quot;FileName&quot;].ToString();
                    Response.Clear();
                    Response.ClearContent();
                    Response.AddHeader(&quot;Content-Disposition&quot;, &quot;attachment; filename=&quot; + filename);
                    Response.AddHeader(&quot;Content-Length&quot;, content.Length.ToString());
                    Response.OutputStream.Write(content, 0, content.Length);
                    Response.End();
                }
            }
        }
    }
}
</pre>
<p>Please write to me if I missed something. Happy Programming .</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2009/10/07/how-to-store-and-retrieve-files-from-sql-server-database/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Consuming a C++ DLL in C#</title>
		<link>http://www.dotnetthoughts.net/2009/07/10/consuming-a-c-dll-in-c/</link>
		<comments>http://www.dotnetthoughts.net/2009/07/10/consuming-a-c-dll-in-c/#comments</comments>
		<pubDate>Fri, 10 Jul 2009 09:41:24 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Win 32 API]]></category>
		<category><![CDATA[Windows Forms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Interop]]></category>
		<category><![CDATA[RegSvr]]></category>

		<guid isPermaLink="false">http://anuraj.wordpress.com/?p=323</guid>
		<description><![CDATA[While working on my current project, I had to use some low level I/O operations, but it was difficult using C#, and I got some C++ implementations. Then I thought of creating a DLL in C++ and use it in C#, but I didn&#8217;t get any code for the implementation. So I done some searching [...]]]></description>
			<content:encoded><![CDATA[<p>While working on my current project, I had to use some low level I/O operations, but it was difficult using C#, and I got some C++ implementations. Then I thought of creating a DLL in C++ and use it in C#, but I didn&#8217;t get any code for the implementation. So I done some searching and I found a solution. It is not a complete solution, but it works <img src='http://www.dotnetthoughts.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>Creating a DLL using C++</strong><br />
For creating a DLL in C++, I was used cl.exe, which comes with .net framework. For the implementation I just wrote simple C++ file.(Simple.cpp)</p>
<pre class="brush: cpp;">
#include &lt;iostream&gt;

extern &quot;C&quot; __declspec(dllexport) char* Hello();
char* Hello()
{
	return &quot;Hello world&quot;;
}
</pre>
<p>I think this is pretty much clear.The extern &#8220;C&#8221; __declspec(dllexport) allows generate export names automatically. For more details :<a href="http://msdn.microsoft.com/en-us/library/a90k134d(VS.80).aspx" target="_blank">Exporting from a DLL Using __declspec(dllexport)(MSDN)</a></p>
<p>After creating this Simple.cpp file, go to Visual Studio Tools &gt; Visual Studio 2008 Command Prompt. Go to the location where you have stored the Simple.cpp file and for compiling and linking C++ file you can use &#8220;cl.exe /LD Simple.cpp&#8221;.(For more details about cl.exe options checkout : <a href="http://msdn.microsoft.com/en-us/library/fwkeyyhe(VS.71).aspx" target="_blank">Compiler Options Listed Alphabetically(MSDN)</a> It will compile and Link, and gives a DLL as output.</p>
<p><strong>Consuming a C++ library in C#</strong><br />
When I try to add the DLL by Add Reference, Visual Studio will not allows to add C++ library as Reference. So I tried it with Interop option, by using DLLImportAttribute.</p>
<pre class="brush: csharp;">
[DllImport(@&quot;D:\Simple.dll&quot;, EntryPoint = &quot;Hello&quot;)]
public extern static string Hello();
</pre>
<p>Then you can call this function in C# like the following</p>
<pre class="brush: csharp;">
private void button1_Click(object sender, EventArgs e)
{
            MessageBox.Show(Hello());
}
</pre>
<p>It will display a Messagebox with &#8220;Hello World&#8221;. Thats it you consumed a C++ DLL in C#.</p>
<p><strong>Issue in the implementation</strong></p>
<ol>
<li>I can&#8217;t use the DllImport function without the full location. To avoid this I tried to Register the DLL using RegSvr32.But I got some error from RegSvr like this.</li>
<blockquote><p>The module &#8220;D:\Simple.dll&#8221; was loaded but the entry-point DllRegisterServer was not found.</p>
<p>Make sure that &#8220;D:\Simple.dll&#8221; is a valid DLL or OCX file and then try again.</p></blockquote>
</ol>
<p>I still exploring the things, I will update once I got the solution for this. 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/2009/07/10/consuming-a-c-dll-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
