<?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>FormatException &#187; C#</title>
	<atom:link href="http://www.formatexception.com/tag/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.formatexception.com</link>
	<description>Ramblings on developing in the Windows World</description>
	<lastBuildDate>Fri, 23 Sep 2011 15:34:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Often Unused Operators: fixed()</title>
		<link>http://www.formatexception.com/2011/03/often-unused-operators-fixed/</link>
		<comments>http://www.formatexception.com/2011/03/often-unused-operators-fixed/#comments</comments>
		<pubDate>Wed, 09 Mar 2011 16:43:26 +0000</pubDate>
		<dc:creator>Brian</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[fixed]]></category>
		<category><![CDATA[often unused operators]]></category>

		<guid isPermaLink="false">http://www.formatexception.com/?p=359</guid>
		<description><![CDATA[This post is inspired by Eric Clippert&#8217;s post on References and Pointers. I think it escapes a lot of C# devs that they have the same pointer abilities as C/C++, or maybe it&#8217;s that those features have been intentionally down-played by Microsoft for a reason. As C# devs we&#8217;ve come to rely on nice, safe [...]]]></description>
			<content:encoded><![CDATA[<p>This post is inspired by Eric Clippert&#8217;s post on <a href="http://blogs.msdn.com/b/ericlippert/archive/2011/03/07/references-and-pointers-part-one.aspx" target="_blank">References and Pointers</a>.</p>
<p>I think it escapes a lot of C# devs that they have the same pointer abilities as C/C++, or maybe it&#8217;s that those features have been intentionally down-played by Microsoft for a reason.  As C# devs we&#8217;ve come to rely on nice, safe and managed code and GC.  That doesn&#8217;t mean we can&#8217;t cause an out of memory exception or infinite recursion or some other bad thing along the way, but for the most part C# tries to protect us.  While I&#8217;m not going to cover pointers (something of which I have a fondness for given that my very first college class was &#8220;Fundamentals of C&#8221;) I do want to go over the fixed() operation.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/f58wzh21.aspx" target="_blank">Fixed</a> is basically telling the GC, &#8220;Don&#8217;t move me, don&#8217;t touch me, don&#8217;t GC me, don&#8217;t even look at me&#8221; which is why fixed can only be used within an unsafe context.  It&#8217;s important to mention that unsafe means, um, unsafe.  When you identify an area of code as unsafe you&#8217;re saying, &#8220;Hey, I know I&#8217;m doing something that could potientially be really bad and all the work MS has done to try and protect me I&#8217;m ignoring.  I really, really promise to only use smart code here.&#8221; </p>
<p>Here&#8217;s a bit of code using fixed:</p>
<pre name="code" class="csharp">unsafe void FixedExample()
{
&nbsp;&nbsp;&nbsp;&nbsp;double[] arr = { 0, 1.5, 3, 4.5, 6, 7.5, 9 };
&nbsp;&nbsp;&nbsp;&nbsp;fixed(double* p1 = &#038;arr[1])
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;fixed (double* p2 = &#038;arr[5])
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int diff = (int)(p2 - p1);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Debug.Print(diff.ToString());
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;}
}</pre>
<pre name="code" class="csharp">unsafe void FixedExample2()
{
&nbsp;&nbsp;&nbsp;&nbsp;double[] array =  { 0, 1.5, 3, 4.5, 6, 7.5, 9 };
&nbsp;&nbsp;&nbsp;&nbsp;fixed (double* arr = array)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;double* p1 = &#038;arr[1];
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;double* p2 = &#038;arr[3];
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int diff = (int)(p2 - p1);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Debug.Print(diff.ToString());
&nbsp;&nbsp;&nbsp;&nbsp;}
}</pre>
<p>Basically, fixed allows you to get pointers to managed types which would otherwise be subjected to GC.  If you were to work just with pointers and not managed types you can do the above (using stackalloc) without even needing fixed.</p>
<pre name="code" class="csharp">unsafe void StackallocExample()
{
&nbsp;&nbsp;&nbsp;&nbsp;int arraySize = 7;
&nbsp;&nbsp;&nbsp;&nbsp;double* arr = stackalloc double[arraySize];
&nbsp;&nbsp;&nbsp;&nbsp;double j = 0;
&nbsp;&nbsp;&nbsp;&nbsp;for (int i = 0; i < arraySize; i++, j += 1.5)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;arr[i] = j;
&nbsp;&nbsp;&nbsp;&nbsp;}

&nbsp;&nbsp;&nbsp;&nbsp;double* p1 = &#038;arr[1];
&nbsp;&nbsp;&nbsp;&nbsp;double* p2 = &#038;arr[15];
&nbsp;&nbsp;&nbsp;&nbsp;int diff = (int)(p2 - p1);
&nbsp;&nbsp;&nbsp;&nbsp;Debug.Print(diff.ToString());
}</pre>
<p>but of course the above code is very bad.  If you didn't notice, the second pointer points to the 16th element (since we're obviously 0 based) but I only allocated 7 doubles worth of memory.  If I were do try and do something with arr[15] (rather then just determine the distance between the two elements) that would be very bad as it wouldn't represent a value I had intended and would just be some random bit of whatever was stored in that memory location.  Interestingly enough, if you try the same in the first two examples you'll get a runtime exception.</p>
<p>Thanks,<br />
Brian</p>



Share and Enjoy:


	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.formatexception.com%2F2011%2F03%2Foften-unused-operators-fixed%2F&amp;t=Often%20Unused%20Operators%3A%20fixed%28%29" title="Facebook"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.formatexception.com%2F2011%2F03%2Foften-unused-operators-fixed%2F&amp;t=Often%20Unused%20Operators%3A%20fixed%28%29" title="HackerNews"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/hackernews.png" title="HackerNews" alt="HackerNews" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://www.formatexception.com/2011/03/often-unused-operators-fixed/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>.Net 4.0 stuff on the way.</title>
		<link>http://www.formatexception.com/2009/08/net-4-0-stuff-on-the-way/</link>
		<comments>http://www.formatexception.com/2009/08/net-4-0-stuff-on-the-way/#comments</comments>
		<pubDate>Mon, 31 Aug 2009 21:51:21 +0000</pubDate>
		<dc:creator>Brian</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[.Net 4.0]]></category>

		<guid isPermaLink="false">http://www.formatexception.com/?p=256</guid>
		<description><![CDATA[Here&#8217;s some nice .Net 4.0 stuff on the way. I&#8217;ve been working on some poker tournament software with a lot of the new 4.0 features in mind. Once I have a couple of posts ready I&#8217;ll throw them up. Thanks, Brian Share and Enjoy:]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s some <a href="http://jyotsnakalambe.wordpress.com/2009/08/14/new-release-net-framework-4-0-features/">nice .Net 4.0 stuff on the way</a>.  I&#8217;ve been working on some poker tournament software with a lot of the new 4.0 features in mind.  Once I have a couple of posts ready I&#8217;ll throw them up.</p>
<p>Thanks,<br />
Brian</p>



Share and Enjoy:


	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.formatexception.com%2F2009%2F08%2Fnet-4-0-stuff-on-the-way%2F&amp;t=.Net%204.0%20stuff%20on%20the%20way." title="Facebook"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.formatexception.com%2F2009%2F08%2Fnet-4-0-stuff-on-the-way%2F&amp;t=.Net%204.0%20stuff%20on%20the%20way." title="HackerNews"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/hackernews.png" title="HackerNews" alt="HackerNews" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://www.formatexception.com/2009/08/net-4-0-stuff-on-the-way/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>First in a series of many</title>
		<link>http://www.formatexception.com/2008/09/first-in-a-series-of-many/</link>
		<comments>http://www.formatexception.com/2008/09/first-in-a-series-of-many/#comments</comments>
		<pubDate>Fri, 19 Sep 2008 14:51:12 +0000</pubDate>
		<dc:creator>Brian</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[coding standards]]></category>

		<guid isPermaLink="false">http://www.formatexception.com/?p=69</guid>
		<description><![CDATA[I &#8216;ve been trying to come up with things that lead to a series of follows up stuff.  This way I don&#8217;t have to think too hard about coming up with subjects and it makes writing them easier since I don&#8217;t have to spend so much time in general on them.  And now from: http://www.ayende.com/Blog/archive/2008/08/27/What-I-am-working-on.aspx [...]]]></description>
			<content:encoded><![CDATA[<p><!--StartFragment -->I &#8216;ve been trying to come up with things that lead to a series of follows up stuff.  This way I don&#8217;t have to think too hard about coming up with subjects <img src='http://www.formatexception.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  and it makes writing them easier since I don&#8217;t have to spend so much time in general on them.  And now from:</p>
<p><a class="moz-txt-link-freetext" href="http://www.ayende.com/Blog/archive/2008/08/27/What-I-am-working-on.aspx">http://www.ayende.com/Blog/archive/2008/08/27/What-I-am-working-on.aspx</a></p>
<p>Oren is his name and he is one of the bloggers I follow pretty close.  He&#8217;s been doing some pretty incredible stuff with a product he helped write called &#8220;Rhino Mocks&#8221; that allows you to create mock objects for testing and to set test conditions on those objects (ok, there&#8217;s a lot more but that scratches the surface) and in general he&#8217;s a pretty incredible coder.</p>
<p>Well, recently he posted some code that seems essentially how not to develop software with so many bad coding standards it would keep me busy for awhile.  Take a look at the below code:</p>
<div style="background-color: #FFF;overflow : auto;">
<pre><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> TaxCalculator
{
    <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">string</span> conStr;
    <span style="color: #0000ff;">private</span> DataSet rates;

    <span style="color: #0000ff;">public</span> TaxCalculator(<span style="color: #0000ff;">string</span> conStr)
    {
        <span style="color: #0000ff;">this</span>.conStr = conStr;
        <span style="color: #0000ff;">using</span> (SqlConnection con = <span style="color: #0000ff;">new</span> SqlConnection(conStr))
        {
            con.Open();
            <span style="color: #0000ff;">using</span> (SqlCommand cmd = <span style="color: #0000ff;">new</span> SqlCommand("<span style="color: #8b0000;">SELECT * FROM tblTxRtes</span>", con))
            {
                rates = <span style="color: #0000ff;">new</span> DataSet();
                <span style="color: #0000ff;">new</span> SqlDataAdapter(cmd).Fill(rates);
                Log.Write("<span style="color: #8b0000;">Read </span>" + rates.Tables[0].Rows.Count + <br/>"<span style="color: #8b0000;"> rates from database</span>");
                <span style="color: #0000ff;">if</span> (rates.Tables[0].Rows.Count == 0)
                {
                    MailMessage msg = <span style="color: #0000ff;">new</span> MailMessage("<span style="color: #8b0000;"><a class="moz-txt-link-abbreviated" href="mailto:important@legacy.org">important@legacy.org</a></span>", "<span style="color: #8b0000;"><a class="moz-txt-link-abbreviated" href="mailto:joe@legacy.com">joe@legacy.com</a></span>");
                    msg.Subject = "<span style="color: #8b0000;">NO RATES IN DATABASE!!!!!</span>";
                    msg.Priority = MailPriority.High;
                    <span style="color: #0000ff;">new</span> SmtpClient("<span style="color: #8b0000;">mail.legacy.com</span>", 9089).Send(msg);
                    Log.Write("<span style="color: #8b0000;">No rates for taxes found in </span>" + conStr);
                    <span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span> ApplicationException("<span style="color: #8b0000;">No rates, Joe forgot to load the rates AGAIN!</span>");
                }
            }
        }
    }

    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">bool</span> Process(XmlDocument transaction)
    {
        <span style="color: #0000ff;">try</span>
        {
            Hashtable tx2tot = <span style="color: #0000ff;">new</span> Hashtable();
            <span style="color: #0000ff;">foreach</span> (XmlNode o <span style="color: #0000ff;">in</span> transaction.FirstChild.ChildNodes)
            {
            restart:
                <span style="color: #0000ff;">if</span> (o.Attributes["<span style="color: #8b0000;">type</span>"].Value == "<span style="color: #8b0000;">2</span>")
                {
                    Log.Write("<span style="color: #8b0000;">Type two transaction processing</span>");
                    <span style="color: #0000ff;">decimal</span> total = <span style="color: #0000ff;">decimal</span>.Parse(o.Attributes["<span style="color: #8b0000;">tot</span>"].Value);
                    XmlAttribute attribute = transaction.CreateAttribute("<span style="color: #8b0000;">tax</span>");
                    <span style="color: #0000ff;">decimal</span> r = -1;
                    <span style="color: #0000ff;">foreach</span> (DataRow dataRow <span style="color: #0000ff;">in</span> rates.Tables[0].Rows)
                    {
                        <span style="color: #0000ff;">if</span> ((<span style="color: #0000ff;">string</span>)dataRow[2] == o.SelectSingleNode("<span style="color: #8b0000;">//cust-details/state</span>").Value)
                        {
                            r = <span style="color: #0000ff;">decimal</span>.Parse(dataRow[2].ToString());
                        }
                    }
                    Log.Write("<span style="color: #8b0000;">Rate calculated and is: </span>" + r);
                    o.Attributes.Append(attribute);
                    <span style="color: #0000ff;">if</span> (r == -1)
                    {
                        MailMessage msg = <span style="color: #0000ff;">new</span> MailMessage("<span style="color: #8b0000;"><a class="moz-txt-link-abbreviated" href="mailto:important@legacy.org">important@legacy.org</a></span>", "<span style="color: #8b0000;"><a class="moz-txt-link-abbreviated" href="mailto:joe@legacy.com">joe@legacy.com</a></span>");
                        msg.Subject = "<span style="color: #8b0000;">NO RATES FOR </span>" + o.SelectSingleNode("<span style="color: #8b0000;">//cust-details/state</span>").Value + "<span style="color: #8b0000;"> TRANSACTION !!!!ABORTED!!!!</span>";
                        msg.Priority = MailPriority.High;
                        <span style="color: #0000ff;">new</span> SmtpClient("<span style="color: #8b0000;">mail.legacy.com</span>", 9089).Send(msg);
                        Log.Write("<span style="color: #8b0000;">No rate for transaction in tranasction state</span>");
                        <span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span> ApplicationException("<span style="color: #8b0000;">No rates, Joe forgot to load the rates AGAIN!</span>");
                    }
                    tx2tot.Add(o.Attributes["<span style="color: #8b0000;">id</span>"], total * r);
                    attribute.Value = (total * r).ToString();
                }
                <span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span> (o.Attributes["<span style="color: #8b0000;">type</span>"].Value == "<span style="color: #8b0000;">1</span>")
                {
                    <span style="color: #008000;">//2006-05-02 just need to do the calc</span>
                    <span style="color: #0000ff;">decimal</span> total = 0;
                    <span style="color: #0000ff;">foreach</span> (XmlNode i <span style="color: #0000ff;">in</span> o.ChildNodes)
                    {
                        total += ProductPriceByNode(i);
                    }
                    <span style="color: #0000ff;">try</span>
                    {
                        <span style="color: #008000;">// 2007-02-19 not so simple, TX has different rule</span>
                        <span style="color: #0000ff;">if</span> (o.SelectSingleNode("<span style="color: #8b0000;">//cust-details/state</span>").Value == "<span style="color: #8b0000;">TX</span>")
                        {
                            total *= (<span style="color: #0000ff;">decimal</span>)1.02;
                        }
                    }
                    <span style="color: #0000ff;">catch</span> (NullReferenceException)
                    {
                        XmlElement element = transaction.CreateElement("<span style="color: #8b0000;">state</span>");
                        element.Value = "<span style="color: #8b0000;">NJ</span>";
                        o.SelectSingleNode("<span style="color: #8b0000;">//cust-details</span>").AppendChild(element);
                    }
                    XmlAttribute attribute = transaction.CreateAttribute("<span style="color: #8b0000;">tax</span>");
                    <span style="color: #0000ff;">decimal</span> r = -1;
                    <span style="color: #0000ff;">foreach</span> (DataRow dataRow <span style="color: #0000ff;">in</span> rates.Tables[0].Rows)
                    {
                        <span style="color: #0000ff;">if</span> ((<span style="color: #0000ff;">string</span>)dataRow[2] == o.SelectSingleNode("<span style="color: #8b0000;">//cust-details/state</span>").Value)
                        {
                            r = <span style="color: #0000ff;">decimal</span>.Parse(dataRow[2].ToString());
                        }
                    }
                    <span style="color: #0000ff;">if</span> (r == -1)
                    {
                        MailMessage msg = <span style="color: #0000ff;">new</span> MailMessage("<span style="color: #8b0000;"><a class="moz-txt-link-abbreviated" href="mailto:important@legacy.org">important@legacy.org</a></span>", "<span style="color: #8b0000;"><a class="moz-txt-link-abbreviated" href="mailto:joe@legacy.com">joe@legacy.com</a></span>");
                        msg.Subject = "<span style="color: #8b0000;">NO RATES FOR </span>" + o.SelectSingleNode("<span style="color: #8b0000;">//cust-details/state</span>").Value + "<span style="color: #8b0000;"> TRANSACTION !!!!ABORTED!!!!</span>";
                        msg.Priority = MailPriority.High;
                        <span style="color: #0000ff;">new</span> SmtpClient("<span style="color: #8b0000;">mail.legacy.com</span>", 9089).Send(msg);
                        <span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span> ApplicationException("<span style="color: #8b0000;">No rates, Joe forgot to load the rates AGAIN!</span>");
                    }
                    attribute.Value = (total * r).ToString();
                    tx2tot.Add(o.Attributes["<span style="color: #8b0000;">id</span>"], total * r);
                    o.Attributes.Append(attribute);
                }
                <span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span> (o.Attributes["<span style="color: #8b0000;">type</span>"].Value == "<span style="color: #8b0000;">@</span>")
                {
                    o.Attributes["<span style="color: #8b0000;">type</span>"].Value = "<span style="color: #8b0000;">2</span>";
                    <span style="color: #0000ff;">goto</span> restart;
                    <span style="color: #008000;">// 2007-04-30 some bastard from northwind made a mistake and they have 3 months release cycle, so we have to</span>
                    <span style="color: #008000;">// fix this because they won't until sep-07</span>
                }
                <span style="color: #0000ff;">else</span>
                {
                    <span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span> Exception("<span style="color: #8b0000;">UNKNOWN TX TYPE</span>");
                }
            }
            SqlConnection con2 = <span style="color: #0000ff;">new</span> SqlConnection(conStr);
            SqlCommand cmd2 = <span style="color: #0000ff;">new</span> SqlCommand();
            cmd2.Connection = con2;
            con2.Open();
            <span style="color: #0000ff;">foreach</span> (DictionaryEntry d <span style="color: #0000ff;">in</span> tx2tot)
            {
                cmd2.CommandText = "<span style="color: #8b0000;">usp_TrackTxNew</span>";
                cmd2.Parameters.Add("<span style="color: #8b0000;">cid</span>", transaction.SelectSingleNode("<span style="color: #8b0000;">//cust-details/@id</span>").Value);
                cmd2.Parameters.Add("<span style="color: #8b0000;">tx</span>", d.Key);
                cmd2.Parameters.Add("<span style="color: #8b0000;">tot</span>", d.Value);
                cmd2.ExecuteNonQuery();
            }
            con2.Close();
        }
        <span style="color: #0000ff;">catch</span> (Exception e)
        {
            <span style="color: #0000ff;">if</span> (e.Message == "<span style="color: #8b0000;">UNKNOWN TX TYPE</span>")
            {
                <span style="color: #0000ff;">return</span> <span style="color: #0000ff;">false</span>;
            }
            <span style="color: #0000ff;">throw</span> e;
        }
        <span style="color: #0000ff;">return</span> <span style="color: #0000ff;">true</span>;
    }

    <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">decimal</span> ProductPriceByNode(XmlNode item)
    {
        <span style="color: #0000ff;">using</span> (SqlConnection con = <span style="color: #0000ff;">new</span> SqlConnection(conStr))
        {
            con.Open();
            <span style="color: #0000ff;">using</span> (SqlCommand cmd = <span style="color: #0000ff;">new</span> SqlCommand("<span style="color: #8b0000;">SELECT * FROM tblProducts WHERE pid=</span>" + item.Attributes["<span style="color: #8b0000;">id</span>"], con))
            {
                DataSet <span style="color: #0000ff;">set</span> = <span style="color: #0000ff;">new</span> DataSet();
                <span style="color: #0000ff;">new</span> SqlDataAdapter(cmd).Fill(<span style="color: #0000ff;">set</span>);
                <span style="color: #0000ff;">return</span> (<span style="color: #0000ff;">decimal</span>)<span style="color: #0000ff;">set</span>.Tables[0].Rows[0][4];

            }
        }
    }
}</pre>
</div>
<p>If this code doesn&#8217;t make you shudder I worry about you and suspect you shouldn&#8217;t be working as a computer programmer.<br />
Over the course of the next few weeks, along with my posts on LINQ I want to spend some time analyzing what is wrong with this and help to try to define some of the established coding standards with .Net as well as coding in general.</p>
<p>Let&#8217;s start with the obvious.  We all know I am anti-goto, with good reason.  There is really no place in any modern high-level language for gotos.  Look at this:</p>
<p><span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span> (o.Attributes["<span style="color: #8b0000;">type</span>"].Value == &#8220;<span style="color: #8b0000;">@</span>&#8220;)<br />
{<br />
        o.Attributes["<span style="color: #8b0000;">type</span>"].Value = &#8220;<span style="color: #8b0000;">2</span>&#8220;; <span style="color: #0000ff;"><br />
        goto</span> restart;<br />
        <span style="color: #008000;">// 2007-04-30 some bastard from northwind made a mistake and they have 3 months release cycle, so we have to</span> <span style="color: #008000;"><br />
        // fix this because they won&#8217;t until sep-07</span><br />
}</p>
<p>Okay, if you look at the flow of the foreach this is in this else/if and breaks the flow of the code sending the execution back up to the top in mid-loop restarting everything over again. </p>
<p>But Brian, this had to be done, don&#8217;t you see the comments?</p>
<p>No my young padawan, it doesn&#8217;t.  I&#8217;m not saying the fix for this shouldn&#8217;t be in place, what I&#8217;m saying is that the goto shouldn&#8217;t be there.  If the original programmer thought about this a bit more he would have seen that if he simply put the statement at the beginning of the foreach as an if statement like:</p>
<p><span style="color: #0000ff;">if</span> (o.Attributes["<span style="color: #8b0000;">type</span>"].Value == &#8220;<span style="color: #8b0000;">@</span>&#8220;)<br />
{<br />
        o.Attributes["<span style="color: #8b0000;">type</span>"].Value = &#8220;<span style="color: #8b0000;">2</span>&#8220;; <span style="color: #0000ff;"><br />
</span>        <span style="color: #008000;">// 2007-04-30 some bastard from northwind made a mistake and they have 3 months release cycle, so we have to</span> <span style="color: #008000;"><br />
        // fix this because they won&#8217;t until sep-07</span><br />
}</p>
<p> it would have had the same effect without needing the goto.</p>
<p>But Brian, by putting it later in the code then most of the time you will be able to try and capture the ifs earlier and then you won&#8217;t have to do a compare on every row for &#8220;@&#8221;. </p>
<p>So what?  How do you know that every row won&#8217;t have the &#8220;@&#8221; for the value?  In that case you actually hurt your code execution by not putting the if at the beginning of the foreach loop.  Plain and simple gotos hurt code (see my earlier post on gotos with references on such).  The studies have been done and there are no reason for them in a modern language.</p>
<p>On to the next point of the code:</p>
<pre>MailMessage msg = <span style="color: #0000ff;">new</span> MailMessage("<span style="color: #8b0000;"><a class="moz-txt-link-abbreviated" href="mailto:important@legacy.org">important@legacy.org</a></span>", "<span style="color: #8b0000;"><a class="moz-txt-link-abbreviated" href="mailto:joe@legacy.com">joe@legacy.com</a></span>");</pre>
<p>Well, what&#8217;s wrong with this? </p>
<p>What if Joe quits the company?  What if Important quits the company?  These values should not be embedded in the code. </p>
<p>But Brian, Important is a not person you silly guy! It&#8217;s a mailing group.</p>
<p>Wow, sarcasm is not lost on you.</p>
<p>In modern .Net applications you have the Settings.  This allows you to store values in an easy to use xml file.  To get the values back out you don&#8217;t have to even do any special parsing, you just do (assuming you named your settings &#8220;MySettings&#8221;):</p>
<pre>MailMessage msg = <span style="color: #0000ff;">new</span> MailMessage(MySettings.WhoToSendEmailTo);</pre>
<p>That&#8217;s right.  When you add settings to your application you can then simply refer to the values in them directly as a property of the static Settings object in your project.  Then, in the future if Joe or Important should no longer get the emails then you simply modify the xml file in the application directory (or use the Visual Studio settings editor) and change who it should go to.  No need to recompile.  It&#8217;s that simple.  To add a settings, right click on the project name, select &#8220;Add New&#8221; and click on Settings file.  Name it as you like and Visual Studio will open a settings editor where you can add these properties and values.</p>
<p>Brian, you&#8217;re a dumb ass.  I tried this.  My application spans multiple projects and the settings file is only scoped at the project level.</p>
<p>Fine, if you want to be that way be that way.  Don&#8217;t use the settings features built in to the framework.  But whatever you do don&#8217;t embed this stuff into the application code.  If your smart and have been using a data access layer (DAL) like nhibernate or netTiers then getting and storing these values in the database should be trivial.  While up front it&#8217;s a bit more of a pain, on the back end it is easier because then for each instance of your application running you don&#8217;t have to modify the settings file and deploy to each application.  You just get the values out of the database.</p>
<p>Well, that&#8217;s it for now.  Hopefully you all might be interested in this and if you aren&#8217;t you&#8217;ll still be getting the code.  Doing a series like this is easy for me and allows me more time to do real work so there <img src='http://www.formatexception.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Next time we&#8217;ll look at DALs and refactoring.</p>
<p>Later &#8216;yall,<br />
Brian</p>



Share and Enjoy:


	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.formatexception.com%2F2008%2F09%2Ffirst-in-a-series-of-many%2F&amp;t=First%20in%20a%20series%20of%20many" title="Facebook"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.formatexception.com%2F2008%2F09%2Ffirst-in-a-series-of-many%2F&amp;t=First%20in%20a%20series%20of%20many" title="HackerNews"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/hackernews.png" title="HackerNews" alt="HackerNews" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://www.formatexception.com/2008/09/first-in-a-series-of-many/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The labmda says, &#8220;baaaaa&#8221;</title>
		<link>http://www.formatexception.com/2008/09/the-labmda-says-baaaaa/</link>
		<comments>http://www.formatexception.com/2008/09/the-labmda-says-baaaaa/#comments</comments>
		<pubDate>Wed, 17 Sep 2008 15:38:48 +0000</pubDate>
		<dc:creator>Brian</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://www.formatexception.com/?p=54</guid>
		<description><![CDATA[ LINQ allows you do define simple functions/methods in-line with the query you are doing.  These are called lambda expressions. They have a special format to allow for in-line expressions.   Take a look at: c =&#62; c + 1 Basically this is: for each value c give me c + 1 Rather then complicating things [...]]]></description>
			<content:encoded><![CDATA[<p><!--StartFragment --> LINQ allows you do define simple functions/methods in-line with the query you are doing.  These are called lambda expressions.</p>
<p>They have a special format to allow for in-line expressions.  </p>
<p>Take a look at:</p>
<p>c =&gt; c + 1</p>
<p>Basically this is:<br />
for each value c give me c + 1</p>
<p>Rather then complicating things with full-blown LINQ queries lets cheat and just use simple arrays.  For example:
<div style="background-color: #FFF;"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;;">int</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;">[] myInts = { 1, 9, 2, 8, 3, 7, 4, 6, 5 };</span><br class="MsoNormal" /><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;;">var</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;"> largeInts = myInts.Where(x =&gt; x &gt; 5);</span></div>
<p><br/></p>
<p>The where clause requires a lambda expression that returns a boolean.  Here we&#8217;re saying:</p>
<p>for each value x give me values where x &gt; 5</p>
<p>Um, Brian, I have graduated college, this is kindergarten stuff.</p>
<p>Fine, lets go a bit more complicated:</p>
<div style="background-color: #FFF;"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;;">string</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;">[] digits = { <span style="color: #a31515;">&#8220;zero&#8221;</span>, <span style="color: #a31515;">&#8220;one&#8221;</span>, <span style="color: #a31515;">&#8220;two&#8221;</span>, <span style="color: #a31515;">&#8220;three&#8221;</span>, <span style="color: #a31515;">&#8220;four&#8221;</span>, <span style="color: #a31515;">&#8220;five&#8221;</span>, <span style="color: #a31515;">&#8220;six&#8221;</span>, <span style="color: #a31515;">&#8220;seven&#8221;</span>, <span style="color: #a31515;">&#8220;eight&#8221;</span>, <span style="color: #a31515;">&#8220;nine&#8221;</span> };</span><br class="MsoNormal" /><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;;">var</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;"> shortDigits = digits.Where((digit, index) =&gt; digit.Length &lt; index);</p>
<p></span></div>
<p><br/>That&#8217;s two, yes, two variables here. If you haven&#8217;t realized by now LINQ is really syntactic sugar.  When using arrays with LINQ, since all it is really going to do is just iterate over the values for you, you have access to an index variable that represents the index of where the query is.</p>
<p>Here it is saying<br />
for each digit and its corresponding index give me the values where the length of the digit string is less then the index</p>
<p>meaning shortDigits ends up having the values:</p>
<div style="background-color: #FFF;"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;">{ <span style="color: #a31515;">&#8220;five&#8221;</span>, <span style="color: #a31515;">&#8220;six&#8221;</span>, <span style="color: #a31515;">&#8220;seven&#8221;</span>, <span style="color: #a31515;">&#8220;eight&#8221;</span>, <span style="color: #a31515;">&#8220;nine&#8221;</span> }</span></div>
<p><br/></p>
<p>Now, before we go too far I need to take a step back and clarify something from the last post.  Remember I gave a basic LINQ statement as:</p>
<div style="background-color: #FFF;"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;;">var</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;"> sortedFiles = <span style="color: blue;">from</span> file <span style="color: blue;">in</span> files <span style="color: blue;">orderby</span> file.LastWriteTime <span style="color: blue;">descending</span> <span style="color: blue;">select</span> file;</span></div>
<p><br/></p>
<p>and then went on to say:</p>
<div style="background-color: #FFF;"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;"><span style="color: blue;">from</span> file <span style="color: blue;">in</span> files</span></div>
<p>basically for each file in our files list</p>
<div style="background-color: #FFF;"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;"><span style="color: blue;">orderby</span> file.LastWriteTime</span></div>
<p>LastWriteTime is a property on FileInfo.  files is a list of FileInfo, therefore each file is a FileInfo object.  Intelli-sense is fully supported here so when you type in file and put the dot is shows you all the properties on file as if it were a standardly declared FileInfo.</p>
<div style="background-color: #FFF;"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;"><span style="color: blue;">descending</span></span></div>
<p>Like a standard DESC to an orderby clause.  Like sql it implicitly orders by ASC so if you want descending you have to add it.</p>
<div style="background-color: #FFF;"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;"><span style="color: blue;">select</span> file</span></div>
<p>return the file that applies to the orderby clause.  This may seem a bit redundant and I would agree but it is still needed.</p>
<p>Okay, now that you have read this for a second time I really want to address that last section.  It is only redundant when you want the full object available in the list.  If all I wanted was a list of file names I would do:</p>
<div style="background-color: #FFF;"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;;">var</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;"> sortedFiles = <span style="color: blue;">from</span> file <span style="color: blue;">in</span> files <span style="color: blue;">orderby</span> file.LastWriteTime <span style="color: blue;">descending</span> <span style="color: blue;">select</span> file.Name;</span></div>
<p><br/></p>
<p>Yes, you can return a single property from the object.</p>
<p>BUT WAIT, THERE&#8217;S MORE!</p>
<p>Yes, Ron Popeil here with the amazing Create-The-Object-On-The-Fly ability of LINQ and the 3.5 framework.</p>
<p>That&#8217;s right, Set It and Forget it! and it will generate types ON THE FLY!!!</p>
<p>Say I not only want the file name but also want the time when the file was created (CreationTime).  Well, just add that to your LINQ and now you have an IEnumerable with two properties:</p>
<div style="background-color: #FFF;"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;;">var</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;"> sortedFiles = <span style="color: blue;">from</span> file <span style="color: blue;">in</span> files <span style="color: blue;">orderby</span> file.LastWriteTime <span style="color: blue;">descending</span> <span style="color: blue;">select</span> <span style="color: blue;">new</span> { file.Name, file.CreationTime };</span></div>
<p><br/></p>
<p>Yes, here you can see the real power of the var.  sortedFiles is now a list consisting of some object (really a System.Linq.Enumerable.SelectIterator&lt;System.IO.FileInfo,&lt;string,System.DateTime&gt;&gt; object) that has the properties Name and CreationTime.  This ability is called Anonymous Types.</p>
<p>Taking this idea one step further, remember that a LINQ query is really just SQL you can put in your code to enumerate over lists.</p>
<p>That&#8217;s it Brian, your f-in with me!</p>
<p>Yes, yes I am.</p>
<p>Wow, deja vu.</p>
<p>As you have seen the ability to create anonymous types on the fly as well as using lambda expressions aren&#8217;t really just simply enumerating over a list.  But back to the sql idea.  Let&#8217;s do a join in a LINQ query.</p>
<p>Say we have a Product class that looks like:</p>
<div style="background-color: #FFF;"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;;">public</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;"> <span style="color: blue;">class</span> <span style="color: #2b91af;">Product</span></span><br class="MsoNormal" /><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;">{</span><br class="MsoNormal" /><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;;">    public</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;"> <span style="color: blue;">int</span> ProductId;</span><br />
<span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;;">    public</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;"> <span style="color: blue;">string</span> Name;</span><br />
<span style="font-size: 10pt; font-family: &quot;Courier New&quot;;">}</span></div>
<p><br/></p>
<p>and an Inventory class that looks like:</p>
<div style="background-color: #FFF;"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;;">public</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;"> <span style="color: blue;">class</span> <span style="color: #2b91af;">Inventory</span></span><br />
<span style="font-size: 10pt; font-family: &quot;Courier New&quot;;">{</span><br />
<span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;;">    public</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;"> <span style="color: blue;">int</span> InventoryId;</span><br />
<span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;;">    public</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;"> <span style="color: blue;">int</span> ProductId;</span><br />
<span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;;">    public</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;"> <span style="color: blue;">int</span> NumberOnHand;</span><br />
<span style="font-size: 10pt; font-family: &quot;Courier New&quot;;">}</span></div>
<p><br/></p>
<p>now take a look at this:</p>
<div style="background-color: #FFF;"><span style="font-size: 10pt; color: #2b91af; font-family: &quot;Courier New&quot;;">List</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;">&lt;<span style="color: #2b91af;">Inventory</span>&gt; InventoryList = <span style="color: blue;">new</span> <span style="color: #2b91af;">List</span>&lt;<span style="color: #2b91af;">Inventory</span>&gt;();</span><br class="MsoNormal" /><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;">InventoryList.Add(<span style="color: blue;">new</span> <span style="color: #2b91af;">Inventory</span> { ProductId = 1, NumberOnHand = 3 });</span><br class="MsoNormal" /><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;">InventoryList.Add(<span style="color: blue;">new</span> <span style="color: #2b91af;">Inventory</span> { ProductId = 2, NumberOnHand = 0 });</span><br />
<br class="MsoNormal" /><span style="font-size: 10pt; color: #2b91af; font-family: &quot;Courier New&quot;;">List</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;">&lt;<span style="color: #2b91af;">Product</span>&gt; ProductList = <span style="color: blue;">new</span> <span style="color: #2b91af;">List</span>&lt;<span style="color: #2b91af;">Product</span>&gt;();</span><br />
<span style="font-size: 10pt; font-family: &quot;Courier New&quot;;">ProductList.Add(<span style="color: blue;">new</span> <span style="color: #2b91af;">Product</span> { ProductId = 1, Name = <span style="color: #a31515;">&#8220;Apple&#8221;</span> });</span><br />
<span style="font-size: 10pt; font-family: &quot;Courier New&quot;;">ProductList.Add(<span style="color: blue;">new</span> <span style="color: #2b91af;">Product</span> { ProductId = 2, Name = <span style="color: #a31515;">&#8220;Orange&#8221;</span> });</span><br />
   <br class="MsoNormal" /><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;;">var</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;"> ProductsInInventory = <span style="color: blue;">from</span> InventoryItem <span style="color: blue;">in</span> InventoryList</span><br />
<span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;;">                  join</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;"> ProductItem <span style="color: blue;">in</span> ProductList</span><br />
                                   <span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;;">on</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;"> InventoryItem.ProductId <span style="color: blue;">equals</span> ProductItem.ProductId</span><br />
<span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;;">                 where</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;"> InventoryItem.NumberOnHand &gt; 0</span><br />
<span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;;">                 select</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;;"> <span style="color: blue;">new</span> { ProductItem.Name, InventoryItem.NumberOnHand };</span></div>
<p><br/></p>
<p>    <br />
But Brian, that&#8217;s not how it&#8217;s done in SQL.  </p>
<p>Well, really inner voice?  Like I&#8217;ve never done SQL before.</p>
<p>Wasn&#8217;t the medication supposed to stop you from hearing me?  &#8216;Cause it doesn&#8217;t seem to be doing a great job.</p>
<p>Oh that?  Stopped takin&#8217; it.  Figured without my inner voice I was just talking to myself.</p>
<p>But yes, Inner Voice is correct, that is not how it&#8217;s done.  But I did say that LINQ was like sql, not exactly sql.</p>
<p>The way a join is done is a bit different then in SQL when doing an implicit inner join but it is still pretty simple and actually very similar to doing an explicit inner join.  We just get so used to doing implicit joins we forget about explicit joins.  Once again, things are done in LINQ to facilitate the compiler optimizations and Intelli-sense.</p>
<p>Well, now your foot is wet and I&#8217;ve taken you a bit further into the world of LINQ.  Next on the topic is more on lambda expressions and other types of joins.</p>
<p>Later &#8216;yall,<br />
Brian (and his inner voice)</p>



Share and Enjoy:


	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.formatexception.com%2F2008%2F09%2Fthe-labmda-says-baaaaa%2F&amp;t=The%20labmda%20says%2C%20%22baaaaa%22" title="Facebook"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.formatexception.com%2F2008%2F09%2Fthe-labmda-says-baaaaa%2F&amp;t=The%20labmda%20says%2C%20%22baaaaa%22" title="HackerNews"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/hackernews.png" title="HackerNews" alt="HackerNews" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://www.formatexception.com/2008/09/the-labmda-says-baaaaa/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tiptoe Through the Tulips &#8230; LINQeses&#8230;es</title>
		<link>http://www.formatexception.com/2008/09/tiptoe-through-the-tulips-linqeseses/</link>
		<comments>http://www.formatexception.com/2008/09/tiptoe-through-the-tulips-linqeseses/#comments</comments>
		<pubDate>Wed, 17 Sep 2008 15:30:20 +0000</pubDate>
		<dc:creator>Brian</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[Reflection]]></category>

		<guid isPermaLink="false">http://www.formatexception.com/?p=50</guid>
		<description><![CDATA[ As most can attest when launching into the world of WPF you have to jump in and hope you can figure out how to swim before you drown.  It has a huge learning curve but the end results are usually pretty amazing. LINQ, on the other hand, you can slowly dip a toe in, see how [...]]]></description>
			<content:encoded><![CDATA[<p><!--StartFragment --> As most can attest when launching into the world of WPF you have to jump in and hope you can figure out how to swim before you drown.  It has a huge learning curve but the end results are usually pretty amazing.</p>
<p>LINQ, on the other hand, you can slowly dip a toe in, see how tepid the water is, and then slowly immerse your whole body sliding into the warm 98 degree water.  Over the course of 7 months now I have been slowing dipping into the water called LINQ and wanted to give you a few examples where I found it particularly useful.  Unlike a cruel father I will not throw you into the water and hope you can swim but want to slowly lead you into the fold.</p>
<p>So what the hell is LINQ?  Well, it stands for Language INtegrated Query.  It is a way to query lists in code.  Really that&#8217;s it.  You&#8217;re f-in me Brian, aren&#8217;t you?  Yes, yes I am.  That is the fundamental idea behind LINQ but it can do so much more.</p>
<p>I suppose I should start with the var keyword.  You VB fans will cheer at this.  var is a variable declaration where the type of the variable is implicit in the constructor of the item being created.  This is similar to the Dim except that we are still statically typed here.  In .Net 3.5 the var keyword can be used anywhere you are defining a variable that the type can be implied.</p>
<p>Good Examples:</p>
<div style="background-color: #FFF;">
<tt><span style="color: #3333ff;">var</span> myInt = 3;<br />
<span style="color: #3333ff;">var</span> myDouble = 2.2;<br />
<span style="color: #3333ff;">var</span> files = new <span style="color: #00cccc;">List</span>&lt;<span style="color: #00cccc;">FileInfo</span>&gt;();</tt></div>
<p><br/></p>
<p>Bad Examples:</p>
<div style="background-color: #FFF;">
<tt><span style="color: #3333ff;">var</span> myDouble = 3;<span style="color: #33cc00;">//not a double and myDouble will actually be an int</span><br />
<span style="color: #3333ff;">var</span> myString = <span style="color: #3333ff;">null</span>;<span style="color: #33cc00;">//type cannot be implied, will result in compile error</span></tt></div>
<p><br/></p>
<p>The easiest use for LINQ is in sorting.  No more needing to define an IComparable, just define your sort in an orderby clause.  LINQ has some similarities to writing SQL except that in order to facilitate compilation and intelli-sense the order of the query is a bit different.</p>
<p>Take this code for example:</p>
<div style="background-color: #FFF;"><tt><span style="color: #33cc00;">//START CODE</span><br />
<span style="color: #3333ff;">var</span> files = <span style="color: #3333ff;">new</span> <span style="color: #00cccc;">List</span>&lt;<span style="color: #00cccc;">FileInfo</span>&gt;();<br />
<span style="color: #3333ff;">var</span> ArchiveDirectory = <span style="color: #990000;">"C:\Archive"</span>;<br />
<span style="color: #3333ff;">var</span> archivedFiles = <span style="color: #00cccc;">Directory</span>.GetFiles(ArchiveDirectory);<span style="color: #33cc00;">//will be of type string []</span><br />
<span style="color: #3333ff;">foreach</span> (<span style="color: #3333ff;">var</span> filePath <span style="color: #3333ff;">in</span> archivedFiles)<br />
{<br />
    <span style="color: #3333ff;">var</span> fi = <span style="color: #3333ff;">new</span> <span style="color: #00cccc;">FileInfo</span>(filePath);<br />
    files.Add(fi);<br />
}<br />
<span style="color: #33cc00;">//now sort the file list based on last write time</span><br />
<span style="color: #3333ff;">var</span> sortedFiles = <span style="color: #3333ff;">from </span>file <span style="color: #3333ff;">in </span>files <span style="color: #3333ff;">orderby </span>file.LastWriteTime <span style="color: #3333ff;">descending select</span> file;<br />
<span style="color: #33cc00;">//END CODE</span></tt></div>
<p><br/></p>
<p>Now, up until that last line it is standard C#.  The last line appears to be some sort of odd jacked-up sql.  If we break it down, however, you will see the power.</p>
<div style="background-color: #FFF;"><tt><span style="color: #3333ff;">from </span>file <span style="color: #3333ff;">in </span>files</tt></div>
<p>basically for each file in our files list</p>
<div style="background-color: #FFF;"><tt><span style="color: #3333ff;">orderby </span>file.LastWriteTime</tt></div>
<p>LastWriteTime is a property on FileInfo.  files is a list of FileInfo, therefore each file is a FileInfo object.  Intelli-sense is fully supported here so when you type in file and put the dot it shows you all the properties on file as if it were a standardly declared FileInfo.</p>
<div style="background-color: #FFF;"><span style="color: #3333ff;"><tt>descending</tt></span></div>
<p>Like a standard DESC to an orderby clause.  Like sql it implicitly orders by ASC so if you want descending you have to add it.</p>
<div style="background-color: #FFF;"><tt><span style="color: #3333ff;">select </span>file</tt></div>
<p>return the file that applies to the orderby clause.  The may seem a bit redundant and I would agree but it is still needed.</p>
<p>See?  Pretty simple.  No need to write an IComparable just order the list by the LastWriteTime.</p>
<p>So let&#8217;s take this a step further.</p>
<p>I have an example where I have three different tables all of which have the property &#8220;Name&#8221;.  I need to populate three different combo boxes with the values from each of the different tables.  Now I could write a whole bunch of code to do each table values and combo boxes separately but, well, nah!</p>
<p>Here we&#8217;re going to go a bit extreme.  Use a bit of LINQ, throw in some Generics and finally whip it all together with some Reflection.</p>
<p>Start with getting each list and ordering it by name</p>
<div style="background-color: #FFF;"><tt><span style="color: #33cc00;">//START CODE</span><br />
<span style="color: #3333ff;">var </span>sortedTypes = <span style="color: #3333ff;">from </span>type <span style="color: #3333ff;">in new </span><span style="color: #00cccc;">TypeService</span>().GetAll() <span style="color: #3333ff;">orderby </span>type.Name <span style="color: #3333ff;">select </span>type;<br />
<span style="color: #3333ff;">var </span>sortedFreqs = <span style="color: #3333ff;">from </span>freq <span style="color: #3333ff;">in new</span> <span style="color: #00cccc;">FrequencyService</span>().GetAll() <span style="color: #3333ff;">orderby </span>freq.Name <span style="color: #3333ff;">select </span>freq;<br />
<span style="color: #3333ff;">var </span>sortedEvents = <span style="color: #3333ff;">from </span>event <span style="color: #3333ff;">in new </span><span style="color: #00cccc;">EventService</span>().GetAll() <span style="color: #3333ff;">orderby </span>event.Name <span style="color: #3333ff;">select </span>event;<br />
<span style="color: #33cc00;">//END CODE</span></tt></div>
<p><br/></p>
<p>Well, that should be pretty straight forward now.  We can see the GetAll method of each service returns all the values from a table in the form of a list.  The we use the orderby clause in LINQ to sort it for us by the name.</p>
<p>Now let&#8217;s populate the combo boxes in the form:</p>
<div style="background-color: #FFF;"><tt><span style="color: #33cc00;">//START CODE</span><br />
PopulateComboBox&lt;<span style="color: #00cccc;">Type</span>&gt;(sortedTypes, cboType);<br />
PopulateComboBox&lt;<span style="color: #00cccc;">Frequency</span>&gt;(sortedFreqs, cboFrequency);<br />
PopulateComboBox&lt;<span style="color: #00cccc;">Event</span>&gt;(sortedEvents, cboEvent);<br />
<span style="color: #33cc00;">//END CODE</span></tt></div>
<p><br/></p>
<p>And thats all there is.  Pretty simple, huh?<br />
Oh, you want to see what the hell PopulateComboBox does.  Fine, be that way.</p>
<div style="background-color: #FFF;"><tt><span style="color: #33cc00;">//START CODE</span><br />
<span style="color: #3333ff;">private void </span>PopulateComboBox&lt;T&gt;(System.Linq.<span style="color: #00cccc;">IOrderedEnumerable</span>&lt;T&gt; List, <span style="color: #00cccc;">ComboBox </span>Box)<br />
{<br />
    <span style="color: #3333ff;">foreach </span>(T val <span style="color: #3333ff;">in </span>List)<br />
    {<br />
        <span style="color: #00cccc;">ComboBoxItem </span>cbi = new <span style="color: #00cccc;">ComboBoxItem</span><br />
            {<br />
                Content = FindReflectedProperty(val, <span style="color: #990000;">"Name"</span>),<br />
                Tag = val<br />
            };<br />
        Box.Items.Add(cbi);<br />
    }<br />
}<br />
<span style="color: #33cc00;">//END CODE</span></tt><span style="color: #33cc00;"><br />
</span></div>
<p><br/><br />
As you can see we can&#8217;t take a var on the first value of the parameter since it&#8217;s type cannot be inferred.  As it would happen using the orderby clause in a LINQ query returns a list with the interface System.Linq.IOrderedEnumerable.  We use the good ole&#8217; generics typeparam when calling the method so at runtime the code knows the type of T.  Additionally you can see that when creating the ComboBoxItem we use the new feature in 3.5 of setting properties on the objects when creating the object (really this happens right after the constructor is called).  The final bit to this is FindReflectedProperty.</p>
<div style="background-color: #FFF;"><tt><span style="color: #33cc00;">//START CODE</span><br />
<span style="color: #3333ff;">public static object </span>FindReflectedProperty(<span style="color: #3333ff;">object </span>Instance, <span style="color: #3333ff;">string </span>PropName)<br />
{<br />
    <span style="color: #3333ff;">if </span>(Instance == <span style="color: #3333ff;">null</span>)<br />
        <span style="color: #3333ff;">return null</span>;<br />
    <span style="color: #3333ff;">foreach </span>(<span style="color: #00cccc;">PropertyInfo </span>pi <span style="color: #3333ff;">in </span>Instance.GetType().GetProperties())<br />
    {<br />
        <span style="color: #3333ff;">if </span>(pi.Name == PropName)<br />
            <span style="color: #3333ff;">return </span>pi.GetValue(Instance, <span style="color: #3333ff;">null</span>);<br />
    }<br />
    <span style="color: #3333ff;">return null</span>;<br />
}<br />
<span style="color: #33cc00;">//END CODE</span></tt></div>
<p><br/></p>
<p>Getting the PropertyInfo on the instance passed in we are able to get the value of the property based on the property name.  Of course we can turn this method into more LINQ but I&#8217;ll leave that to the next in the series where we&#8217;ll dip our whole foot in, which should excite all you foot appreciators (or fetishes or whatever).  If you want to read ahead google LINQ Lambda.</p>
<p>And now your toe is wet, assuming you got this far.</p>
<p>Later &#8216;yall,<br />
Brian</p>



Share and Enjoy:


	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.formatexception.com%2F2008%2F09%2Ftiptoe-through-the-tulips-linqeseses%2F&amp;t=Tiptoe%20Through%20the%20Tulips%20...%20LINQeses...es" title="Facebook"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.formatexception.com%2F2008%2F09%2Ftiptoe-through-the-tulips-linqeseses%2F&amp;t=Tiptoe%20Through%20the%20Tulips%20...%20LINQeses...es" title="HackerNews"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/hackernews.png" title="HackerNews" alt="HackerNews" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://www.formatexception.com/2008/09/tiptoe-through-the-tulips-linqeseses/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>GoTo: goto GoTo;</title>
		<link>http://www.formatexception.com/2008/09/goto-goto-goto/</link>
		<comments>http://www.formatexception.com/2008/09/goto-goto-goto/#comments</comments>
		<pubDate>Wed, 17 Sep 2008 15:11:41 +0000</pubDate>
		<dc:creator>Brian</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.formatexception.com/?p=36</guid>
		<description><![CDATA[ Recently while looking over the shoulder&#8217;s of some fellow devs I was witness to something disturbing.  If you haven&#8217;t guessed by now it was a goto statement.  An intern we used to have had used gotos in a switch(case) statement since in C# switch(case) doesn&#8217;t allow fall-through. You have to do: int shippingOption = getShippingOption(); [...]]]></description>
			<content:encoded><![CDATA[<p><!--StartFragment --> Recently while looking over the shoulder&#8217;s of some fellow devs I was witness to something disturbing.  If you haven&#8217;t guessed by now it was a goto statement.  An intern we used to have had used gotos in a switch(case) statement since in C# switch(case) doesn&#8217;t allow fall-through.</p>
<p>You have to do:</p>
<pre>int shippingOption = getShippingOption();
switch(shippingOption)       
      {         
         case 1:   
            cost += 25;
            goto case 2;                 
         case 2:            
            cost += 25;
            goto case 3;           
         case 3:            
            cost += 50;
            break;       
         default:            
            Console.WriteLine("Please select 1, 2, or 3.");            
            break;      
       }</pre>
<p>I have to admit that this is the only situation where I feel gotos should be allowed.  The problem with the code that they were looking at looked more like:</p>
<pre>switch (n)
    {
    case StaticVar1:
        if (statusVariable == 0)
        goto StaticVar3;
        statusVariable = 9;
        DoSomething();
        if (statusVariable == 3)
        goto StaticVar2;
    case StaticVar2:
        if (statusVariable == 0)
        goto StaticVar3;
        statusVariable = DoSomething2();
        goto StaticVar1;
    case StaticVar3:
        if (statusVariable == 0)
        break;
        statusVariable = DoSomething3();
        if (statusVariable == 2)
        goto StaticVar2;
...insert a whole bunch more...
    default:
        break;
    }</pre>
<p>    <br />
which really had more like 10 different cases.  The problem is that he wasn&#8217;t using the gotos to do fall-through.  He was using them like your classic old VB days of gotos.  </p>
<p>Hopefully we all know who Dijkstra is.  Dijkstra is well-known for two things in his career as a computer scientist.  The first thing, of course, is Dijkstra&#8217;s algorithm for best pathing.  If you have ever had to implement a best path algorithm Dijkstra&#8217;s is simple to do, pretty straight forward and it works.  Of course since he created it back in the 60&#8242;s others have come out that improve on his best path algorithm but still at the core of the improved algorithms are Dijkstra&#8217;s algorithm.  I mean, come on, he has an algorithm named after him, wouldn&#8217;t that be cool?  Anyways, the second thing he is known for is his article &#8220;Go To Statement Considered Harmful&#8221; in the March 1968 <em>Communications of the ACM</em>.</p>
<p>&#8220;Dijkstra observed that the quality of code was inversely proportional to the number of gotos the programmer used.&#8221; (McConnell, 2004)  </p>
<p>So what?  The code works.  </p>
<p>Well, not really.  As McConnell says above, speaking on Dijkstra&#8217;s article, the quality of the code was inversely proportional to the number of gotos.  That&#8217;s right, more bugs, harder to troubleshoot, harder to maintain.</p>
<p>Additionally gotos break the fundamental concept of software development that code within a method (procedure, function) flows from top to bottom.</p>
<p>Fine Brian, I still don&#8217;t believe you and you suck.  I mean how are we supposed to handle OnError in VB.Net?</p>
<p>Um, by following the preferred methods of handling exceptions as outlined in:<br />
<a class="moz-txt-link-freetext" href="http://msdn.microsoft.com/en-us/library/aa289194.aspx">http://msdn.microsoft.com/en-us/library/aa289194.aspx</a><br />
which is an article entitled &#8220;Life Without On Error Goto Statements&#8221;</p>
<p>Well, fine but goto statements allow for faster and cleaner code.</p>
<p>Um, no it doesn&#8217;t.</p>
<p>&#8220;Goto statements break the flow of code tending to thwart compiler optimization actually leading to slower executing code&#8221; (McConnell, 2004)</p>
<p>Now, a follow up letter to the ACM was published in March of 1987 (yeah, 20 years later) entitled &#8220;&#8216;GOTO Considered Harmful&#8217; Considered Harmful&#8221; by Frank Rubin, in which the he gave what he considered the seminal example for goto statements, when gotos should be used and the advantage they gave.  The letter was followed by over 50 responses, some of which supported Frank but quite a few gave samples where his goto example would be better served as a method call or some other preferred way other then a goto.</p>
<p>I have looked at millions upon millions of lines of code, most of which is other people&#8217;s code.  It truly is a great learning experience.  The example at the top for fall-through are the only time I&#8217;ve seen that gotos might be used.  Even in the example at the top the goto&#8217;s really aren&#8217;t needed and be worked another way.</p>
<p>I could spend sometime analyzing all the arguments for gotos but unfortunately I don&#8217;t have that time.  Studies show goto statements hurt code.  That&#8217;s all there is.  Want to get out of deeply nested loops?  Use status variables instead of gotos.  Want to move within a switch(case)?  Don&#8217;t.  It&#8217;s bad programming and can be done with a small bit of code duplication that will end up saving cycles in compiler optimization and code maintenance.  Sure you save a few seconds coding but in reality you&#8217;re costing yourself and/or your organization a lot more in maintenance.</p>
<p>If you&#8217;re used to using gotos help out your fellow man (or maintenance programmer) and spend a few more minutes working without gotos.</p>
<p>We all will thank you.</p>
<p>Every time you forward this to someone a kitten won&#8217;t get kicked.  Think of the kittens.</p>
<p>Brian</p>
<p>Refs (Additional Reading):<br />
<em>Code Complete</em> (Second Edition), Microsoft Press, Steve McConnell, 2004</p>
<p>Life Without On Error Goto Statements, Deborah Kurata, July 11, 2003<br />
<a class="moz-txt-link-freetext" href="http://msdn.microsoft.com/en-us/library/aa289194.aspx">http://msdn.microsoft.com/en-us/library/aa289194.aspx</a></p>
<p>I&#8217;d Consider That Harmful, Too, Jeff Atwood, October 25, 2007<br />
<a class="moz-txt-link-freetext" href="http://www.codinghorror.com/blog/archives/000982.html">http://www.codinghorror.com/blog/archives/000982.html</a></p>
<p>goto (C# Reference), November 2007<br />
<a class="moz-txt-link-freetext" href="http://msdn.microsoft.com/en-us/library/13940fs2.aspx">http://msdn.microsoft.com/en-us/library/13940fs2.aspx</a></p>
<p><em>Go To Statement Considered Harmful</em> (see also <em>A Case against the GO TO Statement</em>), E.W. Dijkstra<br />
Association for Computing Machinery (ACM), Communications of the ACM, March 1968</p>



Share and Enjoy:


	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.formatexception.com%2F2008%2F09%2Fgoto-goto-goto%2F&amp;t=GoTo%3A%20goto%20GoTo%3B" title="Facebook"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.formatexception.com%2F2008%2F09%2Fgoto-goto-goto%2F&amp;t=GoTo%3A%20goto%20GoTo%3B" title="HackerNews"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/hackernews.png" title="HackerNews" alt="HackerNews" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://www.formatexception.com/2008/09/goto-goto-goto/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WPF &#8211; ContentProperty, it&#8217;s that simple</title>
		<link>http://www.formatexception.com/2008/09/wpf-contentproperty-its-that-simple/</link>
		<comments>http://www.formatexception.com/2008/09/wpf-contentproperty-its-that-simple/#comments</comments>
		<pubDate>Wed, 17 Sep 2008 15:06:42 +0000</pubDate>
		<dc:creator>Brian</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.formatexception.com/?p=32</guid>
		<description><![CDATA[So there I am, creating a custom control called &#8220;RequiredLabel&#8221; that interestingly enough is a label that has a cool icon in it to show that whatever it is being used for is required. The control has two properties, Text that is the text of the label and Style that is the style of the [...]]]></description>
			<content:encoded><![CDATA[<p>So there I am, creating a custom control called &#8220;RequiredLabel&#8221; that<br />
interestingly enough is a label that has a cool icon in it to show that<br />
whatever it is being used for is required. The control has two<br />
properties, Text that is the text of the label and Style that is the<br />
style of the label. Both are registered as dependency properties so<br />
that they can be set in the xaml. I suppose it would have been fine to<br />
simply leave good enough as good enough but I wanted it so that in the<br />
xaml you can put the text for the label between the start and end tag<br />
for required label. It is simply expected behavior the the content of<br />
your control can be put in that way.</p>
<p>After much soul searching (i.e. Googling) I still couldn&#8217;t find the<br />
answer. How do I make one of my dependency properties the content that<br />
is between the tags? Well, thankfully I had an epiphany and remembered<br />
that somewhere deep in one of my WPF books the answer was held. It is<br />
as simple as putting the attribute above the class declaration with the<br />
dependency property name.</p>
<p>[ContentProperty("Text")]<br />
public partial class RequiredLabel : UserControl<br />
{</p>
<p>This makes it so that when I use my custom control it will look like:</p>
<p>&lt;customControls:RequiredLabel x:Name=&#8221;lblType&#8221; Style=&#8221;{StaticResource<br />
LabelGradient}&#8221;&gt;<br />
                            Defendant&#8217;s Name:<br />
 &lt;/customControls:RequiredLabel&gt;</p>
<p>It also makes it so that if I decide to extend the content to support<br />
user controls instead of just text really easy since I can switch out<br />
the TextBlock that makes up the user control to a panel.</p>
<p>Also if you want to get a glimmer of using dependency properties see<br />
attached code.</p>
<p><a href="http://www.formatexception.com/post_attachments/contentproperty/RequiredLabel.xaml">RequiredLabel.xaml</a><br />
<a href="http://www.formatexception.com/post_attachments/contentproperty/RequiredLabel.xaml.cs">RequiredLabel.xaml.cs</a></p>
<p>Brian</p>



Share and Enjoy:


	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.formatexception.com%2F2008%2F09%2Fwpf-contentproperty-its-that-simple%2F&amp;t=WPF%20-%20ContentProperty%2C%20it%27s%20that%20simple" title="Facebook"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.formatexception.com%2F2008%2F09%2Fwpf-contentproperty-its-that-simple%2F&amp;t=WPF%20-%20ContentProperty%2C%20it%27s%20that%20simple" title="HackerNews"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/hackernews.png" title="HackerNews" alt="HackerNews" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://www.formatexception.com/2008/09/wpf-contentproperty-its-that-simple/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>WPF and MousePosition</title>
		<link>http://www.formatexception.com/2008/09/wpf-and-mouseposition/</link>
		<comments>http://www.formatexception.com/2008/09/wpf-and-mouseposition/#comments</comments>
		<pubDate>Wed, 17 Sep 2008 14:57:55 +0000</pubDate>
		<dc:creator>Brian</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.formatexception.com/?p=27</guid>
		<description><![CDATA[The way I thought it should be done (but it&#8217;s wrong): Point mousePoint = Mouse.GetPosition(this); MyWindow win = new MyWindow(); win.Left = mousePoint.X; win.Top = mousePoint.Y; win.ShowDialog(); &#8220;Mama Freeda! Dang window won&#8217;t go where I put it!&#8221; Okay, maybe I didn&#8217;t say &#8220;Mama Freeda&#8221; nor &#8220;Dang&#8221; but none the less it seems like when getting [...]]]></description>
			<content:encoded><![CDATA[<p>The way I thought it should be done (but it&#8217;s wrong):</p>
<pre name="code" class="csharp">Point mousePoint = Mouse.GetPosition(this);
MyWindow win = new MyWindow();
win.Left = mousePoint.X;
win.Top = mousePoint.Y;
win.ShowDialog();</pre>
<p>&#8220;Mama Freeda! Dang window won&#8217;t go where I put it!&#8221;</p>
<p>Okay, maybe I didn&#8217;t say &#8220;Mama Freeda&#8221; nor &#8220;Dang&#8221; but none the less it<br />
seems like when getting a mouse position in WPF and trying to open a new<br />
window relative to the mouse click is a pain.</p>
<p>Ah Luigi, but I have the solution <img src='http://www.formatexception.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>When setting the left and top properties in a wpf window they relate to<br />
the desktop coordinates. The new window could careless that it&#8217;s being<br />
popped up from a control underneath it.</p>
<p>The problem is that Mouse.GetPosition(this) returns the position<br />
relative to the &#8220;this&#8221; which is most likely the control that is trying<br />
to open the new window. Now if the control is the only control in the<br />
window, there is only one screen, the application is running on the<br />
primary screen and the application is maximized then your golden.</p>
<p>But screw that.</p>
<p>Well, how about using Mouse.GetPosition(Window.GetWindow(this))?</p>
<p>That returns the point relative to the window of the control (this).<br />
That should work won&#8217;t it? That only eliminates a single concern of<br />
ours, if the control is the only control in the window. There is still<br />
that the application must be only one screen, the application is running<br />
on the primary screen and the application must be maximized.</p>
<p>Brian, cut the Brother Stuart and just give us the simple answer!</p>
<p>Um, who&#8217;s Brother Stuart?</p>
<p>And why am I talking to myself like this?</p>
<p>The great thing about wpf controls is that they have the ability given a<br />
point to convert that point to screen (i.e. desktop) coordinates.</p>
<p>So here is easy answer (The way it should be done):</p>
<pre name="code" class="csharp">Point mousePoint = this.PointToScreen(Mouse.GetPosition(this));
MyWindow win = new MyWindow();
win.Left = mousePoint.X;
win.Top = mousePoint.Y;
win.ShowDialog();</pre>
<p>Basically get the mouse position relative to this control and then<br />
convert it out to the desktop coordinates so I can then use it when<br />
setting the left and top properties of a new window. This is great for<br />
pop-up windows that need to be close to a mouse click. The great thing<br />
about this is that since the mouse click position is now relative to the<br />
desktop this works on multi-screen monitors regardless of which monitor<br />
you have the application running on.</p>
<p>Later &#8216;yall,<br />
Brian</p>
<p>ref:<br />
Visual.PointToScreen<br />
<a href="http://msdn.microsoft.com/en-us/library/system.windows.media.visual.pointtoscreen.aspx">http://msdn.microsoft.com/en-us/library/system.windows.media.visual.pointtoscreen.aspx</a><br />
Mouse.GetPosition<br />
<a href="http://msdn.microsoft.com/en-us/library/system.windows.input.mouse.getposition.aspx">http://msdn.microsoft.com/en-us/library/system.windows.input.mouse.getposition.aspx</a><br />
Window.Top<br />
<a href="http://msdn.microsoft.com/en-us/library/system.windows.window.top.aspx">http://msdn.microsoft.com/en-us/library/system.windows.window.top.aspx</a></p>



Share and Enjoy:


	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.formatexception.com%2F2008%2F09%2Fwpf-and-mouseposition%2F&amp;t=WPF%20and%20MousePosition" title="Facebook"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.formatexception.com%2F2008%2F09%2Fwpf-and-mouseposition%2F&amp;t=WPF%20and%20MousePosition" title="HackerNews"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/hackernews.png" title="HackerNews" alt="HackerNews" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://www.formatexception.com/2008/09/wpf-and-mouseposition/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Generics, Params, IEnumerables (well, yield), Oh my!</title>
		<link>http://www.formatexception.com/2008/09/generics-params-ienumerables-yield/</link>
		<comments>http://www.formatexception.com/2008/09/generics-params-ienumerables-yield/#comments</comments>
		<pubDate>Wed, 17 Sep 2008 14:52:19 +0000</pubDate>
		<dc:creator>Brian</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[yield]]></category>

		<guid isPermaLink="false">http://www.formatexception.com/?p=20</guid>
		<description><![CDATA[Hello all, Well, what once was a simple weekly email about cool stuff I ran across while working in DotNet has suddenly become very complicated. I spoke briefly with the devs on Generics the other day and wanted to throw together a more concrete example of using them. In the attached solution you will find [...]]]></description>
			<content:encoded><![CDATA[<p>Hello all,</p>
<p>Well, what once was a simple weekly email about cool stuff I ran across while working in DotNet has suddenly become very complicated. I spoke briefly with the devs on Generics the other day and wanted to throw together a more concrete example of using them. In the <a href="http://www.formatexception.com/post_attachments/generics_params_ienumerables/GenericsParamsIEnumerable.zip">attached solution</a> you will find a quite thorough example of using generics in a BinaryTree class I wrote. It&#8217;s important to remember that T is simply a type and tells your code what type to expect. Please ignore the bit of kludge in the AddNode method between IComparable and IComparable&lt;T&gt;. This was meant to be thrown together and I didn&#8217;t want to spend too much time on it.</p>
<p><a href="http://www.formatexception.com/post_attachments/generics_params_ienumerables/GenericsParamsIEnumerable.zip">In case you missed it above, here is the attached solution</a></p>
<p>In looking at the code for Form1 you can see the generics in action in the button1_Click event. The power of generics really comes through for compile time issues with not having to worry about casting. Here we create trees for int, string and a class I added called City. Since City implements IComparable we can use it for the tree.</p>
<p>By declaring,</p>
<pre>BinaryTree&lt;int&gt; intTree = new BinaryTree&lt;int&gt;();</pre>
<p>we know we have a btree that has ints and without casting we can do with<br />
those ints as we please. Then any methods in the btree knows that the<br />
value is an int.</p>
<p>This btree example, however, has two other things that are pretty cool.<br />
The first is the use of an add method that takes<br />
params T[] Items</p>
<p>I love using params as it allows for variable length parameters on<br />
methods. Um, well, not a lot to say on params, just that they&#8217;re cool.</p>
<p>The other cool thing is the usage of yield in the ScanInOrder method.<br />
yield basically allows you to return from a method when iterating over a<br />
list of items where the code will remember where you were at so that you<br />
can return back to that position. The cool thing about using yield is<br />
that, as shown in the sample, you can use yield multiple times in the<br />
same method. As we all know for an InOrder traversal of a binary tree<br />
we basically move down the left side of the tree, give our value and<br />
then start working on the right side of the tree (well, y&#8217;all know its a<br />
bit more then that but I don&#8217;t think I have to explain it). Here in the<br />
ScanInOrder method of the BinaryTree class it recursively calls<br />
ScanInOrder on the left nodes of the tree items iterating in a foreach<br />
loop yielding each of the results. Then it returns it&#8217;s own result and<br />
finally recursively iterates in a foreach loop over the nodes on the<br />
right side of the tree yielding each of those results.</p>
<p>In the morning my son Edison and I watch Curious George together on the<br />
couch. Right before the cartoon starts KUAT does this cutesy animation<br />
with a song in the back ground that says, &#8220;Learn something new<br />
everyday. You learn a lot that way.&#8221; Hopefully I&#8217;ve helped with that<br />
goal, <img src='http://www.formatexception.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Brian</p>



Share and Enjoy:


	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.formatexception.com%2F2008%2F09%2Fgenerics-params-ienumerables-yield%2F&amp;t=Generics%2C%20Params%2C%20IEnumerables%20%28well%2C%20yield%29%2C%20Oh%20my%21" title="Facebook"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.formatexception.com%2F2008%2F09%2Fgenerics-params-ienumerables-yield%2F&amp;t=Generics%2C%20Params%2C%20IEnumerables%20%28well%2C%20yield%29%2C%20Oh%20my%21" title="HackerNews"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/hackernews.png" title="HackerNews" alt="HackerNews" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://www.formatexception.com/2008/09/generics-params-ienumerables-yield/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>?? Is the way of the WORLD, HAHAHA</title>
		<link>http://www.formatexception.com/2008/09/is-the-way-of-the-world-hahaha/</link>
		<comments>http://www.formatexception.com/2008/09/is-the-way-of-the-world-hahaha/#comments</comments>
		<pubDate>Tue, 16 Sep 2008 22:26:43 +0000</pubDate>
		<dc:creator>Brian</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[often unused operators]]></category>

		<guid isPermaLink="false">http://www.formatexception.com/?p=14</guid>
		<description><![CDATA[ Recently I gave a quick talk to the devs at the court house about the coalesce operator. So why do you care? Well, you probably don&#8217;t so just quit reading right now. For those of you that are still around the coalesce operator works like COALESCE in T-SQL. For instance: SELECT COALESCE( hourly_wage * 40 [...]]]></description>
			<content:encoded><![CDATA[<p><!--StartFragment --> Recently I gave a quick talk to the devs at the court house about the<br />
coalesce operator. So why do you care? Well, you probably don&#8217;t so<br />
just quit reading right now.</p>
<p>For those of you that are still around the coalesce operator works like<br />
COALESCE in T-SQL.</p>
<p>For instance:</p>
<pre>SELECT COALESCE(
hourly_wage * 40 * 52,
salary,
commission * num_sales) AS 'Total Salary' FROM wages</pre>
<p>Here in T-SQL we can see a simple select statement that will determine a<br />
person&#8217;s total salary regardless of if they are on wage, salaried or on<br />
commission since an employee on wage would have a null salary and null<br />
commission but an employee on salary would have a null wage and null<br />
commission.</p>
<p>Basically COALESCE uses the first value it finds that doesn&#8217;t result in<br />
a null.</p>
<p>So how can this help you?</p>
<p>Does this look familiar? (Um, I don&#8217;t really care if it looks familiar,<br />
just keep reading. You&#8217;ve come this far.)</p>
<pre>//set cust first name
if(cust.FirstName != null)
txtFirstName.Text = cust.Firstname;
else
txtFirstName.Text = "";</pre>
<p>Well, with the ?? (a.k.a. coalesce operator) you can trim this down to<br />
txtFirstName.Text = cust.FirstName ?? &#8220;&#8221;;</p>
<p>In T-SQL you can put an unlimited number of commas in the function to<br />
come up with a bunch of values to check. With the ?? operator you can<br />
just string them along, i.e.:</p>
<pre>txtFirstName.Text = cust.FirstName ?? cust.LastName ?? cust.Nickname ?? "Name not found";</pre>
<p>This can be taken a step further since ?? can be used with primitives.<br />
This makes it very nice when dealing with nullable primitives.<br />
Assuming MetaData has an Occurrence that is a int? you can get the<br />
occurrence like:</p>
<pre>int occurrence = MetaData.Occurrence ?? 0;</pre>
<p>No casting just nice code.<br />
Well, later &#8216;yall!</p>
<p>Brian</p>



Share and Enjoy:


	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.formatexception.com%2F2008%2F09%2Fis-the-way-of-the-world-hahaha%2F&amp;t=%3F%3F%20Is%20the%20way%20of%20the%20WORLD%2C%20HAHAHA" title="Facebook"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.formatexception.com%2F2008%2F09%2Fis-the-way-of-the-world-hahaha%2F&amp;t=%3F%3F%20Is%20the%20way%20of%20the%20WORLD%2C%20HAHAHA" title="HackerNews"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/hackernews.png" title="HackerNews" alt="HackerNews" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://www.formatexception.com/2008/09/is-the-way-of-the-world-hahaha/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

