<?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; Windows Forms</title>
	<atom:link href="http://www.dotnetthoughts.net/tag/windows-forms/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>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>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>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>How to check network available</title>
		<link>http://www.dotnetthoughts.net/2010/04/05/how-to-check-network-available/</link>
		<comments>http://www.dotnetthoughts.net/2010/04/05/how-to-check-network-available/#comments</comments>
		<pubDate>Mon, 05 Apr 2010 19:41:55 +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>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=828</guid>
		<description><![CDATA[Sometimes we require to check whether the network is available or not, normally when are trying to do an Updated version check from our application or invoking a third party web service or any looking for any licence information / registration details from website etc. This is a simple function which will return Network status [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes we require to check whether the network is available or not, normally when are trying to do an Updated version check from our application or invoking a third party web service or any looking for any licence information / registration details from website etc.</p>
<p>This is a simple function which will return Network status using Ping Class.</p>
<pre class="brush: csharp;">
using System.Net.NetworkInformation;
public bool IsNetworkAvailable()
{
	using (Ping ping = new Ping())
	{
		PingReply pingReply = ping.Send(&quot;www.google.com&quot;, 200);
		return pingReply.Status == IPStatus.Success;
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2010/04/05/how-to-check-network-available/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>Isolated Storage in C#</title>
		<link>http://www.dotnetthoughts.net/2010/02/03/isolated-storage-in-c/</link>
		<comments>http://www.dotnetthoughts.net/2010/02/03/isolated-storage-in-c/#comments</comments>
		<pubDate>Thu, 04 Feb 2010 01:30:54 +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>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=741</guid>
		<description><![CDATA[As I am working in a Windows Application, client asked about the Windows 7 and Windows Vista compatibility. As I was writing only managed code I was not worried about the compatibility and most of the time it was working fine. (I was using Windows Vista). Today evening one of my colleague was testing the [...]]]></description>
			<content:encoded><![CDATA[<p>As I am working in a Windows Application, client asked about the Windows 7 and Windows Vista compatibility. As I was writing only managed code I was not worried about the compatibility and most of the time it was working fine. (I was using Windows Vista). Today evening one of my colleague was testing the application on his Windows 7 machine, the application was crashing <img src='http://www.dotnetthoughts.net/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' />  After initial diagnostics I was able to find the solution, it was because of Tracing. I was using TextWriterTraceListener,from System.Diagnostics namespace, and the File was created in the application path.Because he installed the application in C:\Program Files\AppFolder, Windows was denied access to write the File. The easily solution was, Right Click on the Application, Select RUNAS option, select Administrator. The other solution was writing the Log File in some temporary location, and use it. Then I found some nice feature in .Net called Isolated Storage. It is helpful to Run your application by less privileged users. With these stores, you can read and write data that less trusted code cannot access and prevent the exposure of sensitive information that can be saved elsewhere on the file system. Data is stored in compartments that are isolated by the current user and by the assembly in which the code exists. Additionally, data can be isolated by domain. Roaming profiles can be used in conjunction with isolated storage so isolated stores will travel with the user&#8217;s profile.</p>
<p>We can access the Isolated Storage related classes from System.IO.IsolatedStorage namespace.</p>
<pre class="brush: csharp;">
//Getting the User scoped Store corresponding to the calling codes assembly identity.
//IsolatedStorageFile class provides basic functionality to create files or folders.
IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForAssembly();
//Checking whether Directory Exists. Directory.Exists will not work. Also do some wildcard
//search like &quot;dotnet*&quot; or &quot;dotnet?&quot;
string[] directories = isolatedStorageFile.GetDirectoryNames(&quot;dotnetthoughts&quot;);
//Creating the directory if it is not exists.
if (directories.Length == 0)
{
    isolatedStorageFile.CreateDirectory(&quot;dotnetthoughts&quot;);
}
//IsolatedStorageFileStream encapsulates stream, used to create files
IsolatedStorageFileStream isolatedStorageFileStream =
    new IsolatedStorageFileStream(@&quot;dotnetthoughts\\System.log&quot;,
        FileMode.OpenOrCreate, isolatedStorageFile);
//Writing the content to IsolatedStorage.
using (StreamWriter streamWriter = new StreamWriter(isolatedStorageFileStream))
{
    streamWriter.WriteLine(&quot;Hello Isolated Storage&quot;);
}
//Reading the contents from Isolated storage – If you try to read like this it will throw //exception.(Stream is not Readable)
using (StreamReader streamReader = new StreamReader(isolatedStorageFileStream))
{
    MessageBox.Show(streamReader.ReadToEnd());
}
isolatedStorageFileStream.Close();
isolatedStorageFile.Close();
</pre>
<p>There is some permission attributes too, which is used to grant code to access IsolatedStorage.</p>
<pre class="brush: csharp;">

[IsolatedStorageFilePermission(SecurityAction.Demand)]
static class Program
{
//Code
}
</pre>
<p>The IsolatedStorage can be used in Silverlight assemblies too, which will helps to access local file system from Silverlight. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2010/02/03/isolated-storage-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
