﻿<?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>Programming By A Tool &#187; C#</title>
	<atom:link href="http://byatool.com/tag/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://byatool.com</link>
	<description>This is my recorded stumbling through ASP.Net, Framework 3.5, C# 3.0, Ajax, Javascript, and Love.  Stay, learn, destroy.  It's your life.</description>
	<lastBuildDate>Thu, 03 May 2012 17:28:21 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>ASP.Net MVC 2/C# 4â€¦ Dynamic Model and Should You Use It?</title>
		<link>http://byatool.com/pontification/asp-net-mvc-2c-4-dynamic-model-and-should-you-use-it/</link>
		<comments>http://byatool.com/pontification/asp-net-mvc-2c-4-dynamic-model-and-should-you-use-it/#comments</comments>
		<pubDate>Tue, 30 Nov 2010 00:11:53 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Pontification]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[ExpandoObject]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1826</guid>
		<description><![CDATA[So there&#8217;s a new sheriff in town and its name is dynamic. Actually, its not really that new and that&#8217;s a horribly misused cliche. My lack of literary genius aside, I&#8217;ve been looking for a reason to use dynamic. Then it came to me: Models. Now the only reason why I started down that path [...]]]></description>
			<content:encoded><![CDATA[<p>So there&#8217;s a new sheriff in town and its name is dynamic.  Actually, its not really that new and that&#8217;s a horribly misused cliche.  My lack of literary genius aside, I&#8217;ve been looking for a reason to use dynamic.  Then it came to me:  Models.  Now the only reason why I started down that path was the use of Python where pretty much anything is dynamic.  In using python, I got used to not embracing the rigidity of classes for models and adopted a more &#8220;Oh what the f&#8211;k&#8221; attitude.  Back in the .net world though, I was using typed views.  Then I readopted the &#8220;Oh what the f&#8211;k&#8221; attitude and applied it to .net mvc.</p>
<p>Here&#8217;s an example:</p>
<pre>    [<span style="color: #008080;">RequiresAuthentication</span>]
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">ActionResult</span> ShowBasicInfo()
    {
      <span style="color: #008080;">IState</span> currentState = ObjectFactory.Create();
      <span style="color: #0000ff;">dynamic</span> returnModel = <span style="color: #0000ff;">new</span> <span style="color: #008080;">ExpandoObject</span>();

      returnModel.UserName = currentState.CurrentUser.UserName;

      <span style="color: #0000ff;">return</span> View(AccountActions.ShowBasicInfo, returnModel);
    }
</pre>
<p>As you can see, I created a dynamic class and just added a property to it.  Now on the view side:</p>
<pre>...
<span style="color: #ff6600;">@model</span> dynamic
...
          &lt;<span style="color: #800000;">label</span> <span style="color: #0000ff;">id=</span><span style="color: #ff0000;">"showBasicInfoEmail"</span> <span style="color: #0000ff;">name=</span><span style="color: #ff0000;">"showBasicInfoEmail"</span>&gt;<span style="color: #ff6600;">@Model.UserName</span>&lt;/<span style="color: #800000;">label</span>&gt;
...
</pre>
<p>So if that&#8217;s all you&#8217;re here for, well there you go.   Now get out.</p>
<p>Ok so the real point to this post was actually the &#8220;should I?&#8221; Now with .Net, you really have to adopt a &#8220;should I?&#8221; attitude on anything that is new otherwise it might come back to bite you in the a&#8211;.  (Update panels anyone?)  Just using something because it looks easier is NOT a reason to do so.</p>
<p>The reason why I originally gravitated toward typed views was I didn&#8217;t like all the magic sting junk that came with the View dictionary, or whatever the hell it was called.  (I&#8217;m too lazy to look it up) Typed views gave a sort of concrete nature much like an interface does to a class.  You knew exactly WHAT the view could show based on the model.  This is good I still think in an environment where you don&#8217;t trust people to code correctly or when a person needs an easy place to look up what the incoming model contains.  After all, on the second point I mean, its a lot easier to look at a class to find EXACTLY what the model has than looking at a controller action code.  Simple for reference.</p>
<p>With that being said, getting stuck in model hell can happen. After all for every action there is an equal and&#8230; wait&#8230; there is a model.  Yeah you can reuse models to cut that down, but its not too hard to imagine it becoming a model infested nightmare.  Sometimes you just have to take the good and the bad, but sometimes you&#8217;re able to trust people and just go with what is easier.</p>
<p>Why trust? With Python and it overall dynamic nature, it was easy to see that such a tool put in the wrong hands could be a disaster.  Anyone who has worked with JavaScript will know this pain.  Python is just a fancy way to annihilate your foot, so the concept of allowing dynamic models only made me shiver like a prostitute on Christmas.  Sorry, that wasn&#8217;t appropriate.  I meant a prostitute on a non religious holiday like Thanksgiving or the Chinese New Year. (Sorry non Christian readers)</p>
<p>On the other hand, when in a small group where you have less time and more to do, it could be used as a compromise as it doesn&#8217;t use the hated magic string dictionary thing approach, but still had a class like feel.  And on top of that, if you wish to create models later, it would be extremely easy to swap the @model dynamic with whatever class type you need.  So in that way, I can almost stop my non stop convulsing that is a natural reaction to doing something I deem bad.</p>
<p>Answer is:  I don&#8217;t f&#8211;king know right now, but I&#8217;m going to fly with it and see how I like it.</p>
<p>Side note: One drawback of the dynamic route is the lack of intellisense.  That could be a deal killer for some.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/pontification/asp-net-mvc-2c-4-dynamic-model-and-should-you-use-it/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ByATool.com gets a shiny new tool!</title>
		<link>http://byatool.com/writing/byatool-com-gets-a-shiny-new-tool/</link>
		<comments>http://byatool.com/writing/byatool-com-gets-a-shiny-new-tool/#comments</comments>
		<pubDate>Wed, 31 Mar 2010 14:03:01 +0000</pubDate>
		<dc:creator>Andre</dc:creator>
				<category><![CDATA[Website News]]></category>
		<category><![CDATA[Writing]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1287</guid>
		<description><![CDATA[A while back, we put up an offer to write for our blog.Â  Only one has risen to the top as someone having both the technical know-how and the razor sharp wit required to write on a site such as this. ByATool.com Readers&#8230; Amy. Amy&#8230; ByATool.com Readers. Amy is a magnificent geek and almost 10 [...]]]></description>
			<content:encoded><![CDATA[<p>A while back, we put up an offer to write for our blog.Â  Only one has risen to the top as someone having both the technical know-how and the razor sharp wit required to write on a site such as this.</p>
<p>ByATool.com Readers&#8230; Amy.</p>
<p>Amy&#8230; ByATool.com Readers.</p>
<p>Amy is a magnificent geek and almost 10 year veteran of server administration  and software development. She has worked at IBM, Concurrent Technologies  Corporation, and University of Pittsburgh Medical Center.  Currently,  she is doing custom SharePoint development connected with Team  Foundation Server and the ASP.NET MVC framework development using the Entity  Framework, C#, and jQuery.  She is currently living in Pittsburgh and  not happy at all about commuting into a city with 3 rivers because of  the many bridges and no serious commuter subway systems&#8230; Who plans  this stuff?</p>
<p>Welcome Amy!</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/writing/byatool-com-gets-a-shiny-new-tool/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Data Annotations, MVC, and Why You Might Like Them</title>
		<link>http://byatool.com/lessons/data-annotations-mvc-and-why-you-might-like-them/</link>
		<comments>http://byatool.com/lessons/data-annotations-mvc-and-why-you-might-like-them/#comments</comments>
		<pubDate>Wed, 16 Dec 2009 18:01:40 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Data Annotations]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1155</guid>
		<description><![CDATA[So if you were like me before I knew what Data Annotations were, you most likely would be thinking, &#8220;What are Data Annotations?&#8221;. Well I&#8217;m glad I can read your mind and therefore I am glad you asked. Now the fun part about this post is that I might have to admit I was wrong. [...]]]></description>
			<content:encoded><![CDATA[<p>So if you were like me before I knew what Data Annotations were, you most likely would be thinking, &#8220;What are Data Annotations?&#8221;.  Well I&#8217;m glad I can read your mind and therefore I am glad you asked.</p>
<p>Now the fun part about this post is that I might have to admit I was wrong.  Why would that be?  Well in <a href="http://byatool.com/pontification/asp-net-mvc-quick-overview-of-controller-structure/">this post</a> I suggested that validation rules would be set in the controller.  Turns out, there is possibly a better place, on the model itself.  How can this be done???  Well that&#8217;s what you&#8217;re about to find out.</p>
<p>Say you have a user create model:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> AddUserModel
  {
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> UserName { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> Password { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> RepeatPassword { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }</pre>
<p>Now you could have a method on the controller like:</p>
<pre>  <span style="color: #0000ff;">publi</span>c <span style="color: #008080;">ActionResul</span>t AddUser(<span style="color: #008080;">AddUserMode</span>l model)
  {
    <span style="color: #0000ff;">if</span>(IsValid(model))
    {
      ...
    }
  }</pre>
<p>Where you have to create the IsValid method for every model on the controller that you need to validate (And possibly on other controllers if you are sharing models between them&#8230;) Or you can have this:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #008080;">ActionResult</span> AddUser(<span style="color: #008080;">AddUserModel</span> model)
  {
    <span style="color: #0000ff;">if</span>(<span style="color: #008080;">ModelState</span>.IsValid)
    {
      ...
    }
  }</pre>
<p>And that is already built in so no validation method needed.  But how is that possible?  Attributes on the model or namely the ValidationAttribute class.</p>
<p>First off you have to include the System.ComponentModel dll in the project.  Simple enough.  Please say you know how to do that or do me a favor and remind yourself to blink. OK done?  Good.</p>
<p>Now you can use some of the built in attributes which is good.  Things like required are nice:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">AddUserModel</span>
  {
    [<span style="color: #008080;">Required</span>]
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> <span style="color: #008080;">UserName</span> { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    ...
  }</pre>
<p>There you go.  Now if the UserName is null or empty, the ModelState will no longer be valid and will fail this check:</p>
<pre>  <span style="color: #008080;">ModelState</span>.IsValid</pre>
<p>Now you might wonder what the error message will be for that?  Honest answer:  I have no f&#8211;king clue.  That&#8217;s why you can actually set it.  Those guys at Microsoft thought of everything.</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">AddUserModel</span>
  {
    [<span style="color: #008080;">Required</span>(ErrorMessage = <span style="color: #800000;">"ENTER A USERNAME IDIOT!"</span>]
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> UserName { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    ...
  }</pre>
<blockquote><p>The guys in the legal department have told me I have to note that your error message should change depending on your use and you shouldn&#8217;t use the one above.  Whatever.</p></blockquote>
<p>Now you might want to actually pass the errors back, and why wouldn&#8217;t you?  You&#8217;re a fine, upstanding, and thoughtful person and I lie like a crook.  The errors, if there are any, are in here:</p>
<pre>  ViewData.ModelState.Values</pre>
<p>And you can use two loops to get to all of them, but I think the parent loop will only run once.</p>
<pre>  <span style="color: #0000ff;">foreach</span> (<span style="color: #008080;">ModelState</span> state <span style="color: #0000ff;">in</span> ViewData.ModelState.Values)
  {
    <span style="color: #0000ff;">foreach</span> (<span style="color: #008080;">ModelErro</span>r error <span style="color: #0000ff;">in</span> state.Errors)
    {
      messageList.Add(error.ErrorMessage);
    }
  }</pre>
<p>Pretty nice huh?  Maybe if you&#8217;re an idiot who just learned about this.  For cool people like me, it&#8217;s old news.</p>
<p>What&#8217;s the point this?  If &#8220;this&#8221; is data annotations:  Well it helps move some of the validation off the controller if you are looking for a more &#8220;Fat model, skinny controller&#8221; design which I&#8217;m told is a good idea.  This also gets rid of all the validation methods and saves time because of it.</p>
<p>If &#8220;this&#8221; is your life?  I have no idea.  But if you&#8217;re to the point that you&#8217;re asking me about the meaning of your life, you are in some serious trouble.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/data-annotations-mvc-and-why-you-might-like-them/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Random Add-On &#8211; Automapper</title>
		<link>http://byatool.com/add-on/random-add-on-automapper/</link>
		<comments>http://byatool.com/add-on/random-add-on-automapper/#comments</comments>
		<pubDate>Tue, 01 Dec 2009 16:23:16 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Add On]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Tools]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1071</guid>
		<description><![CDATA[So if you&#8217;ve bothered reading my posts in the past, and don&#8217;t worry cause I haven&#8217;t, you might have seen me express my rule about not wanting to use third party stuff. Well things change. Actually they don&#8217;t, as I&#8217;m not bending the rule because I&#8217;m becoming a better person, just more lazy. This is [...]]]></description>
			<content:encoded><![CDATA[<p>So if you&#8217;ve bothered reading my posts in the past, and don&#8217;t worry cause I haven&#8217;t, you might have seen me express my rule about not wanting to use third party stuff. Well things change. Actually they don&#8217;t, as I&#8217;m not bending the rule because I&#8217;m becoming a better person, just more lazy. This is where <span style="font-size:20px;font-weight:bold;"><a href="http://automapper.codeplex.com/">Automapper</a></span> comes in.</p>
<p><span style="font-size:20px;font-weight:bold;"><a href="http://automapper.codeplex.com/">Automapper</a></span> is pretty much what it sounds like, it maps class properties automatically. Maybe a more clevererest name would have been ClassPropertyAutoMapper, but the guys who made it shouldn&#8217;t be persecuted for lacking creativity.</p>
<p>How simple is <span style="font-size:20px;font-weight:bold;"><a href="http://automapper.codeplex.com/">Automapper</a></span>? Simple enough that even you can use it. Now that&#8217;s simple! Say you have two classes, a entity class and a model, and you want to map the model to the entity in the constructor. You could do:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">SomeModel</span>
  {
    <span style="color: #0000ff;">public</span> SomeModel(<span style="color: #008080;">SomeEntity</span> someEntity)
   {
     SomeProperty = someEntity.SomeProperty;
   }
  }</pre>
<p>But where&#8217;s the lazyiness? I expect so much less from you. But it&#8217;s ok, salvation is right here:</p>
<pre>  <span style="color: #0000ff;">public</span> SomeModel(<span style="color: #008080;">SomeEntity</span> someEntity)
  {
    <span style="color: #008080;">Mapper</span>.CreateMap();
    <span style="color: #008080;">Mapper</span>.Map(someEntity, <span style="color: #0000ff;">this</span>);
  }</pre>
<p>But&#8230; but what if there are properties on SomeModel that don&#8217;t directly map by name? Well, there&#8217;s an ap&#8230;i for that. (Not sure that even makes sense but it was clever.)</p>
<pre>  <span style="color: #0000ff;">public</span> SomeModel(<span style="color: #008080;">SomeEntity</span> someEntity)
  {
    <span style="color: #008080;">Mapper</span>.CreateMap&lt;<span style="color: #008080;">FiftyPostUser</span>, <span style="color: #008080;">UserInfoViewModel</span>&gt;()
     .ForMember(test =&gt; test.Status, tester =&gt; tester.MapFrom(item =&gt; item.Status.ToString()));
    <span style="color: #008080;">Mapper</span>.Map(someEntity, <span style="color: #0000ff;">this</span>);
  }</pre>
<p>So I know you&#8217;re thinking that there&#8217;s a catch, well there is. You have to actually get the <a href="http://automapper.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=32994">dll and reference in your project</a>. I know! Work is hard. Why can&#8217;t these guys just come to your place of work/home/mom&#8217;s basement and do it for you? What kind of world is it when you can&#8217;t get all that for free? Personally, I hate it.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/add-on/random-add-on-automapper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>State List in Dictionary Form</title>
		<link>http://byatool.com/pointless/state-list-in-dictionary-form/</link>
		<comments>http://byatool.com/pointless/state-list-in-dictionary-form/#comments</comments>
		<pubDate>Tue, 01 Dec 2009 14:55:34 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Pointless]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Stupid]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1077</guid>
		<description><![CDATA[Tired of having to look this up from time to time, so I&#8217;m putting this here for my own use. If you get something out of it, good for you. In the end, I really don&#8217;t care. public Dictionary GetAllStates() { if(_stateList == null) { _stateList = new Dictionary(); _stateList.Add("Alabama","AL"); _stateList.Add("Alaska","AK"); _stateList.Add("American Samoa","AS"); _stateList.Add("Arizona","AZ"); _stateList.Add("Arkanas","AR"); [...]]]></description>
			<content:encoded><![CDATA[<p>Tired of having to look this up from time to time, so I&#8217;m putting this here for my own use.  If you get something out of it, good for you.  In the end, I really don&#8217;t care.</p>
<pre>
    public Dictionary<string, string> GetAllStates()
    {
      if(_stateList == null)
      {
        _stateList = new Dictionary<string, string>();

        _stateList.Add("Alabama","AL");
        _stateList.Add("Alaska","AK");
        _stateList.Add("American Samoa","AS");
        _stateList.Add("Arizona","AZ");
        _stateList.Add("Arkanas","AR");
        _stateList.Add("California","CA");
        _stateList.Add("Colorado","CO");
        _stateList.Add("Connecticut","CT");
        _stateList.Add("Delaware","DE");
        _stateList.Add("District Of Colombia","DC");
        _stateList.Add("Federated States Of Micronesia","FM");
        _stateList.Add("Florida","FL");
        _stateList.Add("Georgia","GA");
        _stateList.Add("Guam","GU");
        _stateList.Add("Hawaii","HI");
        _stateList.Add("Idaho","ID");
        _stateList.Add("Illinois","IL");
        _stateList.Add("Indiana","IN");
        _stateList.Add("Iowa","IA");
        _stateList.Add("Kansas","KS");
        _stateList.Add("Kentucky","KY");
        _stateList.Add("Lousiana","LA");
        _stateList.Add("Maine","ME");
        _stateList.Add("Marshall Islands","MH");
        _stateList.Add("Maryland","MD");
        _stateList.Add("Massachusetts","MA");
        _stateList.Add("Michigan","MI");
        _stateList.Add("Minnesota","MN");
        _stateList.Add("Mississippi","MS");
        _stateList.Add("Missouri","MO");
        _stateList.Add("Montana","MT");
        _stateList.Add("Nebraska","NE");
        _stateList.Add("Nevada","NV");
        _stateList.Add("New Hampshire","NH");
        _stateList.Add("New Jersey","NJ");
        _stateList.Add("New Mexico","NM");
        _stateList.Add("New York","NY");
        _stateList.Add("North Carolina","NC");
        _stateList.Add("North Dakota","ND");
        _stateList.Add("Northern Mariana Islands","MP");
        _stateList.Add("Ohio","OH");
        _stateList.Add("Oklahoma","OK");
        _stateList.Add("Oregon","OR");
        _stateList.Add("Palau","PW");
        _stateList.Add("Pennsylvania","PA");
        _stateList.Add("Puerto Rico","PR");
        _stateList.Add("Rhode Island","RI");
        _stateList.Add("South Carolina","SC");
        _stateList.Add("South  Dakota","SD");
        _stateList.Add("Tennessee","TN");
        _stateList.Add("Texas","TX");
        _stateList.Add("Utah","UT");
        _stateList.Add("Varmont","VT");
        _stateList.Add("Virgin Islands","VI");
        _stateList.Add("Virginia","VA");
        _stateList.Add("Washington","WA");
        _stateList.Add("West Virginia","WV");
        _stateList.Add("Wisconsin","WI");
        _stateList.Add("Wyoming","WY");
      }

      return _stateList;
    }
</pre>
<p>So there.  Hope you&#8217;re happy.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/pointless/state-list-in-dictionary-form/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Framework: Possible Lazy Loading Solution</title>
		<link>http://byatool.com/pontification/entity-framework-possible-lazy-loading-solution/</link>
		<comments>http://byatool.com/pontification/entity-framework-possible-lazy-loading-solution/#comments</comments>
		<pubDate>Fri, 19 Jun 2009 14:53:02 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Pontification]]></category>
		<category><![CDATA[Add new tag]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=713</guid>
		<description><![CDATA[So been a while since I posted last, and I&#8217;m sure everyone has been worried. Turns out that I&#8217;ve been banging my head against the wall named MVC. And man I have a slew of new posts back logged for when I have more time. However, due to the new project I&#8217;ve been working one, [...]]]></description>
			<content:encoded><![CDATA[<p>So been a while since I posted last, and I&#8217;m sure everyone has been worried. Turns out that I&#8217;ve been banging my head against the wall named MVC. And man I have a slew of new posts back logged for when I have more time. However, due to the new project I&#8217;ve been working one, I forced myself to tackle Lazy Loading in the Entity Framework. Turns out the solution isn&#8217;t that hard since it has everything needed to make it work.</p>
<p>One of the biggest waaaaahbumlance calls is the fact that Entity Framework doesn&#8217;t have lazy loading. This isn&#8217;t true. It does, you just have to do a little work, which is to be expected from a FRAMEWORK. Now I have to admit, I wish there were a slightly less odd way of doing this, but eh it&#8217;s not too bad.</p>
<p>Say you have a class named Topic and it has a reference to a Forum class named ParentForum. Now this is just a property on the actual class created by the E-Work to represent a many to one foriegn key relationship between the Topic table and the Forum table. Now the problem comes in when you try to use something from that property like:</p>
<pre>    <span style="color: #008080;">Int32</span> someInt = topic.ParentForum.ForumId;</pre>
<p>If you didn&#8217;t use the Include method when you got that topic:</p>
<pre>    context.Include(<span style="color: #800000;">"ParentForum"</span>).Select(topic =&gt; topic);</pre>
<p>You are screwed because the ParentForum property will return a null. So this forces you to use Include every time you want to get a Topic and access it&#8217;s ParentForum property. Sucks.</p>
<p>So next thought is to find out how to lazy load and then plunk it into that generated property. Eh I don&#8217;t know about you, but that sounds like a bad idea to mess around with a generated file. You have no idea when the E-Work will just trash the file and rebuild.</p>
<p>Next thought was to create a proxy property to check the real one and then load if it&#8217;s not already loaded. Something like:</p>
<pre>    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Forum</span> ParentForumLazyLoaded
    {
        <span style="color: #0000ff;">get</span>
        {
           <span style="color: #008000;">//check and return</span>
        }
    }</pre>
<p>Ok so that&#8217;s not horrible except two things: The name looks dumb and people can still get at the original ParentForum property.</p>
<p>So in comes my solution and it&#8217;s pretty simple. Rename the property name on the class to something ParentForumInner and make it private.</p>
<pre><img class="alignnone size-full wp-image-714" title="bat_lazyload1" src="http://byatool.com/wp-content/uploads/2009/06/bat_lazyload1.jpg" alt="bat_lazyload1" width="598" height="263" /></pre>
<p>Then you can create a much nicer outward facing property like:</p>
<pre>    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Forum</span> ParentForum
    {
      <span style="color: #0000ff;">get</span>
      {
          <span style="color: #0000ff;">if</span> (!ParentForumInnerReference.IsLoaded)
          {
              ParentForumInnerReference.Load();
          }

        <span style="color: #0000ff;">return</span> ParentForumInner;
    }
    <span style="color: #0000ff;">set</span>
    {
        ParentForumInner = <span style="color: #0000ff;">value</span>;
    }
}</pre>
<p>Now one of the issues with this is that although outside the class only the ParentForum property can be seen, within the class they both can be seen which can lead to issues like:</p>
<pre>    context.Topics.Where(topic =&gt; topic.ParentForum.ForumId == id);  <span style="color: #008000;">//boom</span></pre>
<p>Where you should be using:</p>
<pre>    context.Topics.Where(topic =&gt; topic.ParentForumInner.ForumId == id);  <span style="color: #008000;">//yay</span></pre>
<p>E-Work doesn&#8217;t know how to handle that situation when evaluating that expression and the kicker is that it does just fine compile time. You won&#8217;t know this is bad until runtime.</p>
<p>Other issue is that you have to do a little more work then just some setting on the property which is what most people wish for. I guess that may be true, but again this is a framework. It gives you all the tools you need to makes things work, you just have to do some coding.</p>
<p>The plus side to this is that with minimal coding, you can completely get rid of Include which to me is huge.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/pontification/entity-framework-possible-lazy-loading-solution/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>By Reference in C# and How to Get Schooled By It</title>
		<link>http://byatool.com/general-coding/by-reference-in-c-and-how-to-get-schooled-by-it/</link>
		<comments>http://byatool.com/general-coding/by-reference-in-c-and-how-to-get-schooled-by-it/#comments</comments>
		<pubDate>Mon, 01 Dec 2008 20:10:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Referece]]></category>
		<category><![CDATA[Stupid]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=114</guid>
		<description><![CDATA[WARNING: If you understand The concept of By Reference, skip the first part of this post: So you have an object, huh? Ok well what does that mean? Basically there is a stack and a heap. When you declare an object, space is made on the stack, basically it&#8217;s a placeholder saying that there will [...]]]></description>
			<content:encoded><![CDATA[<p><span style="color: #800000;">WARNING: If you understand The concept of By Reference, skip the first part of this post:</span></p>
<p>So you have an object, huh? Ok well what does that mean? Basically there is a stack and a heap. When you declare an object, space is made on the stack, basically it&#8217;s a placeholder saying that there will be something to point.</p>
<pre>    <span style="color: #33cccc;">User</span> someUser;</pre>
<p>Now when you instatiate:</p>
<pre>    someUser = <span style="color: #0000ff;">new</span> <span style="color: #33cccc;">User</span>();</pre>
<p>That user Object is put on the heap and that placeholder (reference) on the stack? Well it&#8217;s given a pointer which SURPRISE points to the object on the heap. Now when you pass the object into the method, you aren&#8217;t really passing what&#8217;s on the heap. You are actually copying and passing the pointer. Inside the method, a new entry is thrown on the stack that points to the same object on the heap. This way if you change anything on the object in the method, the changes are reflected outside the method. (Say if you added items to a list in the method) Now this all changes if the object inside the method is reinitialized or repointed:</p>
<pre>    SomeMethod(<span style="color: #33cccc;">User</span> user)
    {
        user = <span style="color: #0000ff;">new</span> <span style="color: #33cccc;">User</span>();
        user.UserName = <span style="color: #800000;">"Sean"</span>;
    }</pre>
<p>Remember that user we passed in? It now has nothing to do with the one in the method now. There is now a new object on the heap and &#8220;user&#8221; in the method now points to it. Why did I tell you all of this?</p>
<p><span style="color: #800000;">END REFERENCE EXPLANATION:</span></p>
<p>Say you have this:</p>
<pre>    ...

    <span style="color: #33cccc;">UserList</span> userList = <span style="color: #0000ff;">new</span> <span style="color: #33cccc;">UserList</span>();
    <span style="color: #33cccc;">SomeList</span> list = <span style="color: #0000ff;">new</span> <span style="color: #33cccc;">SomeList</span>();</pre>
<pre>    FillListFromUserList(list, userList);

    ...

    <span style="color: #0000ff;">void</span> FillListFromUser(<span style="color: #33cccc;">SomeList</span> listToCopyTo, <span style="color: #33cccc;">UserList</span> userList)
    {
       <span style="color: #0000ff;">foreach</span>(<span style="color: #33cccc;">User</span> currentUser <span style="color: #0000ff;">in</span> userList)
       {
          listToCopyTo.Add(userList);
       }
    }</pre>
<p>Easy, and basically at this point list should have the same items as userList. Now say list needs what&#8217;s in userList but in order by UserID. Suppose you did it like this:</p>
<pre>    <span style="color: #0000ff;">void</span> FillListFromUser(<span style="color: #33cccc;">SomeList</span> listToCopyTo, <span style="color: #33cccc;">UserList</span> userList)
    {
       <span style="color: #0000ff;">foreach</span>(<span style="color: #33cccc;">User</span> currentUser in userList)
       {
          listToCopyTo.Add(userList);
       }

       <span style="color: #0000ff;">var</span> sorted = <span style="color: #0000ff;">from</span> user <span style="color: #0000ff;">in</span> userList
                    <span style="color: #0000ff;">orderby</span> user.UserID
                    <span style="color: #0000ff;">select</span> user;

       listToCopy = sorted.ToList();
    }</pre>
<p>Ok so a quick check to see if list now contains items will show it does. Now say you looked at this method and thought it was a little more than needed. You decide to do this:</p>
<pre>    <span style="color: #0000ff;">void</span> FillListFromUser(<span style="color: #33cccc;">SomeList</span> listToCopyTo, <span style="color: #33cccc;">UserList</span> userList)
    {
        listToCopyTo = userList.OrderBy(user =&gt; user.ID);
    }</pre>
<p>Now a quick check to see if list has something in it shows that it doesn&#8217;t. But wait, what the hell? The first one worked and the second is just short hand right? Eh well the problem is how objects are passed. By reference means that it doesn&#8217;t pass the original pointer from the stack but it copies it so that there are two references on the stack that point to the same object on the heap. What does this all mean? Well both</p>
<pre>    listToCopy = sorted.ToList();
 And
    listToCopyTo = userList.OrderBy(user =&gt; user.ID);</pre>
<p>Have now reset the pointer for the reference in the method (listToCopyTo) making it no longer have anything to do with the list outside of it (list). The reason why it gave a false positive on the first one was that I had added to the list within, and therefor to the object the list outside points to. So the changing of the pointer:</p>
<pre>    listToCopy = sorted.ToList();</pre>
<p>would no longer affect the list oustide. However, in the second example I never added to the object they both pointed to before I changed the pointer on the inner. Hense why the second example had nothing in the outer list. To make matters worse I would have noticed this before if the original userList hadn&#8217;t been sorted by ID already.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/by-reference-in-c-and-how-to-get-schooled-by-it/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C#, Var, and Objec-  Propert-  I have no idea what the term is</title>
		<link>http://byatool.com/pontification/c-var-and-objec-propert-i-have-no-idea-what-the-term-is/</link>
		<comments>http://byatool.com/pontification/c-var-and-objec-propert-i-have-no-idea-what-the-term-is/#comments</comments>
		<pubDate>Thu, 20 Nov 2008 15:31:26 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Pontification]]></category>
		<category><![CDATA[Anonymous Types]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Duck Typing]]></category>
		<category><![CDATA[Dynamic]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=98</guid>
		<description><![CDATA[So I caugh this the other day and I&#8217;m not really sure it&#8217;s useful but it got me thinking&#8230; Say you have a string and you want to create what ReSharper calls a &#8220;implicitly typed local variable declaration&#8221;, or as most people know it as &#8220;var&#8221;, and intialize it with a created value: String someThing [...]]]></description>
			<content:encoded><![CDATA[<p>So I caugh this the other day and I&#8217;m not really sure it&#8217;s useful but it got me thinking&#8230;</p>
<p>Say you have a string and you want to create what ReSharper calls a &#8220;implicitly typed local variable declaration&#8221;, or as most people know it as &#8220;var&#8221;, and intialize it with a created value:</p>
<pre>  <span style="color: #33cccc;">String</span> someThing = <span style="color: #800000;">"hi"</span>;
  <span style="color: #0000ff;">var</span> onTheFly = <span style="color: #0000ff;">new</span> { someThing };</pre>
<p>And now you can do this:</p>
<pre>  <span style="color: #33cccc;">String</span> somethingElse = ontTheFly.something;</pre>
<p>What it basically did was not only take the value of the string, but the name too and made a property on the var. In fact you may have seen this already with Linq:</p>
<pre>    <span style="color: #0000ff;">var</span> hi = <span style="color: #0000ff;">from</span> item <span style="color: #0000ff;">in</span> test
               <span style="color: #0000ff;">select</span> <span style="color: #0000ff;">new</span> {item.UserRole};

    <span style="color: #33cccc;">UserRole</span> someRole = hi.ToList()[0].UserRole;</pre>
<p>So what does this all mean? Right now, I&#8217;m not really sure. I suppose if you have a method that you want to combine a bunch of value/objects into one var so you don&#8217;t have to keep refering to 8 different objects that might work:</p>
<pre>    <span style="color: #008000;">//Get the user
</span>    <span style="color: #33cccc;">User</span> user = <span style="color: #0000ff;">new</span> <span style="color: #33cccc;">User</span> (1);
    <span style="color: #008000;">//Get some icecream... couldn't think of any better fake class name</span>
    <span style="color: #33cccc;">IceCream</span> iceCream = <span style="color: #0000ff;">new</span> <span style="color: #33cccc;">IceCream</span>(1);

    <span style="color: #0000ff;">var</span> stuff = <span style="color: #0000ff;">new</span> { user.UserName, user.UserRoles, user.UserLastName,
                             iceCream.Flavor, iceCream.Texture };

    <span style="color: #008000;">//IMAGINARY CODE GOES HERE</span>
    <span style="color: #008000;">//MORE IMAGINARY CODE</span>
    <span style="color: #008000;">//??</span>
    <span style="color: #008000;">//PROFIT</span>
    <span style="color: #0000ff;">if</span>(stuff.UserName.Equals(<span style="color: #800000;">"Sean"</span>, StringComparison.OrdinalIgnoreCase)
       &amp;&amp; stuff.Flavor == IceCreamFlavor.Chocolate)
    {
       <span style="color: #008000;">//BLAH BLAH BLAH
</span>    }</pre>
<p>As you can see, it could be a way to group together a bunch of things in a method, but I&#8217;m not sure that is really useful.</p>
<p><span style="color: #800000;">*WARNING THIS IS NOT TO BE TAKEN AS FACT, JUST MUSINGS OF AN IDIOT*</span></p>
<p>Now for the theory&#8230; As is, this isn&#8217;t useful but with 4.0 that might change with Duck Typing and dynamic types. Why? Well take a method like this:</p>
<pre>    CallMe(userName, userFirstName, userLastName, userAddress,
             thisIsStupid, makeItEnd, iNeedAnAdult... endMe);</pre>
<p>Now that&#8217;s a lot of parameters. Conventional wisdom says I should create a new class whose properties match the parameters I would be sending in and just send in that class:</p>
<pre>    parameterClass.UserName = userName;
    parameterClass.UserFirstName = firstName;
    .....
    CallMe(parameterClass);</pre>
<p>Now the only annoying thing is having to make the class to do this. What if dynamic types + duck typing takes that step away?</p>
<pre>    <span style="color: #0000ff;">var</span> parameter = <span style="color: #0000ff;">new</span> { userName, userFirstName, userLastName .... };
    CallMe(parameter);</pre>
<p>Then CallMe would take in a dynamic type and just look to see if it has the needed properties. Would be nice if this is possible but I haven&#8217;t used 4.0 yet to know, I&#8217;m only guessing from what I&#8217;ve read.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/pontification/c-var-and-objec-propert-i-have-no-idea-what-the-term-is/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH</title>
		<link>http://byatool.com/general-coding/linq-extension-methods-versus-linq-query-language-deathmatch/</link>
		<comments>http://byatool.com/general-coding/linq-extension-methods-versus-linq-query-language-deathmatch/#comments</comments>
		<pubDate>Thu, 13 Nov 2008 03:09:38 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Func]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=86</guid>
		<description><![CDATA[Today I was writing out an example of why the extension methods are for the most part better to use than the querying language. Go figure I would find a case where that&#8217;s not entirely true. Say you are using these three funcs: Func&#60;User, String&#62; userName = user =&#62; user.UserName; Func&#60;User, Boolean&#62; userIDOverTen = user [...]]]></description>
			<content:encoded><![CDATA[<p>Today I was writing out an example of why the extension methods are for the most part better to use than the querying language.  Go figure I would find a case where that&#8217;s not entirely true.  Say you are using these three funcs:</p>
<pre><span style="color: #33cccc;">    Func</span>&lt;<span style="color: #33cccc;">User</span>, <span style="color: #33cccc;">String</span>&gt; userName = user =&gt; user.UserName;
<span style="color: #33cccc;">    <span>Func</span></span>&lt;<span style="color: #33cccc;">User</span>, <span style="color: #33cccc;">Boolean</span>&gt; userIDOverTen = user =&gt; user.UserID &lt; 10;
<span style="color: #33cccc;">    <span>Func</span></span>&lt;<span style="color: #33cccc;">User</span>, <span style="color: #33cccc;">Boolean</span>&gt; userIDUnderTen = user =&gt; user.UserID &gt; 10;</pre>
<p>As you can see the first one replaces the lamdba expression to get the user name, the second replaces a lamdba expression used to check if the ID is lower than 10, and let&#8217;s face it, the third should be pretty easy to understand now.</p>
<p>NOTE:  This is a  silly example but it works.</p>
<pre><span style="color: #33cccc;">    </span><span style="color: #0000ff;">var</span> userList =
<span style="color: #33cccc;">      </span><span style="color: #0000ff;">from</span> user <span style="color: #0000ff;">in</span> userList
<span style="color: #33cccc;">      </span><span style="color: #0000ff;">where</span> userIDOverTen(user)
<span style="color: #33cccc;">      </span><span style="color: #0000ff;">select</span> userName;
Versus

<span style="color: #33cccc;">    </span><span style="color: #0000ff;">var</span> otherList =
<span style="color: #33cccc;">      </span>userList
<span style="color: #33cccc;">      </span>.Where(IDIsBelowNumber)
<span style="color: #33cccc;">      </span>.Select(userName)</pre>
<p>In this example, the second is a little less verbose since the extension method can make full use of the Func, but he Linq expression can&#8217;t since it is look just for a Boolean rather than a Func that returns boolean.   However, this is where it might be better to use the expression language.  Say you already had a method that takes in more than just a user:</p>
<pre><span style="color: #33cccc;">    </span><span style="color: #0000ff;">private</span> <span style="color: #33cccc;">Boolean</span> IDIsBelowNumber(<span style="color: #33cccc;">User</span> user, <span style="color: #33cccc;">Int32</span> someNumber, <span style="color: #33cccc;">Boolean</span> doSomething)
<span style="color: #33cccc;">    </span>{
<span style="color: #33cccc;">      </span><span style="color: #0000ff;">return</span> user.UserID &lt; someNumber;
    }</pre>
<p>Note:  doSomething is just there because of the where extension method being ok with a method that takes in a user and integer and returns boolean.  Kind of annoying for this example.</p>
<p>Now if you look at the Linq query:</p>
<pre><span style="color: #33cccc;">    </span><span style="color: #0000ff;">var</span> completeList =
<span style="color: #33cccc;">      </span><span style="color: #0000ff;">from</span> user <span style="color: #0000ff;">in</span> userList
<span style="color: #33cccc;">      </span><span style="color: #0000ff;">where</span> userIDOverTen(user, 10)
<span style="color: #33cccc;">      </span><span style="color: #0000ff;">select</span> userName;</pre>
<p>You&#8217;re good for it.  Now the Extension Method:</p>
<pre><span style="color: #33cccc;">    </span><span style="color: #0000ff;">var</span> otherList =
<span style="color: #33cccc;">      </span>userList
<span style="color: #33cccc;">      </span>.Where(IDIsBelowNumber????)
<span style="color: #33cccc;">      </span>.Select(userName)</pre>
<p>Without a lambda expression, I really can&#8217;t call that method.  So now what I have to do is create a method that creates a Func based off the original method call.</p>
<pre><span style="color: #33cccc;">    </span><span style="color: #0000ff;">private</span> <span style="color: #33cccc;">Func</span>&lt;<span style="color: #33cccc;">User</span>, <span style="color: #33cccc;">Boolean</span>&gt; IDIsBelowNumberFunc(<span style="color: #33cccc;">Int32</span> number)
<span style="color: #33cccc;">    </span>{
<span style="color: #33cccc;">      </span><span style="color: #0000ff;">return</span> user =&gt; IDIsBelowNumber(user, number, <span style="color: #0000ff;">true</span>);
<span style="color: #33cccc;">    </span>}</pre>
<p>And then plug it in:</p>
<pre><span style="color: #33cccc;">    </span><span style="color: #0000ff;">var</span> otherList =
<span style="color: #33cccc;">      </span>userList
<span style="color: #33cccc;">      </span>.Where(IDIsBelowNumberFunc(10))
<span style="color: #33cccc;">      </span>.Select(userName)</pre>
<p>What does this all mean?  You just lost 5 minutes of your life.  I hope it was worth it.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/linq-extension-methods-versus-linq-query-language-deathmatch/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Static Abstract &#8230; should I bother?</title>
		<link>http://byatool.com/pontification/static-abstract-should-i-bother/</link>
		<comments>http://byatool.com/pontification/static-abstract-should-i-bother/#comments</comments>
		<pubDate>Fri, 17 Oct 2008 20:00:58 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Pontification]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Stupid]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=68</guid>
		<description><![CDATA[So it came up recently that someone was bummed that you can&#8217;t create a static abstract method. Now conceptually, this is blocked by C# but I came up with this &#8220;work around&#8221;&#8230; And I have no idea if I would ever use it. This was more of a &#8220;Do it because I can&#8221; rather than [...]]]></description>
			<content:encoded><![CDATA[<p>So it came up recently that someone was bummed that you can&#8217;t create a static abstract method.  Now conceptually, this is blocked by C# but I came up with this &#8220;work around&#8221;&#8230; And I have no idea if I would ever use it.  This was more of a &#8220;Do it because I can&#8221; rather than &#8220;Do it because I should.&#8221;</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">abstract</span> <span style="color: #0000ff;">class</span> <span style="color: #33cccc;">Parent</span>
  {
    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">abstract</span> <span style="color: #33cccc;">String</span> ReturnAValue(<span style="color: #33cccc;">String</span> returnThis);

    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #33cccc;">String</span> ReturnAValue(<span style="color: #33cccc;">String</span> returnThis) <span style="color: #0000ff;">where</span> K : <span style="color: #33cccc;">Parent</span>
    {
        K classToCreate;

        classToCreate = Activator.CreateInstance();
        <span style="color: #0000ff;">return</span> classToCreate.ReturnAValue(returnThis);
    }
  }</pre>
<p>So what I did here was create a parent class that causes any child to override the ReturnAValue method so that I could create a static method on the parent that basically would just instantiate the child class and call the overridden method. How&#8217;s that for a run on sentence?</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #33cccc;">ChildA</span> : <span style="color: #33cccc;">Parent</span>
  {
    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">override</span><span style="color: #33cccc;"> String</span> ReturnAValue(<span style="color: #33cccc;">String</span> returnThis)
    {
        <span style="color: #0000ff;">return</span> <span style="color: #ff0000;">"ChildA "</span> + returnThis;
    }
  }</pre>
<p>And this in full use:</p>
<pre>  <span style="color: #33cccc;">String</span> testReturn;
  testReturn = Parent.ReturnAValue(<span style="color: #ff0000;">"returned"</span>);</pre>
<p>Can you guess what that returns? If you can, you&#8217;re special. You might wonder why I have to use generics in this. Well I mean you could do this:</p>
<pre>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #33cccc;">String</span> ReturnAValue(<span style="color: #33cccc;">Parent</span> returnThis)
    {
        <span style="color: #0000ff;">return</span> returnThis.ReturnAValue(returnThis);
    }
</pre>
<p>But that assumes you have to instantiate the child and pass it in.</p>
<p>Now the main problem with this, beyond the fact that you&#8217;ll probably never use this, is Activator.CreateInstance() need a default public constructor to use. Kind of a catch.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/pontification/static-abstract-should-i-bother/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Switch Remover: Convert Switch Statements to Dictionaries</title>
		<link>http://byatool.com/general-coding/the-switch-remover/</link>
		<comments>http://byatool.com/general-coding/the-switch-remover/#comments</comments>
		<pubDate>Fri, 17 Oct 2008 13:30:10 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[.Net]]></category>
		<category><![CDATA[Action]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Lambda]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=65</guid>
		<description><![CDATA[Folks, what if I told you that Switch is a thing of the past? What if I told you I had a way to reduce code in certain areas so that you don&#8217;t have that messy Switch logic? What would you pay for that? Would you pay $19.95? Not convinced? Well take this: switch(someDropDownList.SelectedValue) { [...]]]></description>
			<content:encoded><![CDATA[<p>Folks, what if I told you that Switch is a thing of the past? What if I told you I had a way to reduce code in certain areas so that you don&#8217;t have that messy Switch logic? What would you pay for that? Would you pay $19.95? Not convinced? Well take this:</p>
<pre>  <span style="color: #0000ff;">switch</span>(someDropDownList.SelectedValue)
  {
     <span style="color: #0000ff;">case</span> <span style="color: #ff0000;">"hi"</span>:
        CallThisMethod();
        CallThatMethod();
        CallAnotherMethod();
        <span style="color: #0000ff;">break</span>;
     <span style="color: #0000ff;">case</span> <span style="color: #ff0000;">"there"</span>:
        CallThisMethod();
        CallThatMethod();
        CallAnotherMethod();
        CallSomethingElse();
        <span style="color: #0000ff;">break</span>;
  }</pre>
<p>And I&#8217;ll give you this:</p>
<pre>  doSomething[someDropDownList.SelectedValue]();</pre>
<p>I bet you&#8217;re ready to pay $19.95, but wait there&#8217;s more. I&#8217;ll actually throw in how I did such an amazing thing.</p>
<pre>  <span style="color: #33cccc;">Dictionary</span>&lt;<span style="color: #33cccc;">String</span>, <span style="color: #33cccc;">Action</span>&gt; switchRemover = <span style="color: #0000ff;">new</span> <span style="color: #33cccc;">Dictionary</span>&lt;<span style="color: #33cccc;">String</span>, <span style="color: #33cccc;">Action</span>&gt;();
  switchRemover.Add(<span style="color: #ff0000;">"hi"</span>, () =&gt; RunHiMethod();
  switchRemover.Add(<span style="color: #ff0000;">"there"</span>, () =&gt; RunThereMethod();</pre>
<p>Why that&#8217;s amazing! But wait, I must be pulling something. What are these RunHiMethod and RunThereMethod methods? I must be pulling a fast one. Well, all they are is what the switch was doing before all wrapped up into one method. Don&#8217;t get it?</p>
<pre>  <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">void</span> RunHiMethod()
  {
      CallThisMethod();
      CallThatMethod();
      CallAnotherMethod();
  }</pre>
<p>But&#8230; but what if I had to pass something in? What would I do then??? Boy you got me there, I could tell you but I&#8217;d have to charge you more. Wait&#8230; I&#8217;ll even throw that in for free. That&#8217;s right. Remember that old mess we had?</p>
<pre>  <span style="color: #0000ff;">switch</span>(someDropDownList.SelectedValue)
  {
     <span style="color: #0000ff;">case</span> <span style="color: #ff0000;">"hi"</span>:
        CallThisMethod(someUser);
        CallThatMethod();
        CallAnotherMethod();
        <span style="color: #0000ff;">break</span>;
     <span style="color: #0000ff;">case</span> <span style="color: #ff0000;">"there"</span>:
        CallThisMethod(someUser);
        CallThatMethod();
        CallAnotherMethod();
        CallSomethingElse();
        <span style="color: #0000ff;">break</span>;
}</pre>
<p>Well shoot,we could do something like this:</p>
<pre>  <span style="color: #33cccc;">Dictionary</span>&lt;<span style="color: #33cccc;">String</span>, <span style="color: #33cccc;">Action</span>&lt;<span style="color: #33cccc;">User</span>&gt;&gt; switchRemover = <span style="color: #0000ff;">new</span> <span style="color: #33cccc;">Dictionary</span>&lt;<span style="color: #33cccc;">String</span>, <span style="color: #33cccc;">Action</span>&gt;();
  switchRemover.Add(<span style="color: #ff0000;">"hi"</span>, currentUser =&gt; RunHiMethod(currentUser);
  switchRemover.Add(<span style="color: #ff0000;">"there"</span>, currentUser =&gt; RunThereMethod(currentUser );</pre>
<p>And then:</p>
<pre>  doSomething[someDropDownList.SelectedValue](currentUser);</pre>
<p>That&#8217;s amazing! You ready with your credit card? I knew you would be.</p>
<p>The Switch Remover does not come with a warranty.<br />
The Switch Remover can not be used in all circumstances.<br />
The Switch Remover assumes no fault for any physical conditions caused by the sudden surge of awesomeness you might feel.</p>
<p>SO BUY IT NOW!</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/the-switch-remover/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Uhg It Won&#8217;t End</title>
		<link>http://byatool.com/general-coding/uhg-it-wont-end/</link>
		<comments>http://byatool.com/general-coding/uhg-it-wont-end/#comments</comments>
		<pubDate>Fri, 10 Oct 2008 17:22:58 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Func]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=60</guid>
		<description><![CDATA[Still on the readability thing, but there was a second argument in the post that inspired now what is three posts of my own here. The question was should you use Linq based on people saying it&#8217;s more readable, therefore just making it syntax sugar. foreach(Item current in itemList) { itemNameList.Add(current.Name); } Versus var itemNameList [...]]]></description>
			<content:encoded><![CDATA[<p>Still on the readability thing, but there was a second argument in the <a title="HERHEHREHRE" href="http://keithelder.net/blog/archive/2008/10/08/Balancing-Readability-and-New-Syntax-Sugar-in-C-3.0.aspx">post</a> that inspired now what is three posts of my own here. The question was should you use Linq based on people saying it&#8217;s more readable, therefore just making it syntax sugar.</p>
<pre>  <span style="color: #0000ff;">foreach</span>(<span style="color: #33cccc;">Item</span> current <span style="color: #0000ff;">in</span> itemList)
  {
     itemNameList.Add(current.Name);
  }</pre>
<p>Versus</p>
<pre> <span style="color: #0000ff;">var</span> itemNameList = <span style="color: #0000ff;">from</span> item <span style="color: #0000ff;">in</span> itemList
                    <span style="color: #0000ff;">select</span> item.Name;</pre>
<p>Or</p>
<pre>  <span style="color: #33cccc;">Func</span>&lt;<span style="color: #33cccc;">Item</span>, <span style="color: #33cccc;">String</span>&gt; itemName = current =&gt; current.Name;
  itemNameList.Select(itemName);</pre>
<p>So at this point it&#8217;s really a matter of preference. Problem is, you have to look closer to why the third is so much more than syntax yummies.</p>
<p>Say you want a method that takes in a UserList and you want to select all the users that have a property (Could be name, address, whatever) that matches a string. Well you could do this:</p>
<pre> <span style="color: #0000ff;">public</span> <span style="color: #33cccc;">IList</span>&lt;<span style="color: #33cccc;">User</span>&gt; AllUsersThatMatch(<span style="color: #33cccc;">IList</span>&lt;<span style="color: #33cccc;">User</span>&gt; userList, <span style="color: #33cccc;">NeededProperty </span>property, <span style="color: #33cccc;">String </span>value)
 {
    <span style="color: #33cccc;">IList</span>&lt;<span style="color: #33cccc;">User</span>&gt; returnList;

    returnList = <span style="color: #0000ff;">new</span> List();

    <span style="color: #0000ff;">foreach</span>(UserItem currentUser <span style="color: #0000ff;">in</span> userList)
    {
        <span style="color: #0000ff;">switch</span>(property)
        {
            <span style="color: #0000ff;">case</span>(NeededProperty.Name):
                <span style="color: #0000ff;">if</span>(currentUser.Name == value)
                {
                    userList.Add(currentUser);
                }
                <span style="color: #0000ff;">break</span>;
            <span style="color: #0000ff;">case</span>(NeededProperty.Phone):
                <span style="color: #0000ff;">if</span>(currentUser.Phone == value)
                {
                    userList.Add(currentUser);
                }
                <span style="color: #0000ff;">break</span>;
        }
    }
 }</pre>
<p>Or you could do this:</p>
<pre> <span style="color: #0000ff;">public</span> <span style="color: #33cccc;">Func</span>&lt;<span style="color: #33cccc;">User</span>, <span style="color: #33cccc;">Boolean</span>&gt; MatchesProperty(<span style="color: #33cccc;">NeededProperty </span>property, <span style="color: #33cccc;">String</span> value)
 {
    <span style="color: #33cccc;">Func</span>&lt;<span style="color: #33cccc;">User</span>, <span style="color: #33cccc;">Boolean</span>&gt; returnValue;

    <span style="color: #0000ff;">switch</span>(property)
    {
        <span style="color: #0000ff;">case</span> <span style="color: #33cccc;">NeededProperty</span>.Name:
            returnValue = currentItem =&gt; currentItem.Name == value;
            <span style="color: #0000ff;">break</span>;
        <span style="color: #0000ff;">case</span> <span style="color: #33cccc;">NeededProperty</span>.Phone:
            returnValue = currentItem =&gt; currentItem.Phone == value;
            <span style="color: #0000ff;">break</span>;
    }
    <span style="color: #0000ff;">return</span> returnValue;
  }

 <span style="color: #0000ff;">public</span> <span style="color: #33cccc;">IList</span>&lt;<span style="color: #33cccc;">User</span>&gt; AllUsersThatMatch(<span style="color: #33cccc;">IList</span>&lt;<span style="color: #33cccc;">User</span>&gt; userList, <span style="color: #33cccc;">NeededProperty </span>property, <span style="color: #33cccc;">String </span>value)
 {
    <span style="color: #33cccc;">IList</span>&lt;<span style="color: #33cccc;">User</span>&gt;  returnList;

    returnList = userList.Where(MatchesProperty(property, value));
    <span style="color: #0000ff;">return</span> returnList;
 }</pre>
<p>Now which do you think is easier to upkeep? For those of you wondering what I did, I simply used a method that would return the Func I needed for the passed in Enum and called it in the Where clause. The amount of code is probably close to the same right now, but add in 5 more values for the NeededProperty enum and you&#8217;ll see the code amount differing more and more.</p>
<p>I realize this isn&#8217;t the best of example, and probably the first way could be refactored but the idea is still there. The Linq Method approach gives you a lot more flexibility in the long run with dynamic stuff like this.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/uhg-it-wont-end/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What Is Readable Addon</title>
		<link>http://byatool.com/pontification/what-is-readable-addon/</link>
		<comments>http://byatool.com/pontification/what-is-readable-addon/#comments</comments>
		<pubDate>Fri, 10 Oct 2008 15:03:43 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Pontification]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Func]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=58</guid>
		<description><![CDATA[Quick thought too about which to use due to readability: var you = from factor in seansAwesomeness select new FactorLite { Amount = amount; }; or you could do: Func&#60;Person, FactorLite&#62; selectFactorLite = currentFactor =&#62; new FactorLite { Amount = currentFactor.Amount }; seansAwesomeness.Select(selectFactorLite); I guess it&#8217;s a matter of preference, but the first seems way [...]]]></description>
			<content:encoded><![CDATA[<p>Quick thought too about which to use due to readability:</p>
<pre><span style="color: #0000ff;">var</span> you = <span style="color: #0000ff;">from</span> factor <span style="color: #0000ff;">in</span> seansAwesomeness
          <span style="color: #0000ff;">select</span> <span style="color: #0000ff;">new</span> FactorLite
          {
             Amount = amount;
          };</pre>
<p>or you could do:</p>
<pre><span style="color: #00ccff;">Func</span>&lt;<span style="color: #00ccff;">Person</span>, <span style="color: #00ccff;">FactorLite</span>&gt; selectFactorLite = currentFactor =&gt; <span style="color: #0000ff;">new</span> <span style="color: #00ccff;">FactorLite </span>{ Amount = currentFactor.Amount };

seansAwesomeness.Select(selectFactorLite);</pre>
<p>I guess it&#8217;s a matter of preference, but the first seems way too verbose for something too simple.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/pontification/what-is-readable-addon/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What Is Readable</title>
		<link>http://byatool.com/pontification/what-is-readable/</link>
		<comments>http://byatool.com/pontification/what-is-readable/#comments</comments>
		<pubDate>Fri, 10 Oct 2008 14:51:57 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Pontification]]></category>
		<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[FizzBuzz]]></category>
		<category><![CDATA[Func]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Select]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=56</guid>
		<description><![CDATA[So a couple of posts I read recently have been about readability of Linq, more so Linq query expressions versus the Linq methods. Don&#8217;t know what I mean? Expression: var result = from knowledge in Sean select knowledge.Linq; As opposed to: var result = Sean.Select(knowledge =&#62; knowledge.Linq); Personally I would replace the lambda expression with [...]]]></description>
			<content:encoded><![CDATA[<p>So a couple of posts I read recently have been about readability of Linq, more so Linq query expressions versus the Linq methods.  Don&#8217;t know what I mean?</p>
<p>Expression:</p>
<pre><span style="color: #0000ff;">var</span> result = <span style="color: #0000ff;">from</span> knowledge <span style="color: #0000ff;">in</span> Sean
             <span style="color: #0000ff;">select</span> knowledge.Linq;</pre>
<p>As opposed to:</p>
<pre><span style="color: #0000ff;">var</span> result = Sean.Select(knowledge =&gt; knowledge.Linq);</pre>
<p>Personally I would replace the lambda expression with a Func, but I can live with it right now. Anywho, the argument is that the first looks better than the second. I really don&#8217;t see this as a looks problem, but a useage problem. Fact is, they both have their uses and you should know how to read both. Why is that? Well here&#8217;s an example CAUSE I KNOW YOU WANT ONE!</p>
<p>One of my earlier posts had to do with <a title="FizzBuzz" href="http://byatool.com/?p=46">solving the FizzBuzz</a> thing with Linq where I gave you this bad ass solution:</p>
<pre> <span style="color: #0000ff;">var</span> result =
      listToConvert
      .<span style="color: #000000;">Where</span>(WhereBothDivisible(fizzNumber, buzzNumber))
      .<span style="color: #000000;">Select</span>(selectKeyValuePair(<span style="color: #ff0000;">"FizzBuzz"</span>))
      .Concat(
            listToConvert
            .Where(WhereBuzzDivisable(fizzNumber, buzzNumber))
            .Select(selectKeyValuePair(<span style="color: #ff0000;">"Buzz"</span>)))
            .Concat(
                  listToConvert
                  .Where(WhereFizzDivisable(fizzNumber, buzzNumber))
                  .Select(selectKeyValuePair(<span style="color: #ff0000;">"Fizz"</span>)))
                  .Concat(
                         listToConvert
                        .Where(WhereNeitherDivisable(fizzNumber, buzzNumber))
                        .Select(selectKeyValuePair(<span style="color: #ff0000;">"Nothing"</span>)));</pre>
<p>As you can see, I&#8217;ve used both Func fields and methods to return Funcs to clean up how this would look. I&#8217;ll even show what it would look like without this approach:</p>
<pre><span style="color: #0000ff;">var</span> result = listToConvert.Where(currentItem =&gt;
             IsDivisible(currentItem, fizzNumber) &amp;&amp; IsDivisible(currentItem, buzzNumber)
             ).Select(currentItem =&gt; new KeyValuePair(currentItem, <span style="color: #ff0000;">"FizzBuzz"</span>)).Concat(...</pre>
<p>Now I can totally admit that this second one I am showing is just ouch. So the first lesson to be learn is that Funcs and Methods that return Funcs can significantly clean up the Linq Method approach.</p>
<p>Now you could do the same with expressions:</p>
<pre> <span style="color: #0000ff;">var</span> fizzBuzz = <span style="color: #0000ff;">from</span> currentNumber <span style="color: #0000ff;">in</span> listToConvert
                <span style="color: #0000ff;">where</span> WhereBuzzDivisable(fizzNumber, buzzNumber)
                <span style="color: #0000ff;">select</span> selectKeyValuePair(<span style="color: #ff0000;">"FizzBuzz"</span>);

 <span style="color: #0000ff;">var</span> buzz = <span style="color: #0000ff;">from</span> currentNumber <span style="color: #0000ff;">in</span> listToConvert
            <span style="color: #0000ff;">where</span> WhereBuzzDivisable(fizzNumber, buzzNumber)
            <span style="color: #0000ff;">select</span> selectKeyValuePair(<span style="color: #ff0000;">"Buzz"</span>);

 <span style="color: #0000ff;">var</span> fizz = <span style="color: #0000ff;">from</span> currentNumber <span style="color: #0000ff;">in</span> listToConvert
            <span style="color: #0000ff;">where</span> WhereFizzDivisable(fizzNumber, buzzNumber)
            <span style="color: #0000ff;">select</span> selectKeyValuePair(<span style="color: #ff0000;">"Fizz"</span>);

<span style="color: #0000ff;">var</span> neither = <span style="color: #0000ff;">from</span> currentNumber <span style="color: #0000ff;">in</span> listToConvert
              <span style="color: #0000ff;">where</span> WhereNeitherDivisable(fizzNumber, buzzNumber)
              <span style="color: #0000ff;">select</span> selectKeyValuePair(<span style="color: #ff0000;">"Fizz"</span>);</pre>
<p>Ok so nice and pretty, but now what? Concatenation. This is where is gets ugly:</p>
<pre>  fizzBuzz.Concat(fizz.Concat(buzz.Concat(neither))));</pre>
<p>OR</p>
<pre> <span style="color: #0000ff;">var</span> fizzBuzz = <span style="color: #0000ff;">from</span> currentNumber <span style="color: #0000ff;">in</span> listToConvert
                <span style="color: #0000ff;">where</span> WhereBuzzDivisable(fizzNumber, buzzNumber)
                <span style="color: #0000ff;">select</span> selectKeyValuePair(<span style="color: #ff0000;">"FizzBuzz"</span>)
                .Concat(
                     <span style="color: #0000ff;">from</span> currentNumber <span style="color: #0000ff;">in</span> listToConvert
                     <span style="color: #0000ff;">where</span> WhereBuzzDivisable(fizzNumber, buzzNumber)
                     <span style="color: #0000ff;">select</span> selectKeyValuePair(<span style="color: #ff0000;">"Buzz"</span>))
                     .Concat(....);</pre>
<p>See what I&#8217;m getting at? The non expression one is looking a bit better now or maybe this is a fight to see which is less fugly. Now I admit that this may not be the best FizzBuzz solution, but it gives an example or where the Linq queries can go very wrong.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/pontification/what-is-readable/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dynamic Linq: OrderBy Using a String for a Property Name</title>
		<link>http://byatool.com/general-coding/orderby-using-a-property-name/</link>
		<comments>http://byatool.com/general-coding/orderby-using-a-property-name/#comments</comments>
		<pubDate>Wed, 01 Oct 2008 13:39:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Order By]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/10/01/orderby-using-a-property-name/</guid>
		<description><![CDATA[Now this is kind of dangerous to do since there is no compile time check (Like most things set in markup) but say you want to sort a collection, using the Linq extension methods, but you don&#8217;t know what you what to sort on at any given time. On top of that, you have a [...]]]></description>
			<content:encoded><![CDATA[<p>Now this is kind of dangerous to do since there is no compile time check (Like most things set in markup) but say you want to sort a collection, using the Linq extension methods, but you don&#8217;t know what you what to sort on at any given time. On top of that, you have a datagrid and a bunch of sort expressions to deal with. Now you could do something like create a hashtable full of lambda expressions that the key is the sort expression:</p>
<pre><span style="color: #00cccc;">Dictionary</span>&lt;<span style="color: #00cccc;">String</span>, <span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">IComparable</span>&gt;&gt; list;

userList = <span style="color: #00cccc;">User</span>.GetUserList();
list = <span style="color: #3333ff;">new</span> <span style="color: #00cccc;">Dictionary</span>&lt;<span style="color: #00cccc;">String</span>, <span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">IComparable</span>&gt;&gt;();
list.Add(<span style="color: #990000;">"UserName"</span>, currentUser =&gt; currentUser.UserName);
list.Add(<span style="color: #990000;">"UserID"</span>, currentUser =&gt; currentUser.UserID);
userList.OrderBy(list[<span style="color: #990000;">"UserID"</span>]);</pre>
<p>Works just fine, and might be preferable to what I&#8217;m about to show. OooOoOO sound eerie?</p>
<pre><span style="color: #009900;">//This is just to get the property info using reflection.  In order to get the value</span>
<span style="color: #009900;">//from a property dynamically, we need the property info from the class</span>
<span style="color: #3333ff;">public</span> <span style="color: #3333ff;">static</span> <span style="color: #00cccc;">PropertyInfo</span>[] GetInfo&lt;K&gt;(K item) <span style="color: #3333ff;">where</span> K : <span style="color: #3333ff;">class</span>
{
  <span style="color: #00cccc;">PropertyInfo</span>[] propertyList;
  <span style="color: #00cccc;">Type</span> typeInfo;

  typeInfo = item.GetType();
  propertyList = typeInfo.GetProperties();

  <span style="color: #3333ff;">return</span> propertyList;
}

<span style="color: #009900;">//This is the dynamic order by func that the OrderBy method needs to work</span>
<span style="color: #3333ff;">public</span> <span style="color: #3333ff;">static</span> <span style="color: #00cccc;">IComparable</span> OrderByProperty&lt;T&gt;(<span style="color: #00cccc;">String</span> propertyName, T item)
  <span style="color: #3333ff;">where</span> T : <span style="color: #3333ff;">class</span>
{
  <span style="color: #00cccc;">PropertyInfo</span>[] propertyList;

  propertyList = GetInfo(item);

  <span style="color: #009900;">//Here we get the value of that property of the passed in item and make sure</span>
  <span style="color: #009900;">//to type the object (Which is what GetValue returns) into an IComparable</span>
  return (<span style="color: #00cccc;">IComparable</span>)propertyList.First(currentProperty
    =&gt; currentProperty.Name == propertyName).GetValue(item, <span style="color: #3333ff;">null</span>);
}</pre>
<p>And use:</p>
<pre><span style="color: #009900;">//This takes the current user and calls the OrderByProperty method which in turn</span>
<span style="color: #009900;">//gives us the Func OrderBy is requesting.</span>
<span style="color: #3333ff;">var</span> test = userList.OrderBy(currentUser
  =&gt; DynamicPropertySort.OrderByProperty(<span style="color: #990000;">"UserID"</span>, currentUser)).ToList();</pre>
<p>Ok so what the hell? I mean intellisense on the OrderBy method doesn&#8217;t give much help. <span style="color: #00cccc;">Func</span>&lt;&lt;<span style="color: #00cccc;">User</span>, TKey&gt;&gt;. Yeah ok. So basically the return type is open. Well this kind of sucks right? Because I would have to return a Func that already knows the return type. (Be it string, int, ect) Of course, this would mean we would have to handle each sort expression in code. NOT VERY DYNAMIC IS IT? Well f that. Truth is, what the order by is looking for is a Func that takes in a User and returns something it can compare. This is where <span style="color: #00cccc;">IComparable </span>comes in.</p>
<p>The OrderBy has to take the returned value, say UserID which is an int, and figure out how to compare it to another value. Pretty simple. So as long as the property you are ordering by uses <span style="color: #00cccc;">IComparable</span>, you&#8217;re good to go. Pretty nice huh?</p>
<p>Now I would suggest, if you use this (HAHAHAHA), is to cache a dictionary of the property info with the class type as the key so that you don&#8217;t have to use as much reflection everytime. I just didn&#8217;t put that in.</p>
<p>U U USING</p>
<pre><span style="color: #3333ff;">using</span> System;
<span style="color: #3333ff;">using</span> System.Collections.Generic;
<span style="color: #3333ff;">using</span> System.Linq;
<span style="color: #3333ff;">using</span> System.Reflection;
<span style="color: #3333ff;">using</span> System.Text;</pre>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/orderby-using-a-property-name/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

