<?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>Bitmatic</title>
	<atom:link href="http://bitmatic.com/feed" rel="self" type="application/rss+xml" />
	<link>http://bitmatic.com</link>
	<description>Lean IT-solutions in .NET/C#</description>
	<lastBuildDate>Tue, 11 Jan 2011 09:37:39 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Redirecting MouseWheel events to another control</title>
		<link>http://bitmatic.com/c/redirecting-mousewheel-events-to-another-control</link>
		<comments>http://bitmatic.com/c/redirecting-mousewheel-events-to-another-control#comments</comments>
		<pubDate>Sun, 01 Nov 2009 12:42:36 +0000</pubDate>
		<dc:creator>Jakob</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[controls]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[native code]]></category>

		<guid isPermaLink="false">http://bitmatic.com/?p=478</guid>
		<description><![CDATA[Redirecting events from one control to another is quite easy. I recently needed it for an application that uses a number of ComboBoxes to filter data in a DataGridView. It was very confusing to the user when she selected an item in the ComboBox and subsequently tried using the mouse wheel to scroll through the [...]]]></description>
			<content:encoded><![CDATA[<p>Redirecting events from one control to another is quite easy. I recently needed it for an application that uses a number of ComboBoxes to filter data in a DataGridView. It was very confusing to the user when she selected an item in the ComboBox and subsequently tried using the mouse wheel to scroll through the data, that it would be the ComboBox, and not the DataGridView that would be scrolling.<br />
I decided to make a special ComboBox that would redirect Mouse wheel events to the DataGridView, instead of trying to fix it by manipulating focus. Manipulating focus gives you nothing but problems in my experience.</p>
<h3>The ComboBox with MouseWheel redirect</h3>
<p>The class i implemented for this solution just overrides the WndProc function, which handles all the messages sent to the control. It then reroutes mouse wheel events to another control (the reciever) through the Win32 API function SendMessage.<br />
That&#8217;s it&#8230;<br />
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">class</span> ComboBoxMWRedirect : ComboBox
{
    [DllImport(<span class="str">"user32.dll"</span>, CharSet = CharSet.Auto)]
    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">extern</span> IntPtr SendMessage(
        IntPtr hWnd,
        <span class="kwrd">int</span> message,
        IntPtr WParam,
        IntPtr LParam);

    <span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">int</span> WM_MOUSEWHEEL = 0x020A;
    <span class="kwrd">private</span> Control _reciever;

    <span class="rem">//needed for designer support</span>
    <span class="kwrd">private</span> ComboBoxMWRedirect() {}

    <span class="kwrd">public</span> ComboBoxMWRedirect(Control reciever)
    {
        _reciever = reciever;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> WndProc(<span class="kwrd">ref</span> Message message)
    {
        <span class="kwrd">if</span> (message.Msg == WM_MOUSEWHEEL)
        {
            <span class="rem">//route mouse wheel messages to the reciever</span>
            SendMessage(
                _reciever.Handle,
                message.Msg,
                message.WParam,
                message.LParam);
        }
        <span class="kwrd">else</span>
        {
            <span class="rem">//route all other messages on to the base class</span>
            <span class="kwrd">base</span>.WndProc(<span class="kwrd">ref</span> message);
        }
    }
}</pre>
<p>Now to have one of your ComboBoxes redirect the mouse wheel, just use one of these instead, and specify the recieving control when you call the constructor. If, for instance, i want to redirect to a DataGridView calle dataGridView1 i would construct the redirecting ComboBox like this:<br />
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
ComboBoxMWRedirect cb = <span class="kwrd">new</span> ComboBoxMWRedirect(dataGridView1);</pre>
<h3>Completely avoiding the event</h3>
<p>The code can also be used to avoid the Mouse wheel event altogether. Just change the WndProc overridde to the code below, and mouse wheel events will be ignored.<br />
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
<span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> WndProc(<span class="kwrd">ref</span> Message message)
{
    <span class="rem">//avoid mouse wheel events</span>
    <span class="kwrd">if</span> (message.Msg != WM_MOUSEWHEEL)
        <span class="kwrd">base</span>.WndProc(<span class="kwrd">ref</span> message);
}</pre>
<p>Overriding WndProc gives you a lot of power and control over what happens in your application. This particular (very limited) example handles MouseWheel events on a ComboBox, but you can really use this to do a lot of very powerful stuff, like disabling the keyboard or parts of it, routing messages to other controls, broadcasting messages to have several controls react to the same message, etc. etc.</p>
]]></content:encoded>
			<wfw:commentRss>http://bitmatic.com/c/redirecting-mousewheel-events-to-another-control/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Fixing the Logitech Setpoint &#8211; ActiveSync problems</title>
		<link>http://bitmatic.com/general/fixing-the-logitech-setpoint-activesync-problems</link>
		<comments>http://bitmatic.com/general/fixing-the-logitech-setpoint-activesync-problems#comments</comments>
		<pubDate>Fri, 30 Oct 2009 22:18:59 +0000</pubDate>
		<dc:creator>Jakob</dc:creator>
				<category><![CDATA[general]]></category>
		<category><![CDATA[ActiveSync]]></category>
		<category><![CDATA[Drivers]]></category>
		<category><![CDATA[Logitech]]></category>

		<guid isPermaLink="false">http://bitmatic.com/?p=487</guid>
		<description><![CDATA[Logitech&#8217;s SetPoint software is causing severe problems for people using ActiveSync to sync with their mobile devices. The incompatibility between SetPoint and ActiveSync causes programs running on the affected computer to loose focus for about half a second every four seconds or so &#8211; making it next to impossible to work on the computer. The [...]]]></description>
			<content:encoded><![CDATA[<p>Logitech&#8217;s SetPoint software is causing severe problems for people using ActiveSync to sync with their mobile devices.<br />
The incompatibility between SetPoint and ActiveSync causes programs running on the affected computer to loose focus for about half a second every four seconds or so &#8211; making it next to impossible to work on the computer.<br />
The problem seems to be caused by a Microosoft Outlook process that is started in the background by ActiveSync when ActiveSync tries to sync with the connected device. It is really between this background Outlook process and the Logitech SetPoint software the incompatibility lies. They have a really hard time existing at the same time.<br />
Luckily there are a few solutions.</p>
<h3>Solution 1 &#8211; Start Outlook before connecting the device</h3>
<p>This solution really is as simple as it sounds. If Outlook runs already when the device is plugged in ActiveSync will hook itself up to the existing Outlook instance which doesn&#8217;t cause the focus problems with SetPoint.<br />
For most users this will be the ideal solution, since most people that use Outlook as their mail/contacts/etc. program tends to have it running all the time anyway. In fact, many people are probably using this solution already without even knowing it making them happily unaware of how crappy a piece of software SetPoint really is.</p>
<h3>Solution 2 &#8211; Kill the Outlook.exe process</h3>
<p>This solution is admittedly not very elegant &#8211; but it will work.</p>
<ul>
<li>Plug in your device as normal</li>
<li>Wait for the device to stop syncing</li>
<li>Press Ctrl+Alt+Delete to open up the task manager</li>
<li>Select the &#8220;Processes&#8221; tab</li>
<li>Select the process called &#8220;OUTLOOK.EXE&#8221;</li>
<li>Hit &#8220;Kill Process&#8221;</li>
<li>Windows will complain and warn you about killing processes, but trust me &#8211; the problem will disappear</li>
</ul>
<p>This solution may seem very crude, but it is the one i usually end up doing when i need to sync to backup my contacts every once in a while.</p>
<h3>Solution 3 &#8211; Don&#8217;t sync anything</h3>
<ul>
<li>Setup ActiveSync to not sync anything with the device</li>
</ul>
<p>This solution is ideal for those of you that really only plugin the device to recharge it (like me most of the time). When ActiveSync is set up to not sync anything, it will actually still sync the clock, but the main thing is &#8211; it wont fire up the background Outlook process that is the source of the problem&#8230;. Problem solved &#8211; If you don&#8217;t need the sync&#8217;ing.</p>
<h3>Solution 4 &#8211; The proper solution</h3>
<p>Logitech and Microsoft call each other and solve the problem&#8230;.. <img src='http://bitmatic.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<h3>Wrapping it up</h3>
<p>I have presented a few solutions to this curious problem. A quick search of this problem on google will reveal numerous frustrated Logitech users dating back many years. It seems that neither Microsoft nor Logitech have any interest in solving this problem. It is a real shame since it has scared of people from buying Logitech products. They have some of the best hardware available on the market, but it is shamelessly ruined by poorly designed software.</p>
]]></content:encoded>
			<wfw:commentRss>http://bitmatic.com/general/fixing-the-logitech-setpoint-activesync-problems/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Fixing a slow scrolling DataGridView</title>
		<link>http://bitmatic.com/c/fixing-a-slow-scrolling-datagridview</link>
		<comments>http://bitmatic.com/c/fixing-a-slow-scrolling-datagridview#comments</comments>
		<pubDate>Sun, 25 Oct 2009 12:14:43 +0000</pubDate>
		<dc:creator>Jakob</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[controls]]></category>
		<category><![CDATA[DataGridView]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[Scroll]]></category>
		<category><![CDATA[VS2008]]></category>

		<guid isPermaLink="false">http://bitmatic.com/?p=476</guid>
		<description><![CDATA[Whenever your C#/.NET DataGridView reaches a certain size, it tends to get really slow to scroll. Depending on the speed of your computer this may be more or less noticeable. In an application i did for a client this became a real problem due to a combination of lots of DataGridView cells and fairly slow [...]]]></description>
			<content:encoded><![CDATA[<p>Whenever your C#/.NET DataGridView reaches a certain size, it tends to get really slow to scroll. Depending on the speed of your computer this may be more or less noticeable. In an application i did for a client this became a real problem due to a combination of lots of DataGridView cells and fairly slow computers.<br />
Luckily the solution turned out to be simple&#8230;</p>
<h3>Turn on double buffering</h3>
<p>Turning on double buffering seems to solve the problem. Normally double buffering would only help reduce flickering, since painting is being done to an off-screen buffer, but for the DataGridView it also significantly reduces the amount of functions being called internally in the DataGridView &#8211; thus reducing processor load and increasing speed. (statistics gathered with the <a href="http://www.eqatec.com/tools/tracer">Eqatec Tracer</a>)</p>
<h3>My DataGridView doesn&#8217;t have a DoubleBuffered property !?!?</h3>
<p>For some reason Microsoft has decided to hide the DoubleBuffered property from DataGridView. Luckily you can set it anyway with reflection.<br />
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> ExtensionMethods
{
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> DoubleBuffered(<span class="kwrd">this</span> DataGridView dgv, <span class="kwrd">bool</span> setting)
    {
        Type dgvType = dgv.GetType();
        PropertyInfo pi = dgvType.GetProperty(<span class="str">"DoubleBuffered"</span>,
            BindingFlags.Instance | BindingFlags.NonPublic);
        pi.SetValue(dgv, setting, <span class="kwrd">null</span>);
    }
}</pre>
<p>Just drop the above class into your project somewhere, or add the function to your existing extension methods.<br />
The extension method allows you to set the DoubleBuffered property on your DataGridView in the following manner:<br />
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
dataGridView1.DoubleBuffered(<span class="kwrd">true</span>);</pre>
<p>You now have a smooth scrolling DataGridView <img src='http://bitmatic.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://bitmatic.com/c/fixing-a-slow-scrolling-datagridview/feed</wfw:commentRss>
		<slash:comments>43</slash:comments>
		</item>
		<item>
		<title>Understanding thread priorities in C#</title>
		<link>http://bitmatic.com/c/understanding-thread-priorities-in-c</link>
		<comments>http://bitmatic.com/c/understanding-thread-priorities-in-c#comments</comments>
		<pubDate>Mon, 21 Sep 2009 20:14:57 +0000</pubDate>
		<dc:creator>Jakob</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[Threads]]></category>

		<guid isPermaLink="false">http://bitmatic.com/?p=434</guid>
		<description><![CDATA[Thread priorities in the .NET framework are more complex than many developers think. Setting Thread priority is more than just adjusting the ThreadPriority of a Thread. You also have to take into account the priority of the process to which the threads belong. The ProcessPriorityClass Setting ThreadPriority to one of the values possible with C# [...]]]></description>
			<content:encoded><![CDATA[<p>Thread priorities in the .NET framework are more complex than many developers think. Setting Thread priority is more than just adjusting the ThreadPriority of a Thread. You also have to take into account the priority of the process to which the threads belong.</p>
<h3>The ProcessPriorityClass</h3>
<p>Setting ThreadPriority to one of the values possible with C# will only shift the priority of the thread up and down within a class of priorities shared by the whole process. This means that even setting ThreadPriority to ThreadPriority.Highest will not actually give the thread a high priority, compared to the system processes. It will only give the thread a high priority compared to other threads belonging to comparable processes.<br />
I&#8221;l try to make it a bit clearer with this little css/ascii illustration <img src='http://bitmatic.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div style="width:100%;">
<div style="position:relative;left:15px;background:#a6ddea;width:465px;font-size:75%;">Full system priority range: 1-31</div>
<div style="position:relative;left:30px;background:#a6ddea;width:60px;font-size:75%;">Idle</div>
<div style="position:relative;left:60px;background:#a6ddea;width:60px;font-size:75%;">BelowNormal</div>
<div style="position:relative;left:90px;background:#a6ddea;width:60px;font-size:75%;">Normal</div>
<div style="position:relative;left:120px;background:#a6ddea;width:60px;font-size:75%;">AboveNormal</div>
<div style="position:relative;left:165px;background:#a6ddea;width:60px;font-size:75%;">High</div>
<div style="position:relative;left:330px;background:#a6ddea;width:60px;font-size:75%;">RealTime</div>
</div>
<p>In C# processes start with normal priority, so setting ThreadPriority.Highest under normal conditions wont make the thread higher priority than ThreadPriority.Lowest in a process running with a high priority class.</p>
<h3>Letting Windows know that you are really important.</h3>
<p>Take a look at this code:<br />
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
<span class="kwrd">class</span> Program
{
  <span class="kwrd">static</span> <span class="kwrd">void</span> Main(<span class="kwrd">string</span>[] args)
  {
    Thread t = <span class="kwrd">new</span> Thread(threadFunc);
    Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime;
    t.Priority = ThreadPriority.Highest;
    t.Start();
    Console.ReadLine();
    t.Abort();
  }

  <span class="kwrd">static</span> <span class="kwrd">void</span> threadFunc()
  {
    <span class="kwrd">while</span> (<span class="kwrd">true</span>) {}
  }
}</pre>
<p>This code will make a thread/process that has the highest possible priority you can set with C#. Luckily i have a dual-core processor &#8211; otherwise that code would have frozen my computer. Now it only uses up one of my cores frantically checking if true is still true&#8230;<br />
The magic here lies in assigning ProcessPriorityClass.RealTime to the current process. Note that this is done in a process-wide scope, and all the threads in the process will have their priorities adjusted to fit in the new priority range. You can not have threads with extremely high and extremely low priorities within the same process.</p>
<h3>It is really cool &#8211; but don&#8217;t abuse it.</h3>
<p>Do not run off and adjust the priorities of all your programs, to get the processing time they rightly deserve. Fixing problems by raising priorities are very often a symptom of some greater underlying problem in your code, and the correct way of fixing things are most often to remove the bottlenecks in your program, and leave the priorities alone. This holds especially true for ProcessPriorityClass.RealTime, since this will potentially block execution of critical system stuff like garbage collection or keyboard and mouse input.<br />
I would recommend against using anything higher than ProcessPriorityClass.High</p>
]]></content:encoded>
			<wfw:commentRss>http://bitmatic.com/c/understanding-thread-priorities-in-c/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Voluntary fall through in C# switch statements</title>
		<link>http://bitmatic.com/c/voluntary-fallthrough-in-c-switch-statements</link>
		<comments>http://bitmatic.com/c/voluntary-fallthrough-in-c-switch-statements#comments</comments>
		<pubDate>Fri, 28 Aug 2009 22:22:16 +0000</pubDate>
		<dc:creator>Jakob</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://bitmatic.com/?p=420</guid>
		<description><![CDATA[I used to use voluntary fall through a lot in switch statements in C and C++. In C# it is no longer as easy to do as before, since all cases of a C# switch are required to end with either break or goto. You can still do voluntary fall through. You just need to [...]]]></description>
			<content:encoded><![CDATA[<p>I used to use voluntary fall through a lot in switch statements in C and C++. In C# it is no longer as easy to do as before, since all cases of a C# switch are required to end with either break or goto. You can still do voluntary fall through. You just need to be very specific about it.</p>
<h3>Finally an excuse for using goto !!</h3>
<p>You can use the goto statement to jump from one case to another in a C# switch. Just replace the usual break statement with a goto pointing at the next case, and you have voluntary fallthrough.<br />
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
<span class="kwrd">int</span> i = 0;
<span class="kwrd">switch</span> (i)
{
  <span class="kwrd">case</span> 0:
    Console.Write(<span class="str">"Voluntary fallthrough "</span>);
    <span class="kwrd">goto</span> <span class="kwrd">case</span> 1;
  <span class="kwrd">case</span> 1:
    Console.Write(<span class="str">"is still "</span>);
    <span class="kwrd">goto</span> <span class="kwrd">default</span>;
  <span class="kwrd">default</span>:
    Console.Write(<span class="str">"possible"</span>);
    <span class="kwrd">break</span>;
}</pre>
<p>This code will print out &#8220;Voluntary fallthrough is still possible&#8221; on the console.</p>
<p>I have always been a big fan of goto statements&#8230; Not really because of their usefulness, but more because everyone is always hitting on them. It is a bit like cheering for the underdog in a football match, which i almost always do. I have had a principle of having at least 1 goto statement in all applications i have done for some years now, and with voluntary fall through i may actually have found a reasonable excuse for them <img src='http://bitmatic.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> .</p>
]]></content:encoded>
			<wfw:commentRss>http://bitmatic.com/c/voluntary-fallthrough-in-c-switch-statements/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>String &amp; StringBuilder performance in the Compact Framework</title>
		<link>http://bitmatic.com/c/string-stringbuilder-performance-in-the-compact-framework</link>
		<comments>http://bitmatic.com/c/string-stringbuilder-performance-in-the-compact-framework#comments</comments>
		<pubDate>Tue, 28 Jul 2009 17:01:48 +0000</pubDate>
		<dc:creator>Jakob</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Compact Framework]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[string]]></category>

		<guid isPermaLink="false">http://bitmatic.com/?p=395</guid>
		<description><![CDATA[Here&#8217;s a few general guidelines when working with strings: Don&#8217;t concatenate strings &#8211; use a StringBuilder instead Whenever possible initialize the StringBuilder with enough capacity to avoid re-allocations Excessive concatenation of strings will be several orders of magnitude slower than using a StringBuilder String.Format() &#038; StringBuilder.AppendFormat() are significantly slower than just using the +operator or [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a few general guidelines when working with strings:</p>
<ul>
<li>Don&#8217;t concatenate strings &#8211; use a StringBuilder instead</li>
<li>Whenever possible initialize the StringBuilder with enough capacity to avoid re-allocations</li>
<li>Excessive concatenation of strings will be several orders of magnitude slower than using a StringBuilder</li>
<li>String.Format() &#038; StringBuilder.AppendFormat() are significantly slower than just using the +operator or Append() &#8211; but may be more readable</li>
<li>When performance optimizing an application &#8211; string usage is a good place to start</li>
</ul>
<h3>Don&#8217;t concatenate strings</h3>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx">StringBuilder</a> is an often overlooked class, that can be used to solve a lot of performance problems in your applications.<br />
To give an example of how ineffective the basic string can be, take a look at the following code that builds 2 large strings by concatenating 1000 times to the same string using String and StringBuilder:<br />
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
<span class="kwrd">string</span> s = <span class="kwrd">string</span>.Empty;
<span class="kwrd">for</span> (<span class="kwrd">int</span> j = 0; j &lt; 1000; j++)
{
  s += <span class="str">"Test of string performance."</span>;
}

StringBuilder sb = <span class="kwrd">new</span> StringBuilder();
<span class="kwrd">for</span> (<span class="kwrd">int</span> j = 0; j &lt; 1000; j++)
{
  sb.Append(<span class="str">"Test of string performance."</span>);
}
</pre>
<p>Performance is measured on my HTC S710 moblie phone. The performance difference is very noticeable.</p>
<ul>
<li>The String implementation takes about 800ms</li>
<li>The StringBuilder implementation takes about 12ms</li>
</ul>
<p>StringBuilder is almost 70 times faster than String in this particular example and initializing the StringBuilder with enough capacity up front will shave another 2ms off. I have done tons of optimizations on Compact Framework applications over the years, and the first thing i usually do is replace String with StringBuilder in code similar to the above example.</p>
<h3>Immutable strings &#8211; blessing or curse?</h3>
<p>Strings in the .NET framework are immutable &#8211; meaning that once they are created they can not be changed. It is a design decision from the .NET framework designers, that allows for a lot of optimizations, but also cost performance under certain circumstances.<br />
This is the main reason the String concatenation from before is so slow. Every time the strings are concatenated, a new String is created, and the old one is left for the garbage collector. At least a thousand strings of increasing size are created, copied and garbage collected for no good reason. It is amazingly ineffective.</p>
<h3>StringBuilder &#8211; definitely a blessing!</h3>
<p>The StringBuilder is the thing to use, when handling and manipulating large strings. It holds the string in an internal array that it grows as needed. This enables a very fast append that only rarely allocates anything new. In my test the StringBuilder initially had a capacity of 64 bytes, and grew to double size whenever needed, but implementations may vary.<br />
This behaviour means that you can optimize performance even further by initializing the StringBuilder to a size that is slightly larger than what you expect the final string to be &#8211; thereby removing the need to ever re-allocate.</p>
<h3>A word or two about String.Format()</h3>
<p>I always assumed that using String.Format() to splice strings with variables was the fastest way of doing it. Tests show, however, that it is not&#8230;<br />
I have made test of 4 different ways of accomplishing the same thing:<br />
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
<span class="rem">//using string</span>
<span class="kwrd">string</span> x = <span class="str">"Test of string performance."</span> + 1 + 2 + <span class="str">"hello"</span>;
<span class="kwrd">string</span> x = <span class="kwrd">string</span>.Format(<span class="str">"Test of string performance.{0}{1}{2}"</span>, 1, 2, <span class="str">"hello"</span>);

<span class="rem">//using StringBuilder</span>
sb.Append(<span class="str">"Test of string performance."</span>).Append(1).Append(2).Append(<span class="str">"hello"</span>);
sb.AppendFormat(<span class="str">"Test of string performance.{0}{1}{2}"</span>, 1, 2, <span class="str">"hello"</span>);</pre>
<p>The results are similar for both the String and StringBuilder. Using the +operator or chained appends is <b>roughly twice as fast</b> as using the Format() method. This came as a bit of a surprise to me.</p>
]]></content:encoded>
			<wfw:commentRss>http://bitmatic.com/c/string-stringbuilder-performance-in-the-compact-framework/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Single instance applications in Windows CE</title>
		<link>http://bitmatic.com/c/single-instance-applications-in-windows-ce</link>
		<comments>http://bitmatic.com/c/single-instance-applications-in-windows-ce#comments</comments>
		<pubDate>Mon, 13 Jul 2009 18:22:36 +0000</pubDate>
		<dc:creator>Jakob</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Compact Framework]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[native code]]></category>
		<category><![CDATA[Windows CE]]></category>

		<guid isPermaLink="false">http://bitmatic.com/?p=370</guid>
		<description><![CDATA[I programmed a Windows CE application last month that had as a requirement that only one instance could run at the same time. Had it been Windows Mobile, this had been handled by the OS, but on Windows CE you have to take care of this yourself. I was a bit surprised that there is [...]]]></description>
			<content:encoded><![CDATA[<p>I programmed a Windows CE application last month that had as a requirement that only one instance could run at the same time. Had it been Windows Mobile, this had been handled by the OS, but on Windows CE you have to take care of this yourself.<br />
I was a bit surprised that there is no easy way of accomplishing this. Searching the internet gave me basically no easy answer either, but there seems to be 3 standard ways of accomplishing this.</p>
<ul>
<li>Write a dummy text file on startup, and check the existance of this file.</li>
<li>Write to a registry-key on startup, and use that as a &#8220;mutex&#8221;.</li>
<li>Use a named mutex with a system-wide scope.</li>
</ul>
<p>Obviously the first two have the problem that they may break the program, if the program exits without resetting the file/registry-key used as a pseudo-mutex. They are also very crude and not very elegant&#8230;. But that&#8217;s up to personal taste i guess.<br />
I went for the third choice; The named mutex.</p>
<h3>The named mutex in Windows CE</h3>
<p>The .NET Compact Framework does not support named mutexes. Luckily Windows CE does however, and it can be imported through a few functions in coredll.dll.<br />
A named mutex is an object created by the OS with a name specified on creation. The actual functionality of the object is not very interesting right now. The interesting bit is that only one object can exist with any given name. If you try to create another object with the same name, you get an error.<br />
Basically, if you create a named mutex with the name of the application itself, this can be used to ensure that only one instance of the application can be run.</p>
<h3>Wrapping it up</h3>
<p>I decided to wrap it all up nicely in a class, so that it will be easy to use. The class is called SingleInstanceApplication, and here is what i came up with:</p>
<pre class="csharpcode">
<span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Windows.Forms;
<span class="kwrd">using</span> System.Runtime.InteropServices;
<span class="kwrd">using</span> System.Reflection;

<span class="kwrd">namespace</span> Bitmatic
{
  <span class="kwrd">static</span> <span class="kwrd">class</span> SingleInstanceApplication
  {
    [DllImport(<span class="str">"coredll.dll"</span>, SetLastError = <span class="kwrd">true</span>)]
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">extern</span> IntPtr CreateMutex(IntPtr Attr, <span class="kwrd">bool</span> Own, <span class="kwrd">string</span> Name);

    [DllImport(<span class="str">"coredll.dll"</span>, SetLastError = <span class="kwrd">true</span>)]
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">extern</span> <span class="kwrd">bool</span> ReleaseMutex(IntPtr hMutex);

    <span class="kwrd">const</span> <span class="kwrd">long</span> ERROR_ALREADY_EXISTS = 183;

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Run(Form frm)
    {
      <span class="kwrd">string</span> name = Assembly.GetExecutingAssembly().GetName().Name;
      IntPtr mutexHandle = CreateMutex(IntPtr.Zero, <span class="kwrd">true</span>, name);
      <span class="kwrd">long</span> error = Marshal.GetLastWin32Error();

      <span class="kwrd">if</span> (error != ERROR_ALREADY_EXISTS)
        Application.Run(frm);

      ReleaseMutex(mutexHandle);
    }
  }
}</pre>
<p>Feel free to steal&#8230;.<br />
The class imports the two native functions for creating and destroying mutexes, and has only a single public function.<br />
The Run function tries to create a mutex with the name of the application. It then checks the error code returned, to see if the mutex already exists, and if it doesn&#8217;t; starts the application. Finally it releases the mutex.<br />
Very simple, and quite a bit more elegant than the file/registry based solutions.</p>
<h3>Using it</h3>
<p>Using the class is very very simple. Just add the class itself to your project, open up Program.cs and replace:</p>
<pre class="csharpcode">
[MTAThread]
<span class="kwrd">static</span> <span class="kwrd">void</span> Main()
{
  Application.Run(<span class="kwrd">new</span> Form1());
}</pre>
<p>with:</p>
<pre class="csharpcode">
[MTAThread]
<span class="kwrd">static</span> <span class="kwrd">void</span> Main()
{
  SingleInstanceApplication.Run(<span class="kwrd">new</span> Form1());
}</pre>
<p>You only really changed one line, and now you have an application that is guaranteed to run  only as a single instance.</p>
]]></content:encoded>
			<wfw:commentRss>http://bitmatic.com/c/single-instance-applications-in-windows-ce/feed</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Using embedded resource files in visual studio 2008</title>
		<link>http://bitmatic.com/c/using-embedded-resource-files-in-visual-studio-2008</link>
		<comments>http://bitmatic.com/c/using-embedded-resource-files-in-visual-studio-2008#comments</comments>
		<pubDate>Sun, 28 Jun 2009 20:37:17 +0000</pubDate>
		<dc:creator>Jakob</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[How-to]]></category>
		<category><![CDATA[VS2008]]></category>

		<guid isPermaLink="false">http://bitmatic.com/?p=341</guid>
		<description><![CDATA[Why embed files ? Many of my projects use a lot of secondary files. It can be images, icons, xml-files, text, sound, whatever&#8230;. These files pose a couple of problems for me: They clutter the program folder. The user may accidentally delete or change them. They expose your graphics/sound files to stealing and copying. They [...]]]></description>
			<content:encoded><![CDATA[<h3>Why embed files ?</h3>
<p>Many of my projects use a lot of secondary files. It can be images, icons, xml-files, text, sound, whatever&#8230;. These files pose a couple of problems for me:</p>
<ul>
<li>They clutter the program folder.</li>
<li>The user may accidentally delete or change them.</li>
<li>They expose your graphics/sound files to stealing and copying.</li>
<li>They expose program-sensitive information that a user may try to use to hack/change the behaviour of the program.</li>
</ul>
<p>Luckily there is a fairly easy solution to parts of these problems. Embed the file in the assembly.</p>
<h3>Embedding a file</h3>
<p>The actual embedding of a file in an assembly in Visual Studio 2008 is very easy indeed. You just add the file to the project, and set the build action to &#8220;Embedded Resource&#8221;.<br />
The compiler will then automagically embed the file in the assembly, where it will be accessible during runtime, to use as you wish. Of course this will make your assembly grow, and with many files, it may grow a lot, but this is usually no problem. You can embed any type of file, and you can arrange the files any way you want in project folders and the like.</p>
<h3>Getting the file from the assembly</h3>
<p>Getting the file out of the assembly is almost as easy as getting it in there. It uses functions from the System.Reflection to access the assembly itself, so adding a &#8220;using System.Reflection;&#8221; to your code is advisable.<br />
There are basically two functions worth noting here:</p>
<ul>
<li>GetManifestResourceNames() &#8211; Gets the names of all the embedded resources in the assembly.</li>
<li>GetManifestResourceStream(string name) &#8211; Returns a stream representing the named resource.</li>
</ul>
<p>So getting hold of the first resource in an assembly is as easy as:</p>
<pre class="csharpcode">
Assembly A = Assembly.GetExecutingAssembly();
<span class="kwrd">string</span>[] names = A.GetManifestResourceNames();
Stream S = A.GetManifestResourceStream(names[0]);</pre>
<p>The above example should get the point across. It is very easy to gain access to an embedded resource as you would access any file.<br />
A more practical example, is using an embedded resource file to set the image of a PictureBox control. It could look like this:</p>
<pre class="csharpcode">
Assembly A = Assembly.GetExecutingAssembly();
Stream S = A.GetManifestResourceStream(<span class="str">"MyProject.Images.jakob.gif"</span>);
pictureBox.Image = Image.FromStream(s);</pre>
<p>In the example here, the actual name of the resource is shown. &#8220;MyProject.Images.jakob.gif&#8221; is the name of a resource called &#8220;jakob.gif&#8221; belonging to the project named &#8220;MyProject&#8221;, and placed in a project folder with the name &#8220;Images&#8221;. This is a fairly ease naming convention, that makes all resource names unique and easy to figure out. If you ever have doubts about the name of a resource, just call GetManifestResourceNames(), and it will tell you the names.</p>
<h3>Saving all the ressources in an assembly to disk</h3>
<p>I&#8217;m going to finish by showing you a nice trick, that shows of the functions i outlined above. It is a function that iterates through all the resources in an assembly, and saves them to disk. It handles the files as raw byte arrays, so it should work with any file. I have tested it on gif, zip and pdf files, and it works like a charm.</p>
<pre class="csharpcode">
<span class="kwrd">private</span> <span class="kwrd">void</span> SaveAllResources()
{
  Assembly A = Assembly.GetExecutingAssembly();
  <span class="kwrd">string</span>[] names = A.GetManifestResourceNames();

  <span class="kwrd">foreach</span> (<span class="kwrd">string</span> filename <span class="kwrd">in</span> names)
  {
    Stream S = A.GetManifestResourceStream(filename);
    <span class="kwrd">byte</span>[] rawFile = <span class="kwrd">new</span> <span class="kwrd">byte</span>[S.Length];

    <span class="rem">//Read the data from the assembly</span>
    S.Read(rawFile, 0, (<span class="kwrd">int</span>)S.Length);

    <span class="rem">//Save the data to the hard drive</span>
    <span class="kwrd">using</span> (FileStream fs = <span class="kwrd">new</span> FileStream(filename, FileMode.Create))
    {
      fs.Write(rawFile, 0, (<span class="kwrd">int</span>)S.Length);
    }
  }
}</pre>
<p>Have fun embedding <img src='http://bitmatic.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://bitmatic.com/c/using-embedded-resource-files-in-visual-studio-2008/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Profiling for the Compact Framework</title>
		<link>http://bitmatic.com/c/profiling-for-the-compact-framework</link>
		<comments>http://bitmatic.com/c/profiling-for-the-compact-framework#comments</comments>
		<pubDate>Fri, 15 May 2009 10:30:44 +0000</pubDate>
		<dc:creator>Jakob</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Compact Framework]]></category>
		<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://bitmatic.com/?p=320</guid>
		<description><![CDATA[Just wanted to share with everyone that there is a .NET Profiler that works with the Compact Framework. It is made by a Danish company called Eqatec and best of all; It is completely free. A long search has ended I have been looking for something like this for several years, but until the Eqatec [...]]]></description>
			<content:encoded><![CDATA[<p>Just wanted to share with everyone that there is a <a href="http://www.eqatec.com/tools/profiler">.NET Profiler</a> that works with the Compact Framework. It is made by a Danish company called <a href="http://www.eqatec.com">Eqatec</a> and best of all; It is completely free.</p>
<h3>A long search has ended</h3>
<p>I have been looking for something like this for several years, but until the Eqatec profiler, no profiler has been able to profile mobile applications. When working with the Compact Framework you often find yourself in situation where performance is an issue. Many times you can make educated guesses as to where the bottlenecks may be, but at other times you are left pretty clueless.<br />
Attach a decent profiler, and your bottlenecks will be clear as ice.</p>
<h3>Does it work?</h3>
<p>When the <a href="http://www.eqatec.com/tools/profiler">Eqatec profiler</a> was released I immediately put it into work with profiling an application that had some performance issues during initial startup. We had tried solving these by guesswork, but it hadn&#8217;t helped a lot.<br />
Within 2 hours of attaching the profiler, I had cut the startup time to a fraction of what it was before.</p>
<p>There is a small issue that you need to be aware of with this profiler. Because of the way it works, by instrumenting the code, it adds a little bit of overhead to every function call. This means that small functions that get called a lot will appear to be more time consuming than they really are, because most of the time used is actually the overhead. This is something to look out for, when deciding which functions to try to optimize. It would be really nice if Eqatec could find a way to compensate for this overhead.</p>
<p>Other than that the profiler works like a charm. And by the way &#8211; I am not paid to write this, I just like the product a lot.</p>
]]></content:encoded>
			<wfw:commentRss>http://bitmatic.com/c/profiling-for-the-compact-framework/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Downloading files from the internet with C#</title>
		<link>http://bitmatic.com/c/downloading-files-from-the-internet-with-c</link>
		<comments>http://bitmatic.com/c/downloading-files-from-the-internet-with-c#comments</comments>
		<pubDate>Thu, 14 May 2009 12:16:44 +0000</pubDate>
		<dc:creator>Jakob</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[download]]></category>
		<category><![CDATA[file]]></category>
		<category><![CDATA[internet]]></category>

		<guid isPermaLink="false">http://bitmatic.com/?p=299</guid>
		<description><![CDATA[With the .NET framework it has become very easy to programmatically download content from the internet. Using the WebClient class from the System.Net downloading a file from the net becomes as easy as specifying the address to download. There are several different ways to accomplish this depending on the type of file you want to [...]]]></description>
			<content:encoded><![CDATA[<p>With the .NET framework it has become very easy to programmatically download content from the internet. Using the WebClient class from the System.Net downloading a file from the net becomes as easy as specifying the address to download.<br />
There are several different ways to accomplish this depending on the type of file you want to get, and also the content of the file.</p>
<h3>Downloading a string</h3>
<p>The following code uses a WebClient to download the file returned by http://bitmatic.com. The file is returned as a string, so it can be directly assigned to, for instance, a RichTextBox. With basically one line of code you have built yourself a (very) primitive web-browser. The method is very good if you just want a simple textual presentation of a web-content, or you need to work with the content in a textual manner with regular expressions or something similar.<br />
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
<span class="kwrd">using</span> (WebClient client = <span class="kwrd">new</span> WebClient())
{
  richTextBox.Text = client.DownloadString(<span class="str">"http://bitmatic.com"</span>);
}</pre>
<p>The WebClient object is scoped with the &#8220;using&#8221;-keyword. This is because it uses ressources that needs to be disposed properly. You could of course just ignore this and let the garbage collector dispose of it at some indefinite time, but that way you will run the risk of running out of ressources before the garbage collector cleans up (and don&#8217;t even think about calling the garbage collector manually&#8230; just don&#8217;t). You could also call client.Dispose(), but i mostly prefer the &#8220;using&#8221; syntax.</p>
<h3>Downloading a and saving a file</h3>
<p>Downloading and saving a file to your local filesystem is equally easy. Just supply an address and a filename to the DownloadFile method, and you have downloaded a file. You can download both using http and ftp with this method. The framework will handle this for you in a transparent way.<br />
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
<span class="kwrd">using</span> (WebClient client = <span class="kwrd">new</span> WebClient())
{
  client.DownloadFile(<span class="str">"http://bitmatic.com"</span>, <span class="str">"bitmatic.html"</span>);
}</pre>
<p>This code saves the content at http://bitmatic.com in a file called &#8220;bitmatic.html&#8221; on the local file system.</p>
<h3>Downloading the raw data in a byte array</h3>
<p>Lastly i want to mention a method that returns the content as a byte array. This will mostly be usefull for binary files, since the text encoding may be lost when using this method. You could look into the ResponseHeaders property of the WebClient after getting the data, they may contain information about encoding if the content was a text file, but really, you should just use DownloadString for text files.<br />
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
<span class="kwrd">using</span> (WebClient client = <span class="kwrd">new</span> WebClient())
{
  <span class="kwrd">byte</span>[] bArr = client.DownloadData(<span class="str">"http://bitmatic.com"</span>);
}</pre>
<h3>Only half the story</h3>
<p>The WebClient is a very powerfull class, and the tiny code examples above should only serve as an appetizer. The class also allows you to do all the operations asynchronously, and perform uploads as well as downloads. If you start to look into modifying the headers that are sent you could get really creative. Take a look at the <a href="http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.80).aspx">msdn article about WebClient</a> for further inspiration.</p>
]]></content:encoded>
			<wfw:commentRss>http://bitmatic.com/c/downloading-files-from-the-internet-with-c/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

