<?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>Confessions of a Keytarist &#187; C#</title>
	<atom:link href="http://www.blog.ianmellor.co.uk/tag/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.blog.ianmellor.co.uk</link>
	<description>Only an idiot blames his fools... tools.. damn keyboard</description>
	<lastBuildDate>Fri, 09 Jul 2010 14:03:00 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Making the extra effort</title>
		<link>http://www.blog.ianmellor.co.uk/2009/09/17/making-the-extra-effort/</link>
		<comments>http://www.blog.ianmellor.co.uk/2009/09/17/making-the-extra-effort/#comments</comments>
		<pubDate>Thu, 17 Sep 2009 09:54:38 +0000</pubDate>
		<dc:creator>Sk93</dc:creator>
				<category><![CDATA[Annoyances]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Laziness]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://www.blog.ianmellor.co.uk/2009/09/17/making-the-extra-effort/</guid>
		<description><![CDATA[Warning: rant ahead!
I’m now the sole developer working on arguably one of the largest projects for our company, and things are going well. However, I keep falling into traps and pitfalls created by one of the projects last programmers.   
One of his “favourite” tricks seems to be creating a business layer method that [...]]]></description>
			<content:encoded><![CDATA[<p>Warning: rant ahead!</p>
<p>I’m now the sole developer working on arguably one of the largest projects for our company, and things are going well. However, I keep falling into traps and pitfalls created by one of the projects last programmers.   </p>
<p>One of his “favourite” tricks seems to be creating a business layer method that populates an object based on data retrieved from a database. Nothing odd there.. but it’s when you have the need to re-use one of his functions that you end up falling right into his carefully seeded trap!</p>
<p> <span id="more-69"></span>
<p>For example, we have an object called “CustomerSite”, which as the name suggests, has various properties that pertain to a customer’s site – 15 individual properties to be exact.   <br />Whilst writing an additional management page for the project today, I had the need to get a “CustomerSite” object from the database, based on the site code.    <br />A quick look through our data access methods reveals a pre-written method “GetCustomerSiteBySiteCode”. Excellent; No need to write a new stored proc and no need to write the retrieval C# code!</p>
<p>However, in hindsight I knew this particular programmer had written both the retrieval method and the stored proc, so I should have checked ahead of time, but alas I did not…</p>
<p>So I fire up my new shiny page and all goes well, right up to when my codebehind calls the “GetCustomerSiteBySiteCode” method. At which point, my page throws a wobbly with invalid use of null errors throwing hand over fist.</p>
<p>Initially, I start checking the database to make sure the data is actually fine for the customer site I selected. With that being fine, I check my code to make sure I’m not doing anything daft. Happy that I’ve not, it’s time to place a breakpoint and step on through&#8230;</p>
<p>It’s at the point I step into “GetCustomerSiteBySiteCode” that I realise I’ve been stung; Despite the “CustomerSite” object having 15 properties, only TWO of them are being set by this method – the rest are simply set to null.</p>
<p>After altering the method to actually populate all 15 properties, I checked the stored procedure, to find two select statements, the first with all fifteen fields commented out with the note “Probably want to include these fields later, but haven’t the need to use them yet.”</p>
<p>To quote Peter Griffin “This really grinds my gears”. It was the programmer who created the “CustomerSite” object to begin with, and it’s always had all 15 properties from the get go. It’s simply a case of laziness and lack of forethought; there’s every reason to believe that this method would be called elsewhere, especially as when he was working on the project, it was a multi-person project.</p>
<p>Grr.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.ianmellor.co.uk/2009/09/17/making-the-extra-effort/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>No Closure</title>
		<link>http://www.blog.ianmellor.co.uk/2009/07/23/no-closure/</link>
		<comments>http://www.blog.ianmellor.co.uk/2009/07/23/no-closure/#comments</comments>
		<pubDate>Thu, 23 Jul 2009 15:39:56 +0000</pubDate>
		<dc:creator>Sk93</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Computers]]></category>
		<category><![CDATA[Tricks]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://www.blog.ianmellor.co.uk/?p=47</guid>
		<description><![CDATA[A colleague came to me today asking if I knew of any way to remove the close button from a windows form, but still show the minimize and maximize buttons.
On the face of it, it sounded like an easy answer. I knew you could disable both the minimize and maximize buttons very easily from within [...]]]></description>
			<content:encoded><![CDATA[<p>A colleague came to me today asking if I knew of any way to remove the close button from a windows form, but still show the minimize and maximize buttons.</p>
<p>On the face of it, it sounded like an easy answer. I knew you could disable both the minimize and maximize buttons very easily from within the Visual Studio GUI – so surely there’s an option for the third button; the close button?   <br />Actually, no. Whilst you can remove all three buttons in one go (changing the setting “ControlBox” to false.) and as previously mentioned, you can disable the maximize and minimize buttons (“MaximizeBox” and “MinimizeBox” settings respectively), there is no setting to directly control the Close button.</p>
<p> <span id="more-47"></span>
<p>A quick Google search produced a few varied approaches, but the one I suggested my colleague to implement is as follows:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">private const int CP_NOCLOSE_BUTTON = 0x200;
protected override CreateParams CreateParams
{
    get
    {
        CreateParams mdiCp = base.CreateParams;
        mdiCp.ClassStyle = mdiCp.ClassStyle | CP_NOCLOSE_BUTTON;
        return mdiCp;
    }
}</pre></td></tr></table></div>

<p>This small bit of code simply needs to be placed within your form class; It overrides a property that is already called when a form is initialised, so doesn’t need to be explicitly called.</p>
<p>Some before and after shots:</p>
<p><a href="http://www.blog.ianmellor.co.uk/images/NoClosure_E2CF/2.jpg"><img title="Before" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="238" alt="Before" src="http://www.blog.ianmellor.co.uk/images/NoClosure_E2CF/2_thumb.jpg" width="238" border="0" /></a> <a href="http://www.blog.ianmellor.co.uk/images/NoClosure_E2CF/1.jpg"><img title="After" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="238" alt="After" src="http://www.blog.ianmellor.co.uk/images/NoClosure_E2CF/1_thumb.jpg" width="238" border="0" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.ianmellor.co.uk/2009/07/23/no-closure/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>There can be only one!</title>
		<link>http://www.blog.ianmellor.co.uk/2009/07/10/there-can-be-only-one/</link>
		<comments>http://www.blog.ianmellor.co.uk/2009/07/10/there-can-be-only-one/#comments</comments>
		<pubDate>Fri, 10 Jul 2009 12:33:37 +0000</pubDate>
		<dc:creator>Sk93</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Computers]]></category>
		<category><![CDATA[Mutex]]></category>
		<category><![CDATA[Threading]]></category>
		<category><![CDATA[Tricks]]></category>

		<guid isPermaLink="false">http://www.blog.ianmellor.co.uk/2009/07/10/there-can-be-only-one/</guid>
		<description><![CDATA[I had to make a slight change to one of my applications for a customer today, making it check if it is already running on the local machine and, if it is, abandon it’s attempt to start up another instance.
My initial thoughts were to examine the executing processes and check for the existence of the [...]]]></description>
			<content:encoded><![CDATA[<p>I had to make a slight change to one of my applications for a customer today, making it check if it is already running on the local machine and, if it is, abandon it’s attempt to start up another instance.</p>
<p>My initial thoughts were to examine the executing processes and check for the existence of the application in the list:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">    string procName = Process.GetCurrentProcess().ProcessName;           
    Process[] processes= Process.GetProcessesByName(procName);
&nbsp;
    if (processes.Length == 1)
    {
        //run application
        ...
    }</pre></td></tr></table></div>

<p>Now, whilst this works, it is easily “beatable” by simply changing the executable’s name. Doing so will cause the method “GetProcessessByName()” to return only a single match, instead of the current application and any other duplicate instances.</p>
<p><span id="more-43"></span></p>
<p>After pondering on the subject for a while, I started to think how threading works, or more precisely, how threading deals with shared resources.</p>
<p>When a thread attempts to access a shared resource, an exclusive lock is applied to that resource until the thread completes it’s task. These locks are actually “Mutex” objects (<a href="http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx" target="_blank">read more here</a>).</p>
<p>Using a Mutex, I was able to create the following code:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">    bool isFirstInstance;
    Mutex mx = new Mutex(true,&quot;Global\\MyApplicationName&quot;,out isFirstInstance);
&nbsp;
    if (isFirstInstance)
    {
        //run application
        ...
        mx.Close();
    }
    else
    {
        //application already running
    }</pre></td></tr></table></div>

<p>The “Global\\” prefix tells the Mutex to be available across all user instances on the machine, not just the current.<br />
  <br />Also, whilst it’s not strictly required to close the Mutex before exiting, as it will be automatically closed when the application ends, I’ve added it in this example for completeness.</p>
<p>In my opinion, this method is more reliable, more robust, and slightly cooler <img src='http://www.blog.ianmellor.co.uk/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.ianmellor.co.uk/2009/07/10/there-can-be-only-one/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Elegantly Invoking</title>
		<link>http://www.blog.ianmellor.co.uk/2009/06/12/elegantly-invoking/</link>
		<comments>http://www.blog.ianmellor.co.uk/2009/06/12/elegantly-invoking/#comments</comments>
		<pubDate>Fri, 12 Jun 2009 13:55:23 +0000</pubDate>
		<dc:creator>Sk93</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[extension methods]]></category>
		<category><![CDATA[invoke]]></category>
		<category><![CDATA[lambda]]></category>

		<guid isPermaLink="false">http://www.blog.ianmellor.co.uk/?p=13</guid>
		<description><![CDATA[Anyone who has seen code written by me that requires the invoking of WinForm controls will know that I have an irrational hatred of the &#8220;recommended&#8221; way of resolving cross-thread operations.
Now, whilst I agree that cross-thread operations should be handled correctly, and I&#8217;m actually glad Microsoft decided to tighten its belt over this when it [...]]]></description>
			<content:encoded><![CDATA[<p>Anyone who has seen code written by me that requires the invoking of WinForm controls will know that I have an irrational hatred of the &#8220;recommended&#8221; way of resolving cross-thread operations.</p>
<p>Now, whilst I agree that cross-thread operations should be handled correctly, and I&#8217;m actually glad Microsoft decided to tighten its belt over this when it came to creating the dotNet framework, it just seems very &#8220;bloaty&#8221; to have to write methods such as the following:<br />
<span id="more-13"></span></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">delegate void SetFirstNameTextCallBack(string value);
private void SetFirstNameText(string value)
{
   if (txtFirstName.InvokeRequired)
   {
      SetFirstNameTextCallBack cb = new SetFirstNameTextCallBack(SetFirstNameText);
      cb.Invoke(value);
   }
   else
   {
      txtFirstName.Text = value;
   }
}</pre></td></tr></table></div>

<p>Ok, you can get a bit cleverer and write delegates and methods that expect a control, property name and property value to be provided, such as this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">delegate void SetControlPropertyCallBack(Control control, string property, object value);
private void SetControlProperty(Control control, string property, object value)
{
   if (control.InvokeRequired)
   {
      SetControlPropertyCallBack cb = new SetControlPropertyCallBack(SetControlProperty);
      cb.Invoke(control, property, value);
   }
   else
   {
      Type t = control.GetType();
      System.Reflection.PropertyInfo propInf = t.GetProperties().First(p =&amp;gt; p.Name.ToUpper() == property.ToUpper());
      propInf.SetValue(control, value, null);
   }
}</pre></td></tr></table></div>

<p>But it still looks yuck to me.</p>
<p>Over the last few weeks, I&#8217;ve been increasingly using lambda and extension methods, and came up with a new way of handling invokes that I actually like!<br />
It involves extending the &#8220;Invoke&#8221; method, as shown below:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">public static TResult Invoke(this T controlToInvokeOn, Func codeToInvoke) where T : Control
{
   if (controlToInvokeOn.InvokeRequired)
   {
      return (TResult)controlToInvokeOn.Invoke(codeToInvoke);
   }
   else
   {
      return (TResult)codeToInvoke();
   }
}</pre></td></tr></table></div>

<p>With this implemented, any time you need to invoke anything, you can do so quickly and elegantly with a little lambda:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">txtFirstName.Invoke(()=&gt;Text = &quot;test&quot;);</pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://www.blog.ianmellor.co.uk/2009/06/12/elegantly-invoking/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
