<?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"
	>

<channel>
	<title>Programming Tutorial On The Way</title>
	<atom:link href="http://funcode.org/feed" rel="self" type="application/rss+xml" />
	<link>http://funcode.org</link>
	<description>free online programming resource on dotnet, csharp, web related topics</description>
	<pubDate>Tue, 02 Sep 2008 15:58:36 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.6.1</generator>
	<language>en</language>
			<item>
		<title>Use Boolean Variables For CheckBox Values</title>
		<link>http://funcode.org/article/visual-basic/use-boolean-variables-for-checkbox-values.aspx</link>
		<comments>http://funcode.org/article/visual-basic/use-boolean-variables-for-checkbox-values.aspx#comments</comments>
		<pubDate>Tue, 02 Sep 2008 15:58:36 +0000</pubDate>
		<dc:creator>kar</dc:creator>
		
		<category><![CDATA[Visual Basic]]></category>

		<category><![CDATA[Boolean]]></category>

		<category><![CDATA[CheckBox]]></category>

		<category><![CDATA[WinForm]]></category>

		<guid isPermaLink="false">http://funcode.org/?p=217</guid>
		<description><![CDATA[Visual Basic specifies a Boolean’s default values as zero for False and -1 for True. You may save and set the value of a check box, based on the absolute value of a Boolean variable, as these correspond to the intrinsic constants vbUnchecked and vbChecked:


Dim bBool as Boolean
bBool = True
'//If bBool = 0 the checkbox [...]]]></description>
			<content:encoded><![CDATA[<p>Visual Basic specifies a Boolean’s default values as zero for <span class="code">False</span> and -1 for <span class="code">True</span>. You may save and set the value of a check box, based on the absolute value of a Boolean variable, as these correspond to the intrinsic constants vbUnchecked and vbChecked:<br />
<span id="more-217"></span></p>
<pre>
<span class="code">Dim</span> bBool <span class="code">as Boolean</span><br />
bBool = <span class="code">True</span><br />
'//If bBool = 0 the checkbox will be<br />
'//unchecked, if it is anything else it will<br />
'//be checked.<br />
Check1.Value = <span class="code">Abs</span>(bBool)</p>
<pre>
]]></content:encoded>
			<wfw:commentRss>http://funcode.org/article/visual-basic/use-boolean-variables-for-checkbox-values.aspx/feed</wfw:commentRss>
		</item>
		<item>
		<title>Display Horizontal Scrollbar in ListBox</title>
		<link>http://funcode.org/article/visual-basic/display-horizontal-scrollbar-in-listbox.aspx</link>
		<comments>http://funcode.org/article/visual-basic/display-horizontal-scrollbar-in-listbox.aspx#comments</comments>
		<pubDate>Tue, 02 Sep 2008 15:02:44 +0000</pubDate>
		<dc:creator>kar</dc:creator>
		
		<category><![CDATA[Visual Basic]]></category>

		<category><![CDATA[ListBox]]></category>

		<category><![CDATA[Scrollbar]]></category>

		<category><![CDATA[WinForm]]></category>

		<guid isPermaLink="false">http://funcode.org/?p=215</guid>
		<description><![CDATA[Unlike the Windows 95 common controls, the standard list box doesn’t have a horizontal scrollbar when list items are too wide to fit within the list box. Fortunately, it’s not hard to direct a listbox control to display a horizontal scrollbar. Add this code to a form’s Load event. It fills a list box with [...]]]></description>
			<content:encoded><![CDATA[<p>Unlike the Windows 95 common controls, the standard list box doesn’t have a horizontal scrollbar when list items are too wide to fit within the list box. Fortunately, it’s not hard to direct a listbox control to display a horizontal scrollbar. Add this code to a form’s Load event. It fills a list box with 100 long strings and calls SetHScroll to show a horizontal scrollbar in the list box:</p>
<pre>
<span class="code">Private Sub</span> Form_Load()
	<span class="code">Dim</span> i <span class="code">As Integer</span>
	<span class="code">For</span> i = 1 <span class="code">To</span> 100
		List1.AddItem CStr(i) &#038; _
			" bottle(s) of beer on the wall."
	<span class="code">Next</span> i
	SetHScroll <span class="code">Me</span>, List1, List1.List(0)
<span class="code">End Sub</span>
</pre>
<p><span id="more-215"></span></p>
<p>Add this code, which includes the required API declarations and the SetHScroll routine, to a BAS module. The <em>SetHScroll</em> routine uses the <em>SendMessage</em> API function to send the LB_SETHORIZONTALEXTENT message to a list box. The last argument is an item from the list, preferably one of the longest items. SetHScroll determines the string’s width in pixels and passes this value to the list box along with the LB_SETHORIZONTALEXTENT message. The list box sets its horizontal extent to this value, and if it is wider than the list-box control, the list box displays a horizontal scrollbar:</p>
<pre>
<span class="code">#If</span> Win32 <span class="code">Then</span>
<span class="code">Declare Function</span> SendMessage Lib "user32" _
	<span class="code">Alias</span> "SendMessageA" ( _
	<span class="code">ByVal</span> hwnd <span class="code">As Long</span>, <span class="code">ByVal</span> wMsg <span class="code">As Long</span>, _
	<span class="code">ByVal</span> wParam <span class="code">As Long</span>, lParam <span class="code">As Long</span>) <span class="code">As Long</span>
<span class="code">#Else</span>
<span class="code">Declare Function</span> SendMessage Lib "user32" _
	<span class="code">Alias</span> “SendMessageA” ( _
	<span class="code">ByVal</span> hwnd <span class="code">As Integer</span>, <span class="code">ByVal</span> wMsg <span class="code">As Integer</span>, _
	<span class="code">ByVal</span> wParam <span class="code">As Integer</span>, lParam <span class="code">As Long</span>) <span class="code">As Long</span>
<span class="code">#End If</span>
'Define constant for message to list-box control
<span class="code">Const</span> LB_SETHORIZONTALEXTENT = &#038;H194
<span class="code">Public Sub</span> SetHScroll(Frm <span class="code">As</span> Form, Ctrl <span class="code">As</span> _
	Control, strText <span class="code">As String</span>)
	<span class="code">Dim</span> nScaleMode <span class="code">As Integer</span>
	<span class="code">Dim</span> nTextWidth <span class="code">As Integer</span>
	'Scale in pixels for window message
	nScaleMode = Frm.ScaleMode
	Frm.ScaleMode = 3
	'Get the width, in pixels, of the text string
	nTextWidth = Frm.TextWidth(strText)
	'Send a message to the list box
	SendMessage Ctrl.hwnd, _
		LB_SETHORIZONTALEXTENT, nTextWidth, 0
	'Restore previous scale mode
	Frm.ScaleMode = nScaleMode
<span class="code">End Sub</span>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://funcode.org/article/visual-basic/display-horizontal-scrollbar-in-listbox.aspx/feed</wfw:commentRss>
		</item>
		<item>
		<title>Get the True Member of An Option Array</title>
		<link>http://funcode.org/article/visual-basic/get-the-true-member-of-an-option-array.aspx</link>
		<comments>http://funcode.org/article/visual-basic/get-the-true-member-of-an-option-array.aspx#comments</comments>
		<pubDate>Mon, 01 Sep 2008 16:47:40 +0000</pubDate>
		<dc:creator>kar</dc:creator>
		
		<category><![CDATA[Visual Basic]]></category>

		<category><![CDATA[Option Array]]></category>

		<category><![CDATA[Tips]]></category>

		<category><![CDATA[WinForm]]></category>

		<guid isPermaLink="false">http://funcode.org/?p=209</guid>
		<description><![CDATA[Setting an element in an array of option buttons to True is easy. Click on the option button, or use this code:

OptionArray(ThisOne) = True

ThisOne is the Index of the member you want to be selected. Getting the True member of an option array is not so simple. Because you need to perform this kind of [...]]]></description>
			<content:encoded><![CDATA[<p>Setting an element in an array of option buttons to <span class="code">True</span> is easy. Click on the option button, or use this code:</p>
<pre>
OptionArray(ThisOne) = True
</pre>
<p><em>ThisOne</em> is the Index of the member you want to be selected. Getting the True member of an option array is not so simple. Because you need to perform this kind of task in almost any reasonably complex program, adding this function to your code library or generic module simplifies the task. You don’t need to know the array size in advance:<br />
<span id="more-209"></span></p>
<pre>
<span class="code">Function</span> OptionTrueIs(OptionArrayName <span class="code">As</span> _
	<span class="code">Variant</span>) <span class="code">As Integer</span>
	' Returns the index of the True
	' member of an option array
	<span class="code">Dim</span> Ctl <span class="code">as</span> Control
	<span class="code">For Each</span> Ctl <span class="code">in</span> OptionArrayName
		<span class="code">If</span> Ctl.Value = <span class="code">True Then</span>
			OptionTruels = Ctl.Index
			<span class="code">Exit For</span>
		<span class="code">End If</span>
	<span class="code">Next</span>
<span class="code">End Function</span>
</pre>
<p>You can use the routine to set a Public variable from a Properties sheet using this format:</p>
<pre>
SomePublicVariable = OptionTrueIs(SomeOptionArray())
</pre>
<p>Or use this code to save a program variable between runs:</p>
<pre>
SaveSetting("MyApp", "OptionSettings", _
	"OptionKey", OptionTrueIs(SomeOptionArray())
</pre>
<p>Load the routine using this code:</p>
<pre>
SomeOptionArray(GetSetting("MyApp", "", _
	"OptionSettings", "OptionKey",0))=<span class="code">True</span>
</pre>
<p>Or you can load the routine using this code:</p>
<pre>
SomePublicVariable = GetSetting("MyApp", "", _
	"OptionSettings", "OptionKey",0)
</pre>
<p>Use this code to control a Select Case structure:</p>
<pre>
<span class="code">Select Case</span> OptionTrueIs(SomeOptionArray())
	<span class="code">Case</span> 0:
	' This code will execute if element 0
	' of SomeOptionArray() is selected.
<span class="code">End Select</span>
</pre>
<p>Use this code to test a condition:</p>
<pre>
<span class="code">If</span> OptionTrueIs(SomeOptionArray()) = SomeValue Then
	' This code will execute if element
	' SomeValue of SomeOptionArray() is
	' selected.
<span class="code">End If</span>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://funcode.org/article/visual-basic/get-the-true-member-of-an-option-array.aspx/feed</wfw:commentRss>
		</item>
		<item>
		<title>Determine Which Option Buttons Have Been Selected</title>
		<link>http://funcode.org/article/visual-basic/determine-which-option-buttons-have-been-selected.aspx</link>
		<comments>http://funcode.org/article/visual-basic/determine-which-option-buttons-have-been-selected.aspx#comments</comments>
		<pubDate>Mon, 01 Sep 2008 16:38:09 +0000</pubDate>
		<dc:creator>kar</dc:creator>
		
		<category><![CDATA[Visual Basic]]></category>

		<category><![CDATA[Option Button]]></category>

		<category><![CDATA[Tips]]></category>

		<category><![CDATA[WinForm]]></category>

		<guid isPermaLink="false">http://funcode.org/?p=206</guid>
		<description><![CDATA[When attempting to determine which option buttons a user has selected from an array of option buttons, use this code instead of using an inefficient If-Then construct:

intSelectedItem = Option(0).Value * O - _
    Option(1).Value*1 - Option(2).Value * 2


If you have more than a few items, put this code in a loop:

intSelectedItems = [...]]]></description>
			<content:encoded><![CDATA[<p>When attempting to determine which option buttons a user has selected from an array of option buttons, use this code instead of using an inefficient <strong>If-Then</strong> construct:</p>
<pre>
intSelectedItem = Option(0).Value * O - _
    Option(1).Value*1 - Option(2).Value * 2
</pre>
<p><span id="more-206"></span><br />
If you have more than a few items, put this code in a loop:</p>
<pre>
intSelectedItems = 0
<span class="code">For</span> iCount = 0 <span class="code">to</span> N
  'N = total number of option boxes minus one
  intSelectedItem = - _
  Option(iCount).Value * iCount
<span class="code">Next</span>
</pre>
<p><em>intSelectedItem</em> is the index of the option button that the user selected.</p>
]]></content:encoded>
			<wfw:commentRss>http://funcode.org/article/visual-basic/determine-which-option-buttons-have-been-selected.aspx/feed</wfw:commentRss>
		</item>
		<item>
		<title>The stylish digital photo frame</title>
		<link>http://funcode.org/article/news/the-stylish-digital-photo-frame.aspx</link>
		<comments>http://funcode.org/article/news/the-stylish-digital-photo-frame.aspx#comments</comments>
		<pubDate>Fri, 29 Feb 2008 18:39:34 +0000</pubDate>
		<dc:creator>kar</dc:creator>
		
		<category><![CDATA[News]]></category>

		<guid isPermaLink="false">http://funcode.org/article/news/the-stylish-digital-photo-frame.aspx</guid>
		<description><![CDATA[
I am already has a digital camera, and now I am looking for digital photo frame. Well, I think many people have known this frame or maybe you already has one at your home. I like this frame because it’s more convenient and it looks beautiful at my home and my office. Beside that, it’s [...]]]></description>
			<content:encoded><![CDATA[<p><img id="image202" src="http://funcode.org/wp-content/uploads/2008/03/digital-photo-frame.jpg" alt="Digital Photo Frame" /><br />
I am already has a digital camera, and now I am looking for digital photo frame. Well, I think many people have known this frame or maybe you already has one at your home. I like this frame because it’s more convenient and it looks beautiful at my home and my office. Beside that, it’s an ideal gift for any occasion. Whether celebrating a wedding, birthday party or any happy event, it’s the perfect present as well as a fantastic way to display and remember the occasion. The slideshow function of the frame as it is like having an endless number of pictures at once. And I finally get my digital photo frame at Digitalframez.com.au.<br />
<span id="more-203"></span><br />
They provide <a href="http://www.digitalframez.com.au">digital photo frame</a> with unique and visually striking method for displaying your most treasured digital photos. With the digital photo frame you can play movie and audio files over and over again, all beautifully displayed inside your digital frame. All the frame that offer by them are high quality and easy to use. They give you the detail information of each frame includes the price, feature and the size. And now they have the special promotion, where you can get the free 256MB SD memory card with every 10 inch frame order. With the digital photo frame, now my home looks more fashionable and stylish. So I think you should get one too. You can visit the Digitalframez.com.au to know more information about this frame.</p>
]]></content:encoded>
			<wfw:commentRss>http://funcode.org/article/news/the-stylish-digital-photo-frame.aspx/feed</wfw:commentRss>
		</item>
		<item>
		<title>Waiting for All Threads in theThread Pool to Finish</title>
		<link>http://funcode.org/article/csharp/waiting-for-all-threads-in-thethread-pool-to-finish.aspx</link>
		<comments>http://funcode.org/article/csharp/waiting-for-all-threads-in-thethread-pool-to-finish.aspx#comments</comments>
		<pubDate>Fri, 15 Feb 2008 14:16:54 +0000</pubDate>
		<dc:creator>kar</dc:creator>
		
		<category><![CDATA[CSHARP]]></category>

		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://funcode.org/article/csharp/waiting-for-all-threads-in-thethread-pool-to-finish.aspx</guid>
		<description><![CDATA[For threads that are manually created via the Thread class, you can call the Join method to wait for a thread to finish. This works well when you need to wait for all threads to finish processing before an application terminates. Unfortunately, the thread pool threads do not have a Join method. You need to [...]]]></description>
			<content:encoded><![CDATA[<p>For threads that are manually created via the <span class="code">Thread</span> class, you can call the <span class="code">Join</span> method to wait for a thread to finish. This works well when you need to wait for all threads to finish processing before an application terminates. Unfortunately, the thread pool threads do not have a <span class="code">Join</span> method. You need to make sure that all threads in the thread pool have finished processing before another thread terminates or your application&#8217;s main thread terminates.</p>
<p>Use a combination of the <span class="code">ThreadPool</span> methods — <span class="code">GetMaxThreads</span> and <span class="code">GetAvailableThreads</span> — to determine when the <span class="code">ThreadPool</span> is finished processing the requests.<br />
<span id="more-201"></span><br />
This approach is a bit coarse; since the CLR does not allow access to the thread objects being created, the best we can do is to see when the <span class="code">ThreadPool</span> no longer has requests queued. If this approach is not sufficient for your needs, you could implement your own thread pool, but be careful of the many pitfalls that await you because thread pools are not easy to get right in all cases. Some of the issues are having too many or too few threads to service requests, determining initial levels of threads in the pool, and deadlocking threads.</p>
<pre>
<span class="code">public static void</span> Main()
{
    <span class="code">for</span> (<span class="code">int</span> i=0; i < 25; i++)
    {
        // have to wait or threadpool never gives out threads to requests
        Thread.Sleep(50);
        // queue thread request
        ThreadPool.QueueUserWorkItem(<span class="code">new</span> WaitCallback(ThreadProc), i);
    }
    // have to wait here or the background threads in the thread
    // pool would not run before the main thread exits.
    Console.WriteLine("Main Thread waiting to complete...");
    <span class="code">bool</span> working = <span class="code">true</span>;
    <span class="code">int</span> workerThreads = 0;
    <span class="code">int</span> completionPortThreads = 0;
    <span class="code">int</span> maxWorkerThreads = 0;
    <span class="code">int</span> maxCompletionPortThreads = 0;
    // get max threads in the pool
    ThreadPool.GetMaxThreads(out maxWorkerThreads,out maxCompletionPortThreads);
    <span class="code">while</span>(working)
    {
        // get available threads
        ThreadPool.GetAvailableThreads(<span class="code">out</span> workerThreads, <span class="code">out</span> completionPortThreads);
        <span class="code">if</span> (workerThreads == maxWorkerThreads)
        {
            // allow to quit
            working = <span class="code">false</span>;
        }
        <span class="code">else</span>
        {
            // sleep before checking again
            Thread.Sleep(500);
        }
    }
    Console.WriteLine("Main Thread completing...");
}
<span class="code">static void</span> ThreadProc(Object stateInfo)
{
    //show we did something with this thread...
    Console.WriteLine("Thread {0} running...", stateInfo);
    Thread.Sleep(1000);
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://funcode.org/article/csharp/waiting-for-all-threads-in-thethread-pool-to-finish.aspx/feed</wfw:commentRss>
		</item>
		<item>
		<title>Synchronizing the Reading and Writing of a Resource Efficiently</title>
		<link>http://funcode.org/article/csharp/synchronizing-the-reading-and-writing-of-a-resource-efficiently.aspx</link>
		<comments>http://funcode.org/article/csharp/synchronizing-the-reading-and-writing-of-a-resource-efficiently.aspx#comments</comments>
		<pubDate>Thu, 14 Feb 2008 16:14:58 +0000</pubDate>
		<dc:creator>kar</dc:creator>
		
		<category><![CDATA[CSHARP]]></category>

		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://funcode.org/article/csharp/synchronizing-the-reading-and-writing-of-a-resource-efficiently.aspx</guid>
		<description><![CDATA[Synchronizing the Reading and Writing of a Resource Efficiently
When you have a resource that is shared by multiple threads, you need to provide exclusive access to this resource when a thread is writing to it. However, you do not want the overhead of providing exclusive access to this resource when multiple threads are only reading [...]]]></description>
			<content:encoded><![CDATA[<p>Synchronizing the Reading and Writing of a Resource Efficiently</p>
<p>When you have a resource that is shared by multiple threads, you need to provide exclusive access to this resource when a thread is writing to it. However, you do not want the overhead of providing exclusive access to this resource when multiple threads are only reading from it. You want to allow one thread to access a shared resource only if it is writing to it, but you also want to allow multiple threads to read from this resource. While multiple threads can read from a resource, a write operation cannot occur while any thread is reading from this resource.</p>
<p>Example below uses the <span class="code">ReaderWriterLock</span> class from the <span class="code">System.Threading</span>. The <span class="code">ReaderWriterLock</span> is optimized for scenarios where you have data that changes infrequently but needs protection for those times when it is updated in a multithreading scenario. To illustrate, the <span class="code">GradeBoard</span> class represents a board where an instructor will post the grades students received from a class. Many students can read the grade board, but only the instructor can post a grade (write) to the grade board. Students will not, however, be able to read from the board while the instructor is updating it.<br />
<span id="more-200"></span></p>
<pre>
<span class="code">class</span> GradeBoard
{
    // make a static ReaderWriterLock to allow all student threads to check
    // grades and the instructor thread to post grades
    <span class="code">static</span> ReaderWriterLock readerWriter = <span class="code">new</span> ReaderWriterLock();

    // the grade to be posted
    <span class="code">static char</span> studentsGrade = ' ';

    <span class="code">static void</span> Main()
    {
        // create students
        Thread[] students = new Thread[5];
        <span class="code">for</span> (<span class="code">int</span> i=0; i &lt; students.Length; i++)
        {
            students[i] = <span class="code">new</span> Thread(<span class="code">new</span> ThreadStart(StudentThreadProc));
            students[i].Name = "Student " + i.ToString();
            // start the student looking for a grade
            students[i].Start();
        }

        // make those students "wait" for their grades by pausing the instructor
        Thread.Sleep(5000);

        // create instructor to post grade
        Thread instructor = <span class="code">new</span> Thread(<span class="code">new</span> ThreadStart(InstructorThreadProc));
        instructor.Name = "Instructor";
        // start instructor
        instructor.Start();

        // wait for instructor to finish
        instructor.Join();

        // wait for students to get grades
        <span class="code">for</span> (<span class="code">int</span> i=0;i &lt; students.Length;i++)
        {
            students[i].Join();
        }
    }

    <span class="code">static char</span> ReadGrade()
    {
        // wait ten seconds for the read lock
        readerWriter.AcquireReaderLock(10000);
        <span class="code">try</span>
        {
            // now we can read safely
            <span class="code">return</span> studentsGrade;
        }
        <span class="code">finally</span>
        {
            // Ensure that the lock is released.
            readerWriter.ReleaseReaderLock();
        }
    }

    <span class="code">static void</span> PostGrade(<span class="code">char</span> grade)
    {
        // wait ten seconds for the write lock
        readerWriter.AcquireWriterLock(10000);
        <span class="code">try</span>
        {
            // now we can post the grade safely
            studentsGrade = grade;
            Console.WriteLine("Posting Grade...");
        }
        <span class="code">finally</span>
        {
            // Ensure that the lock is released.
            readerWriter.ReleaseWriterLock();
        }
    }

    <span class="code">static void</span> StudentThreadProc()
    {
        <span class="code">bool</span> isGradeFound = <span class="code">false</span>;
        <span class="code">char</span> grade = ' ';
        <span class="code">while</span>(!isGradeFound)
        {
            grade = ReadGrade();
            <span class="code">if</span>(grade != ' ')
            {
                isGradeFound = <span class="code">true</span>;
                Console.WriteLine("Student Found Grade...");
            }
            <span class="code">else</span> // check back later
                Thread.Sleep(1000);
        }
    }

    <span class="code">static void</span> InstructorThreadProc()
    {
        // everyone likes an easy grader
        PostGrade('A');
    }
}
</pre>
<p>In the example, the <span class="code">ReaderWriterLock</span> protects access to the grade resource of the <span class="code">GradeBoard</span> class. Lots of students can be continually reading their grades using the <em>ReadGrade</em> method, but once the instructor attempts to post the grades using the <em>PostGrade</em> method, the grade resource is locked so that no one but the instructor can access it. The instructor updates the grades and releases the lock, and the pending student read requests are allowed to resume. All students continue to read the grade board, check to see if the grades have been posted, and then wait before making another request. Once the grades are posted, each student finds it, and the thread for that student terminates.</p>
<p>The <em>Main</em> method calls <span class="code">Join</span> on the instructor and student threads to wait until those threads finish before continuing and ending. If it did not do this, the program could potentially end before the threads finish. It protects against a <span class="code">ThreadInterruptedException</span>, as the <span class="code">Join</span> calls could potentially throw this if the thread aborts. The threads are named using the <em>Name</em> property to ease debugging.</p>
]]></content:encoded>
			<wfw:commentRss>http://funcode.org/article/csharp/synchronizing-the-reading-and-writing-of-a-resource-efficiently.aspx/feed</wfw:commentRss>
		</item>
		<item>
		<title>Determining Whether a Request for a Pooled Thread Will Be Queued</title>
		<link>http://funcode.org/article/csharp/determining-whether-a-request-for-a-pooled-thread-will-be-queued.aspx</link>
		<comments>http://funcode.org/article/csharp/determining-whether-a-request-for-a-pooled-thread-will-be-queued.aspx#comments</comments>
		<pubDate>Wed, 13 Feb 2008 17:05:57 +0000</pubDate>
		<dc:creator>kar</dc:creator>
		
		<category><![CDATA[CSHARP]]></category>

		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://funcode.org/article/csharp/determining-whether-a-request-for-a-pooled-thread-will-be-queued.aspx</guid>
		<description><![CDATA[The ThreadPool is a great way to perform background tasks without having to manage all aspects of the thread yourself. It can be handy to know when the ThreadPool itself is going to become a bottleneck to your application, and the GetAvailableThreads method can help you. However, you might want to check your application design [...]]]></description>
			<content:encoded><![CDATA[<p>The <span class="code">ThreadPool</span> is a great way to perform background tasks without having to manage all aspects of the thread yourself. It can be handy to know when the <span class="code">ThreadPool</span> itself is going to become a bottleneck to your application, and the <span class="code">GetAvailableThreads</span> method can help you. However, you might want to check your application design if you are consistently using this many threads as you might be losing performance due to contention or context switching. Queuing up work when the <span class="code">ThreadPoolM</span> is full simply queues it up for execution once one of the threads comes free; the request isn&#8217;t lost, just postponed.</p>
<p>In this example, your application will be creating many threads from the thread pool. When creating a thread from this pool, you want to be informed as to whether a thread in the pool is available or if none are available, and the request for a new thread will have to be queued. Basically, you want to know whether a thread is available for immediate use from the thread pool. Use the <span class="code">ThreadPool.GetAvailableThreads</span> method to get the number of worker threads currently available in the <span class="code">ThreadPool</span> to determine whether you should queue another request to launch another thread via <span class="code">ThreadPool.QueueUserWorkItem</span> or take an alternate action. The <em>Main</em> method calls a method (<span class="code">SpawnManyThreads</span>) to spawn lots of threads to do work in the <span class="code">ThreadPool</span>, then waits for a bit to simulate processing.<br />
<span id="more-199"></span></p>
<pre>
<span class="code">public class</span> TestThreads
{
    <span class="code">public static void</span> Main()
    {
        SpawnManyThreads();
        // have to wait here or the background threads in the thread
        // pool would not run before the main thread exits.
        Console.WriteLine("Main Thread waiting to complete...");
        Thread.Sleep(2000);
        Console.WriteLine("Main Thread completing...");
    }
...
}
</pre>
<p>The <span class="code">SpawnManyThreads</span> method launches threads and pauses between each launch to allow the <span class="code">ThreadPool</span> to register the request and act upon it. The <span class="code">isThreadAvailable</span> method is called with the parameter set to <span class="code">true</span> to determine whether there is a worker thread available for use in the <span class="code">ThreadPool</span>:</p>
<pre>
<span class="code">public static bool</span> SpawnManyThreads()
{
    <span class="code">try</span>
    {
        <span class="code">for</span> (<span class="code">int</span> i=0; i<500; i++)
        {
            // have to wait or threadpool never gives out threads to
            // requests
            Thread.Sleep(100);
            // check to see if worker threads are available in the pool
            <span class="code">if</span>(<span class="code">true</span> == isThreadAvailable(<span class="code">true</span>))
            {
                // launch thread if queue isn't full
                Console.WriteLine("Worker Thread was available...");
                ThreadPool.QueueUserWorkItem(<span class="code">new</span> WaitCallback(ThreadProc), i);
            }
            <span class="code">else</span>
                Console.WriteLine("Worker Thread was NOT available...");
        }
    }
    <span class="code">catch</span> (Exception e)
    {
        Console.WriteLine(e.ToString());
        <span class="code">return false</span>;
    }
    <span class="code">return true</span>;
}
</pre>
<p>The <span class="code">isThreadAvailable</span> method calls <span class="code">ThreadPool.GetAvailableThreads</span> to determine whether the ThreadPool has any available worker threads left. If you pass <span class="code">false</span> as the <em>checkWorkerThreads</em> parameter, it also sees whether there are any completion port threads available. The <span class="code">GetAvailableThreads</span> method compares the current number of threads allocated from the pool against the maximum <span class="code">ThreadPool</span> threads. The worker thread maximum is 25 per CPU, and the completion port thread maximum is 1,000 total, regardless of CPUs on v1.1 of the CLR.</p>
<pre>
<span class="code">public static bool</span> isThreadAvailable(<span class="code">bool</span> checkWorkerThreads)
{
    <span class="code">int</span> workerThreads = 0;
    <span class="code">int</span> completionPortThreads = 0;
    // get available threads
    ThreadPool.GetAvailableThreads(<span class="code">out</span> workerThreads, <span class="code">out</span> completionPortThreads);

    // indicate how many work threads are available
    Console.WriteLine("{0} worker threads available in thread pool.",
                            workerThreads);

    <span class="code">if</span> (checkWorkerThreads)
    {
        <span class="code">if</span>(workerThreads > 0)
            <span class="code">return true</span>;
    }
    <span class="code">else</span> // check completion port threads
    {
        <span class="code">if</span> (completionPortThreads > 0)
            <span class="code">return true</span>;
    }
    <span class="code">return false</span>;
}
</pre>
<p>This is a simple method to call in a threaded fashion:</p>
<pre>
...
<span class="code">static void</span> ThreadProc(Object stateInfo)
    {
        // show we did something with this thread
        Console.WriteLine("Thread {0} running...",stateInfo);
        Thread.Sleep(1000);
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://funcode.org/article/csharp/determining-whether-a-request-for-a-pooled-thread-will-be-queued.aspx/feed</wfw:commentRss>
		</item>
		<item>
		<title>Configuring a Timer</title>
		<link>http://funcode.org/article/csharp/configuring-a-timer.aspx</link>
		<comments>http://funcode.org/article/csharp/configuring-a-timer.aspx#comments</comments>
		<pubDate>Tue, 12 Feb 2008 16:16:02 +0000</pubDate>
		<dc:creator>kar</dc:creator>
		
		<category><![CDATA[CSHARP]]></category>

		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://funcode.org/article/csharp/configuring-a-timer.aspx</guid>
		<description><![CDATA[When using a System.Threading.Timers.Timer class, here are a few scenarios you may encounter:

You want to use a timer to call a timer callback method at a fixed time after the timer object has been created. Once this callback method has been called the first time, you want to call this same callback method at a [...]]]></description>
			<content:encoded><![CDATA[<p>When using a System.Threading.Timers.Timer class, here are a few scenarios you may encounter:</p>
<ul>
<li>You want to use a timer to call a timer callback method at a fixed time after the timer object has been created. Once this callback method has been called the first time, you want to call this same callback method at a specified interval (this interval might be different from the time interval between the creation of the timer and the first time the timer callback method is called).</li>
<li>You want to use a timer to call a timer callback method immediately upon creation of the <span class="code">System.Threading.Timer</span> object, after which the callback method is called at a specified interval.</li>
<li>You want to use a timer to call a timer callback method one time only.</li>
<li>You have been using a <span class="code">System.Threading.Timer</span> object and need to change the intervals at which its timer callback method is called.</li>
</ul>
<p>There are two types of <span class="code">Timer</span> classes in .NET Framework, one from <span class="code">System.Threading</span> and another one from <span class="code">System.Windows.Forms</span>. The former timer is enough to serve the earlier scenarios, but if you are doing UI work and want to use timers, you should investigate the <span class="code">System.Windows.Forms.Timer</span> class. If you are doing server work, you might also want to look at <span class="code">System.Threading.Timers.Timer</span> as well. Both of these classes add events for when the timers are disposed and when the timer &#8220;ticks&#8221;; they also add properties that expose the settings. Here we look at the Timer class of <span class="code">System.Threading.Timers</span> sample codes.<br />
<span id="more-198"></span><br />
To fire a <span class="code">System.Threading.Timer</span> after an initial delay, and then at a specified period after that, use the <span class="code">System.Threading.Timer</span> constructor to set up different times for the initial and following callbacks:</p>
<pre>
<span class="code">using</span> System;
<span class="code">using</span> System.Threading;

<span class="code">public class</span> TestTimers
{
    <span class="code">public static int</span> count = 0;
    <span class="code">public static</span> Timer timerRef = <span class="code">null</span>;

    <span class="code">public static void</span> Main()
    {
        TimerCallback callback = <span class="code">new</span> TimerCallback(TimerMethod);

        // Create a timer that waits one half second, then invokes
        // the callback every second thereafter.
        Timer timer = <span class="code">new</span> Timer(callback, <span class="code">null</span>,500, 1000);

        // store a reference to this timer so the callback can use it
        timerRef = timer;

        // The main thread does nothing until the timer is disposed.
        <span class="code">while</span> (timerRef != <span class="code">null</span>)
            Thread.Sleep(0);
        Console.WriteLine("Timer example done.");
    }

    <span class="code">static void</span> TimerMethod(Object state)
    {
        count++;
        <span class="code">if</span>(count == 5)
        {
            timerRef.Dispose();
            timerRef = <span class="code">null</span>;
        }
    }
}
</pre>
<p>The previous method showed how to fire the callback after 500 milliseconds. To fire the initial callback immediately, change the value to zero:</p>
<pre>
// Create a timer that doesn't wait, then invokes
// the callback every second thereafter.
Timer timer = <span class="code">new</span> Timer(callback, <span class="code">null</span>,0, 1000);
</pre>
<p>To have the timer call the callback only once, change the constructor to pass <span class="code">Timeout.Infinite</span> for the callback interval. You also have to change the current scheme that waits for five callbacks before disposing of the timer to do it the first time. If you didn&#8217;t do this, the program would hang since the Main function is still waiting for the timer to have <span class="code">Dispose</span> called, but the fifth callback will never trigger the <span class="code">Dispose</span> call:</p>
<pre>
        // Create a timer that waits for half a second, then is disposed
        Timer timer = <span class="code">new</span> Timer(callback, <span class="code">null</span>, 500, Timeout.Infinite);

// Also change this...to
    <span class="code">static void</span> TimerMethod(Object state)
    {
            timerRef.Dispose( );
            timerRef = <span class="code">null</span>;
    }
</pre>
<p>To change the interval of a running <span class="code">System.Threading.Timer</span>, call the <span class="code">Change</span> method specifying the delay before the next callback and the new callback interval, like this:</p>
<pre>
<span class="code">static void</span> TimerMethod(Object state)
{
    count++;
    <span class="code">if</span>(count == 5)
    {
        timerRef.Change(1000,2000);
    }
    <span class="code">if</span>(count == 10)
    {
        timerRef.Dispose();
        timerRef = <span class="code">null</span>;
    }
}
</pre>
<p>This code now checks for the fifth callback and changes the interval from one second to two seconds. The sixth callback will happen one second after, and then callbacks through ten will happen two seconds apart.</p>
]]></content:encoded>
			<wfw:commentRss>http://funcode.org/article/csharp/configuring-a-timer.aspx/feed</wfw:commentRss>
		</item>
		<item>
		<title>Encrypting/Decrypting a String</title>
		<link>http://funcode.org/article/csharp/encryptingdecrypting-a-string.aspx</link>
		<comments>http://funcode.org/article/csharp/encryptingdecrypting-a-string.aspx#comments</comments>
		<pubDate>Mon, 11 Feb 2008 14:28:40 +0000</pubDate>
		<dc:creator>kar</dc:creator>
		
		<category><![CDATA[CSHARP]]></category>

		<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://funcode.org/article/csharp/encryptingdecrypting-a-string.aspx</guid>
		<description><![CDATA[Encrypting the string will prevent users from being able to read and decipher the information. If you have a string you want to be able to encrypt and decrypt — perhaps a password or software key — which will be stored in some form accessible by users, such as in a file, the registry, or [...]]]></description>
			<content:encoded><![CDATA[<p>Encrypting the string will prevent users from being able to read and decipher the information. If you have a string you want to be able to encrypt and decrypt — perhaps a password or software key — which will be stored in some form accessible by users, such as in a file, the registry, or even a field, that may be open to attack from malicious code. The sample code in this article, <span class="code">CryptoString</span> class, contains two static methods to encrypt and decrypt a string and two static properties to retrieve the generated key and inititialization vector (IV—a random number used as a starting point to encrypt data) after encryption has occurred. </p>
<p>This class uses the <em>Rijndael algorithm</em> to encrypt and decrypt a string. This algorithm is found in the <span class="code">System.Security.Cryptography.RijndaelManaged</span> class. This algorithm requires a secret key and an initialization vector; both are byte arrays. A random secret key can be generated for you by calling the <span class="code">GenerateKey</span> method on the <span class="code">RijndaelManaged</span> class. This method accepts no parameters and returns void. The generated key is placed in the Key property of the <span class="code">RijndaelManaged</span> class. The <span class="code">GenerateIV</span> method generates a random initialization vector and places this vector in the IV property of the <span class="code">RijndaelManaged</span> class.<br />
<span id="more-197"></span></p>
<pre>
<span class="code">using</span> System;
<span class="code">using</span> System.Security.Cryptography;

<span class="code">public sealed class</span> CryptoString
{
    <span class="code">private</span> CryptoString() {}

    <span class="code">private static byte[]</span> savedKey = <span class="code">null</span>;
    <span class="code">private static byte[]</span> savedIV = <span class="code">null</span>;

    <span class="code">public static byte[]</span> Key
    {
        <span class="code">get</span> { <span class="code">return</span> savedKey; }
        <span class="code">set</span> { savedKey = <span class="code">value</span>; }
    }

    <span class="code">public static byte[]</span> IV
    {
        <span class="code">get</span> { <span class="code">return</span> savedIV; }
        <span class="code">set</span> { savedIV = <span class="code">value</span>; }
    }

    <span class="code">private static void</span> RdGenerateSecretKey(RijndaelManaged rdProvider)
    {
        <span class="code">if</span> (savedKey == <span class="code">null</span>)
        {
            rdProvider.KeySize = 256;
            rdProvider.GenerateKey();
            savedKey = rdProvider.Key;
        }
    }

    <span class="code">private static void</span> RdGenerateSecretInitVector(RijndaelManaged rdProvider)
    {
        <span class="code">if</span> (savedIV == <span class="code">null</span>)
        {
            rdProvider.GenerateIV();
            savedIV = rdProvider.IV;
        }
    }

    <span class="code">public static string</span> Encrypt(<span class="code">string</span> originalStr)
    {
        // Encode data string to be stored in memory
        <span class="code">byte[]</span> originalStrAsBytes = Encoding.ASCII.GetBytes(originalStr);
        <span class="code">byte[]</span> originalBytes = {};

        // Create MemoryStream to contain output
        MemoryStream memStream = <span class="code">new</span> MemoryStream(originalStrAsBytes.Length);

        RijndaelManaged rijndael = <span class="code">new</span> RijndaelManaged();

        // Generate and save secret key and init vector
        RdGenerateSecretKey(rijndael);
        RdGenerateSecretInitVector(rijndael);

        <span class="code">if</span> (savedKey == <span class="code">null</span> || savedIV == <span class="code">null</span>)
        {
            <span class="code">throw</span> (<span class="code">new</span> NullReferenceException(
                    "savedKey and savedIV must be non-null."));
        }

        // Create encryptor, and stream objects
        ICryptoTransform rdTransform = rijndael.CreateEncryptor((<span class="code">byte[]</span>)savedKey.
                            Clone( ),(<span class="code">byte[]</span>)savedIV.Clone());
        CryptoStream cryptoStream = <span class="code">new</span> CryptoStream(memStream, rdTransform,
                            CryptoStreamMode.Write);

        // Write encrypted data to the MemoryStream
        cryptoStream.Write(originalStrAsBytes, 0, originalStrAsBytes.Length);
        cryptoStream.FlushFinalBlock();
        originalBytes = memStream.ToArray();

        // Release all resources
        memStream.Close();
        cryptoStream.Close();
        rdTransform.Dispose();
        rijndael.Clear();

        // Convert encrypted string
        <span class="code">string</span> encryptedStr = Convert.ToBase64String(originalBytes);
        <span class="code">return</span> (encryptedStr);
    }

    <span class="code">public static string</span> Decrypt(<span class="code">string</span> encryptedStr)
    {
        // Unconvert encrypted string
        <span class="code">byte[]</span> encryptedStrAsBytes = Convert.FromBase64String(encryptedStr);
        <span class="code">byte[]</span> initialText = <span class="code">new</span> Byte[encryptedStrAsBytes.Length];

        RijndaelManaged rijndael = <span class="code">new</span> RijndaelManaged();
        MemoryStream memStream = <span class="code">new</span> MemoryStream(encryptedStrAsBytes);

        <span class="code">if</span> (savedKey == <span class="code">null</span> || savedIV == <span class="code">null</span>)
        {
            <span class="code">throw</span> (<span class="code">new</span> NullReferenceException(
                    "savedKey and savedIV must be non-null."));
        }

        // Create decryptor, and stream objects
        ICryptoTransform rdTransform = rijndael.CreateDecryptor((<span class="code">byte[]</span>)savedKey.
                            Clone(),(<span class="code">byte[]</span>)savedIV.Clone());
        CryptoStream cryptoStream = <span class="code">new</span> CryptoStream(memStream, rdTransform,
                            CryptoStreamMode.Read);

        // Read in decrypted string as a byte[]
        cryptoStream.Read(initialText, 0, initialText.Length);

        // Release all resources
        memStream.Close();
        cryptoStream.Close();
        rdTransform.Dispose();
        rijndael.Clear();

        // Convert byte[] to string
        <span class="code">string</span> decryptedStr = Encoding.ASCII.GetString(initialText);
        <span class="code">return</span> (decryptedStr);
    }
}
</pre>
<p>The byte array values in the <em>Key</em> and <em>IV</em> properties must be stored for later use and not modified. This is due to the nature of private-key encryption classes, such as <span class="code">RijndaelManaged</span>. The <em>Key</em> and <em>IV</em> values must be used by both the encryption and decryption routines to successfully encrypt and decrypt data.</p>
<p>The <em>SavedKey</em> and <em>SavedIV</em> private static fields contain the secret key and initialization vector, respectively. The secret key is used by the encryption and decryption methods to encrypt and decrypt data. This key must be used by both the encryption and decryption methods in order to successfully encrypt and then decrypt the data. This is why there are public properties for these values, so they can be stored somewhere secure for later use. This means that any strings encrypted by this object must be decrypted by this object. The initialization vector is used to prevent anyone from attempting to decipher the secret key.</p>
<p>There are two methods in the <span class="code">CryptoString</span> class, <span class="code">RdGenerateSecretKey</span> and <span class="code">RdGenerateSecretInitVector</span>, that are used to generate a secret key and initialization vector, when none exist. The <span class="code">RdGenerateSecretKey</span> method generates the secret key, which is placed in the <em>SavedKey</em> field. Likewise, the <span class="code">RdGenerateSecretInitVector</span> generates the initialization vector, which is placed in the <em>SavedIV</em> field. There is only one key and one <em>IV</em> generated for this class. This enables the encryption and decryption routines to have access to the same key and <em>IV</em> information at all times.</p>
<p>The <span class="code">Encrypt</span> and <span class="code">Decrypt</span> methods of the <span class="code">CryptoString</span> class do the actual work of encrypting and decrypting a string, respectively. The <span class="code">Encrypt</span> method accepts a string that you want to encrypt and returns an encrypted string. The following code calls this method and passes in a string to be encrypted:</p>
<pre>
<span class="code">string</span> encryptedString = CryptoString.Encrypt("MyPassword");
Console.WriteLine("encryptedString: " + encryptedString);
// get the key and IV used so you can decrypt it later
<span class="code">byte[]</span> key = CryptoString.Key;
<span class="code">byte[]</span> IV = CryptoString.IV;
</pre>
<p>Once the string is encrypted, the key and IV are stored for later decryption. This method displays:</p>
<pre>
encryptedString: Ah4vkmVKpwMYRT97Q8cVgQ==
</pre>
<p>The following code sets the key and IV used to encrypt the string, then calls the Decrypt method to decrypt the previously encrypted string:</p>
<pre>
CryptoString.Key = key;
CryptoString.IV = IV;
<span class="code">string</span> decryptedString = CryptoString.Decrypt(encryptedString);
Console.WriteLine("decryptedString: " + decryptedString);
</pre>
<p>This method displays:</p>
<pre>
decryptedString: MyPassword
</pre>
<p>There does not seem to be any problems with using escape sequences such as \r, \n, \r\n, or \t in the string to be encrypted. In addition, using a quoted string literal, with or without escaped characters, works without a problem:</p>
<pre>
@"MyPassword"
</pre>
]]></content:encoded>
			<wfw:commentRss>http://funcode.org/article/csharp/encryptingdecrypting-a-string.aspx/feed</wfw:commentRss>
		</item>
	</channel>
</rss>
