﻿<?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; Lessons</title>
	<atom:link href="http://byatool.com/category/lessons/feed/" rel="self" type="application/rss+xml" />
	<link>http://byatool.com</link>
	<description>ANDRE SMASH!!!!</description>
	<lastBuildDate>Wed, 28 Jul 2010 18:01:05 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Spark View Engine, ASP.Net MVC, and You</title>
		<link>http://byatool.com/lessons/spark-view-engine-asp-net-mvc-and-you/</link>
		<comments>http://byatool.com/lessons/spark-view-engine-asp-net-mvc-and-you/#comments</comments>
		<pubDate>Thu, 27 May 2010 15:10:28 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Spark]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1395</guid>
		<description><![CDATA[So one of the things I was forced to use, semi kicking and screaming, at one point in my illustrious career was the Spark View Engine for ASP.Net MVC. Actually that's not totally true. I only kicked for a bit then skipped the screaming once I noticed what it did: It took all the ugly [...]]]></description>
			<content:encoded><![CDATA[<p>So one of the things I was forced to use, semi kicking and screaming, at one point in my illustrious career was the <a href="http://dev.dejardin.org/">Spark View Engine for ASP.Net MVC</a>.  Actually that's not totally true.  I only kicked for a bit then skipped the screaming once I noticed what it did:  It took all the ugly &lt;% %&gt; junk out of the html... <a href="http://byatool.com/pontification/just-use-html-why-mvc-can-be-a-good-thing/">my beautiful html</a>... and made things like for loops much nicer.  Mind you, this is mererly the tip of the ice pick... eh berg I meant berg... there's a lot more to it.  It handles things like Master Pages and Partial Controls pretty darn well as well as caching javascript files on the go.  Sounds good?  Well it should and if it doesn't, I don't think we can be friends.</p>
<p>First off, I just wanted to quickly write something up on how to get it all going and because I'm such a nice guy <a href="http://byatool.com/Hosted/PhotoShare.UI.zip">I even have a project that is ready to go</a> for common use.  The catch is that I made it in 2010 so if you don't have that yet, you could be screwed.  Then again I could type out a lot of the steps too.  You just don't know.</p>
<p>First off you can either get the assemblies from my hosted project, <a href="http://sparkviewengine.codeplex.com/releases/view/27601">or you can go here</a> and get it.  Either way, I don't care.  No really, I don't.  Not just sayin'.  The care cup had run dry.</p>
<p>The two assemblies you need to reference in your project are:</p>
<pre>  spark.dll
  spark.mvc
</pre>
<p>Next add this line to the Application_Start method in the Global.asax.cs file:</p>
<pre>  <span style="color: #008080;">ViewEngines</span>.Engines.Add(<span style="color: #0000ff;">new</span> <span style="color: #008080;">SparkViewFactory</span>());
</pre>
<p>After that, you'll have to add a little somethin' somethin' to your web.config.  I know, I know.  This is all so very hard.  Live strong like Lance.</p>
<pre>  &lt;<span style="color: #ff0000;">configuration</span>&gt;
    ...
    &lt;<span style="color: #ff0000;">configSections</span>&gt;
      &lt;<span style="color: #ff0000;">section</span> <span style="color: #0000ff;">name=</span><span style="color: #800000;">"spark"</span> <span style="color: #ff0000;">type=</span><span style="color: #800000;">"Spark.Configuration.SparkSectionHandler, Spark"</span>/&gt;
    &lt;/<span style="color: #ff0000;">configSections</span>&gt;
    ...
    &lt;<span style="color: #ff0000;">spark</span>&gt;
      &lt;<span style="color: #ff0000;">compilation</span> <span style="color: #0000ff;">debug=</span><span style="color: #800000;">"true"</span> <span style="color: #0000ff;">defaultLanguage=</span><span style="color: #800000;">"CSharp"</span>&gt;
        &lt;<span style="color: #ff0000;">assemblies</span>&gt;
          &lt;<span style="color: #ff0000;">add</span> <span style="color: #0000ff;">assembly=</span><span style="color: #800000;">"PhotoShare.UI"</span> /&gt; /<span style="color: #008000;">/Whatever the actual UI project is</span>
        &lt;/<span style="color: #ff0000;">assemblies</span>&gt;
      &lt;/<span style="color: #ff0000;">compilation</span>&gt;
      &lt;<span style="color: #ff0000;">pages</span> <span style="color: #0000ff;">automaticEncoding=</span><span style="color: #800000;">"false"</span>&gt; <span style="color: #008000;">//If you want it to auto HTML encode post/get stuff</span>
        &lt;<span style="color: #ff0000;">namespaces</span>&gt;
          &lt;<span style="color: #ff0000;">add</span> <span style="color: #0000ff;">namespace=</span><span style="color: #800000;">"System"</span>/&gt;
          &lt;<span style="color: #ff0000;">add</span> <span style="color: #0000ff;">namespace=</span><span style="color: #800000;">"System.Collections.Generic"</span>/&gt;
          &lt;<span style="color: #ff0000;">add</span> <span style="color: #0000ff;">namespace=</span><span style="color: #800000;">"System.Linq"</span>/&gt;
          &lt;<span style="color: #ff0000;">add</span> <span style="color: #0000ff;">namespace=</span><span style="color: #800000;">"System.Web.Mvc"</span>/&gt;
        &lt;/<span style="color: #ff0000;">namespaces</span>&gt;
      &lt;/<span style="color: #ff0000;">pages</span>&gt;
    &lt;/<span style="color: #ff0000;">spark</span>&gt;
</pre>
<p>Ok so the web config is ready.  Now what?</p>
<p>Well now you are going to create a master page.  That's right you are.  Don't fight me on this.  I'm way cooler than you.</p>
<p>There is a little directory structure hard coding going on since by default you have to have things in certain places for Spark.  Oh well.  All Master Pages go in a directory named "Layouts" in the "Views" directory.  So something like:</p>
<pre>  Views/Layouts/Application.spark
</pre>
<p>D--- it.  Forgot about that little tid bit too.  Spark files have to be named .spark.  Well actually I think there's a way to call them whatever you want, but lets just go with defaults for now smarty pants.</p>
<p>And for the hard part, the html for the master page.</p>
<pre>  &lt;<span style="color: #ff0000;">html</span>&gt;
    &lt;<span style="color: #ff0000;">head</span>&gt;
    &lt;/<span style="color: #ff0000;">head</span>&gt;
    &lt;<span style="color: #ff0000;">body</span>&gt;
      &lt;<span style="color: #ff0000;">div</span>&gt;
        &lt;<span style="color: #ff0000;">use</span> <span style="color: #0000ff;">content=</span><span style="color: #800000;">"Middle"</span> /&gt;
          aasdfasdfa
      &lt;/<span style="color: #ff0000;">div</span>&gt;
    &lt;/<span style="color: #ff0000;">body</span>&gt;
  &lt;/<span style="color: #ff0000;">html</span>&gt;
</pre>
<p>HOLY HECK THAT'S HARD!  Now there needs to be a controller.  So just create one in the controllers folder.  In my project it's called this:</p>
<pre>  Controllers/SparkTestController.cs
</pre>
<p>And then go ahead and create a view for index.  Once you've done that, rename the extension from aspx to spark.  Now for the html:</p>
<pre>  &lt;<span style="color: #ff0000;">use</span> <span style="color: #0000ff;">master=</span><span style="color: #800000;">"Application"</span>/&gt;

  &lt;<span style="color: #ff0000;">div</span>&gt;
    &lt;<span style="color: #ff0000;">content</span> <span style="color: #0000ff;">name=</span><span style="color: #993300;">"Middle"</span>&gt;
        hi there
    &lt;/<span style="color: #ff0000;">content</span>&gt;
  &lt;/<span style="color: #ff0000;">div</span>&gt;
</pre>
<p>And that's it really.  As you can see, the placeholder on the master page (use content="Middle") is referred to on the child page.</p>
<p>To make testing this page easy, I would suggest changing the routing in the Global.asax.cs file to:</p>
<pre>  routes.MapRoute(
          <span style="color: #800000;">"Default"</span>,
          <span style="color: #800000;">"{controller}/{action}"</span>,
          <span style="color: #0000ff;">new</span> { controller = <span style="color: #800000;">"SparkTest"</span>, action = <span style="color: #800000;">"Index"</span>}
</pre>
<p>And you should see something like:</p>
<pre>  hi there aasdfasdfa
</pre>
<p>Proving that both the master page and the child page are printing stuff out.</p>
<p>You might be wondering why you should do all of this?  If you aren't, you are one hell of a lemming.  And not the cool kind like those little guys that blow themselves up for the betterment of the lemming collective.  You're that stupid one the just sits there with its hand out shaking its head.</p>
<p>A quick example:</p>
<pre>  <span style="color: #dcea0a;">&lt;%</span>
    <span style="color: #0000ff;">if</span>(something.IsTrue)
    {
  <span style="color: #dcea0a;">%&gt;</span>
       &lt;<span style="color: #ff0000;">div</span>&gt; hihihihih &lt;/<span style="color: #ff0000;">div</span>&gt;
  <span style="color: #dcea0a;">&lt;%</span>
    }
  <span style="color: #dcea0a;">%&gt;</span>
</pre>
<p>Compared to:</p>
<pre>  &lt;<span style="color: #ff0000;">div</span> <span style="color: #0000ff;">if=</span><span style="color: #800000;">"something.IsTrue"</span>&gt; hihihihih &lt;/<span style="color: #ff0000;">div</span>&gt;
</pre>
<p>Small example, but I think its pretty obvious why the second is so much better.  And this is just scratching the surface on what spark does really.   I'd suggest <a href="http://sparkviewengine.com/documentation">looking here</a> for more.  I'd also suggest a new hair cut because... just wow.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/writing/byatool-com-gets-a-shiny-new-tool/" title="ByATool.com gets a shiny new tool!">ByATool.com gets a shiny new tool!</a></li><li><a href="http://byatool.com/lessons/data-annotations-mvc-and-why-you-might-like-them/" title="Data Annotations, MVC, and Why You Might Like Them">Data Annotations, MVC, and Why You Might Like Them</a></li><li><a href="http://byatool.com/pontification/asp-net-mvc-quick-overview-of-controller-structure/" title="ASP.Net MVC:  Quick Overview of Controller Structure">ASP.Net MVC:  Quick Overview of Controller Structure</a></li><li><a href="http://byatool.com/pointless/asp-net-mvc-attibute-to-check-if-route-value-exists-and-and-means-something/" title="ASP.Net MVC: Attibute to Check if Route Value Exists and&#8230; and Means Something!">ASP.Net MVC: Attibute to Check if Route Value Exists and&#8230; and Means Something!</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/spark-view-engine-asp-net-mvc-and-you/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Failure scanning CollectionGen.dll for extensions.</title>
		<link>http://byatool.com/lessons/failure-scanning-collectiongen-dll-for-extensions/</link>
		<comments>http://byatool.com/lessons/failure-scanning-collectiongen-dll-for-extensions/#comments</comments>
		<pubDate>Thu, 15 Apr 2010 14:32:48 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Nant]]></category>
		<category><![CDATA[NantContrib]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1366</guid>
		<description><![CDATA[Quick hit, you might get this if you try loading the bin directory of the nantcontrib project AND YOU DIDN'T FOLLOW THIS POST. Solution, FOLLOW THIS POST or you can simply remove the CollectionGen.dll from the bin directory. However if you do that, you aren't helping my bounce rate and that makes you a Communist... [...]]]></description>
			<content:encoded><![CDATA[<p>Quick hit, you might get this if you try loading the bin directory of the nantcontrib project <a href="http://byatool.com/lessons/how-to-installusing-nantcontrib-because-the-documentation-sucks/">AND YOU DIDN'T FOLLOW THIS POST.</a></p>
<p>Solution, <a href="http://byatool.com/lessons/how-to-installusing-nantcontrib-because-the-documentation-sucks/">FOLLOW THIS POST</a> or you can simply remove the CollectionGen.dll from the bin directory.  However if you do that, you aren't helping my bounce rate and that makes you a Communist... unless you are a Communist then it makes you a Capitalist.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/how-to-installusing-nantcontrib-because-the-documentation-sucks/" title="How to Install/Using NantContrib BECAUSE THE DOCUMENTATION SUCKS">How to Install/Using NantContrib BECAUSE THE DOCUMENTATION SUCKS</a></li><li><a href="http://byatool.com/lessons/using-subversion-with-nant-automated-checkouts-from-config-file/" title="Using Subversion With Nant: Automated Checkouts From Config File">Using Subversion With Nant: Automated Checkouts From Config File</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/failure-scanning-collectiongen-dll-for-extensions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Install/Using NantContrib BECAUSE THE DOCUMENTATION SUCKS</title>
		<link>http://byatool.com/lessons/how-to-installusing-nantcontrib-because-the-documentation-sucks/</link>
		<comments>http://byatool.com/lessons/how-to-installusing-nantcontrib-because-the-documentation-sucks/#comments</comments>
		<pubDate>Thu, 15 Apr 2010 14:29:30 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Nant]]></category>
		<category><![CDATA[NantContrib]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1363</guid>
		<description><![CDATA[I understand I'm not what you call the sharpest bulb in the bunch, but readmes shouldn't be painful. They should be helpful. They should be kind and gentle, and remind you that the world is great and wonderful. Not put you on the verge of a three figure body count. In a way, this is [...]]]></description>
			<content:encoded><![CDATA[<p>I understand I'm not what you call the sharpest bulb in the bunch, but readmes shouldn't be painful.  They should be helpful.  They should be kind and gentle, and remind you that the world is great and wonderful.  Not put you on the verge of a three figure body count.  In a way, this is why I've shied away from a lot of open source stuff since the readme files read like instructions for putting together something from IKEA.  And not the horrible broken English ones, more like the ones with all those funny squiggly lines.  (I think it's call "Chinese")  Why is it always so painful to figure something out WHEN YOU HAVE INSTRUCTIONS?  Best hint on writing instructions, always assume the person you're writing to is an idiot.  You can infer from that whatever you want.</p>
<p>Anyhow, NantContrib, the library of things that adds on to Nant (With brilliant ideas like being able to add an else to an if WOW), is a victim of nothumanenoughtowriteadecentreadmefileinawaythatnormalhumansunderstanditis (Otherwise known as Thoreau Syndrome) so I thought I would save you some together time between your head and your monitor.</p>
<p>Now you could go download it from wherever it is, or you can just grab <a href="http://www.byatool.com/hosted/nantcontrib.zip">this</a> which is nantcontrib post "fixing" it.  Basically if you get my version, all you have to do is drop it somewhere, anywhere, and extract.  I put it in the same directory that Nant is, so they sort of sit side by side but separate.  A happy little couple, at least for the first few years until Nant has a mid life crisis and decides it's time to get a Corvette and start rolling for college girls at which point nantcontrib starts eying the Fedex guy.  Right now, its idealistic bliss.</p>
<p>Once you've done that, all you have to do is drop this bit into your nant script, probably above your properties, but it possibly can go other places.  I haven't really looked into that.</p>
<pre>
&lt;loadtasks&gt;
  &lt;fileset&gt;
    &lt;include name="c:\nantcontrib\bin\lib\" /&gt;
  &lt;/fileset&gt;
&lt;/loadtasks&gt;
</pre>
<p>And now you are ready to go.</p>
<p>Now you might be curious about what I did to the directory structure of the nantcontrib stuff.  It's actually pretty simple. I just took the bin folder and split it up. (Something I kind of pieced together from random pages)  I took what I understand to be the important stuff (All the dlls except CollectionGen.dll and SlingShot.core.dll.. wait I'm sorry SLiNgshoT.core.dll cause f---ed up casing means its that much better. ITS HARDCORE MAN!  TO THE XXXXXXXTREEEEMEEEE!) and put it into a new folder "lib" that still resides in the bin folder.  The rest of the stuff went into a new folder "tasks".  Then I had the loadtask command include everything in bin\lib.  Boom, everything works as it should.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/failure-scanning-collectiongen-dll-for-extensions/" title="Failure scanning CollectionGen.dll for extensions.">Failure scanning CollectionGen.dll for extensions.</a></li><li><a href="http://byatool.com/lessons/using-subversion-with-nant-automated-checkouts-from-config-file/" title="Using Subversion With Nant: Automated Checkouts From Config File">Using Subversion With Nant: Automated Checkouts From Config File</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/how-to-installusing-nantcontrib-because-the-documentation-sucks/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Force Embeded Video Behind A JQuery Modal Dialog</title>
		<link>http://byatool.com/lessons/force-embeded-video-behind-a-jquery-modal-dialog/</link>
		<comments>http://byatool.com/lessons/force-embeded-video-behind-a-jquery-modal-dialog/#comments</comments>
		<pubDate>Tue, 13 Apr 2010 17:22:22 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[Video]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1361</guid>
		<description><![CDATA[Another quick one, [insert joke about sexual performance... HAHAHAHEHARHAHRAH] and I'll probably file this under "I don't care you if need this but I'm posting it because I have a bad memory". When you use the jQuery Modal Dialog with an embedded video, like say something from youtube, and you have a modal dialog on [...]]]></description>
			<content:encoded><![CDATA[<p>Another quick one, [insert joke about sexual performance... HAHAHAHEHARHAHRAH] and I'll probably file this under "I don't care you if need this but I'm posting it because I have a bad memory".  When you use the jQuery Modal Dialog with an embedded video, like say something  from youtube, and you have a modal dialog on the same page, you might notice that the video stays in front of the dialog.  This would be considered contrary to design.  Nice thing is, it's an easy fix:</p>
<pre>&lt;<span style="color: #800000;">object</span> <span style="color: #0000ff;">class<span style="color: #ff0000;">=</span></span><span style="color: #ff0000;">"nospace"</span> <span style="color: #0000ff;">data=</span><span style="color: #ff0000;">"http://www.youtube.com/v/jU_lNNwCLp0&amp;hl=en_US&amp;fs=1&amp;" height="320" type="application/x-shockwave-flash"</span> <span style="color: #0000ff;">width=</span><span style="color: #ff0000;">"400"</span> &gt;
  &lt;<span style="color: #800000;">param</span> <span style="color: #0000ff;">name<span style="color: #ff0000;">=</span></span><span style="color: #ff0000;">"movie"</span> <span style="color: #0000ff;">value=</span><span style="color: #ff0000;">"http://www.youtube.com/v/jU_lNNwCLp0&amp;hl=en_US&amp;fs=1&amp;"</span> /&gt;
  &lt;<span style="color: #800000;">param</span> <span style="color: #0000ff;">name=</span><span style="color: #ff0000;">"allowFullScreen"</span> <span style="color: #0000ff;">value<span style="color: #ff0000;">=</span></span><span style="color: #ff0000;">"true"</span> /&gt;
  &lt;<span style="color: #800000;">param</span> <span style="color: #0000ff;">name<span style="color: #ff0000;">=</span></span><span style="color: #ff0000;">"allowscriptaccess"</span> <span style="color: #0000ff;">value<span style="color: #ff0000;">=</span></span><span style="color: #ff0000;">"always"</span>/&gt;
  &lt;<span style="color: #800000;">param</span> <span style="color: #0000ff;">name<span style="color: #ff0000;">=</span></span><span style="color: #ff0000;">"wmode"</span> <span style="color: #0000ff;">value<span style="color: #ff0000;">=</span></span><span style="color: #ff0000;">"opaque"</span>/&gt; <span style="color: #008000;">&lt;----- RIGHT THERE LOOK SEE IT?????</span>
&lt;/<span style="color: #800000;">object</span>&gt;
</pre>
<p>It's the last parameter in that block.  I posted the whole thing because it just seemed easier.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/element-embed-is-not-supported-embedding-youtube-video-without-the-embed-tag/" title="Element &#8216;Embed&#8217; Is Not Supported: Embedding YouTube Video Without The Embed Tag">Element &#8216;Embed&#8217; Is Not Supported: Embedding YouTube Video Without The Embed Tag</a></li><li><a href="http://byatool.com/ui/quick-hit-hiding-horizontal-or-verticle-scroll-using-css/" title="Quick Hit: Hiding Horizontal or Verticle scroll using CSS">Quick Hit: Hiding Horizontal or Verticle scroll using CSS</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/force-embeded-video-behind-a-jquery-modal-dialog/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Element &#8216;Embed&#8217; Is Not Supported: Embedding YouTube Video Without The Embed Tag</title>
		<link>http://byatool.com/lessons/element-embed-is-not-supported-embedding-youtube-video-without-the-embed-tag/</link>
		<comments>http://byatool.com/lessons/element-embed-is-not-supported-embedding-youtube-video-without-the-embed-tag/#comments</comments>
		<pubDate>Tue, 13 Apr 2010 16:52:44 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[Video]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1356</guid>
		<description><![CDATA[This should be quick, so don't expect my usual charming self. If you've run into this problem, and chances are you have, you're probably as frustrated as a thumbless hitchhiker. Good thing is, I have the solution and you can watch it here on video: HAHAH THAT WAS FUNNY! Yeah I'm not that big of [...]]]></description>
			<content:encoded><![CDATA[<p>This should be quick, so don't expect my usual charming self.  If you've run into this problem, and chances are you have, you're probably as frustrated as a thumbless hitchhiker.  Good thing is, I have the solution and you can <a href="http://byatool.com/wp-content/uploads/2010/04/nodog.jpg">watch it here on video:</a></p>
<p>HAHAH THAT WAS FUNNY!  Yeah I'm not that big of a bag.  I actually will give you the code.  Go figure.</p>
<pre>&lt;<span style="color: #800000;">object</span> <span style="color: #0000ff;">class<span style="color: #ff0000;">=</span></span><span style="color: #ff0000;">"nospace"</span> <span style="color: #0000ff;">data=</span><span style="color: #ff0000;">"http://www.youtube.com/v/jU_lNNwCLp0&amp;hl=en_US&amp;fs=1&amp;" height="320" type="application/x-shockwave-flash"</span> <span style="color: #0000ff;">width=</span><span style="color: #ff0000;">"400"</span> &gt;
  &lt;<span style="color: #800000;">param</span> <span style="color: #0000ff;">name<span style="color: #ff0000;">=</span></span><span style="color: #ff0000;">"movie"</span> <span style="color: #0000ff;">value=</span><span style="color: #ff0000;">"http://www.youtube.com/v/jU_lNNwCLp0&amp;hl=en_US&amp;fs=1&amp;"</span> /&gt;
  &lt;<span style="color: #800000;">param</span> <span style="color: #0000ff;">name=</span><span style="color: #ff0000;">"allowFullScreen"</span> <span style="color: #0000ff;">value<span style="color: #ff0000;">=</span></span><span style="color: #ff0000;">"true"</span> /&gt;
  &lt;<span style="color: #800000;">param</span> <span style="color: #0000ff;">name<span style="color: #ff0000;">=</span></span><span style="color: #ff0000;">"allowscriptaccess"</span> <span style="color: #0000ff;">value<span style="color: #ff0000;">=</span></span><span style="color: #ff0000;">"always"</span>/&gt;
&lt;/<span style="color: #800000;">object</span>&gt;
</pre>
<p>And there it is.  Easy as something other than pie because pie isn't f---ing easy to make.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/force-embeded-video-behind-a-jquery-modal-dialog/" title="Force Embeded Video Behind A JQuery Modal Dialog">Force Embeded Video Behind A JQuery Modal Dialog</a></li><li><a href="http://byatool.com/ui/quick-hit-hiding-horizontal-or-verticle-scroll-using-css/" title="Quick Hit: Hiding Horizontal or Verticle scroll using CSS">Quick Hit: Hiding Horizontal or Verticle scroll using CSS</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/element-embed-is-not-supported-embedding-youtube-video-without-the-embed-tag/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Subversion With Nant: Automated Checkouts From Config File</title>
		<link>http://byatool.com/lessons/using-subversion-with-nant-automated-checkouts-from-config-file/</link>
		<comments>http://byatool.com/lessons/using-subversion-with-nant-automated-checkouts-from-config-file/#comments</comments>
		<pubDate>Mon, 05 Apr 2010 13:55:20 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Nant]]></category>
		<category><![CDATA[Subversion]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1347</guid>
		<description><![CDATA[This is the first part of a I HAVE NO CLUE HOW MANY part thing involving Nant and how to use it to make your life easier. Of course you might wonder why I'm using Nant over say MSBuild, (Though I'm sure you were actually wondering if you really can get ripped in two weeks) [...]]]></description>
			<content:encoded><![CDATA[<p>This is the first part of a I HAVE NO CLUE HOW MANY part thing involving Nant and how to use it to make your life easier. Of course you might wonder why I'm using Nant over say MSBuild, (Though I'm sure you were actually wondering if you really can get ripped in two weeks) and I have no real reason other than at some point this will tie into Cruise Control for easy deployments. Fact is, the debate between nant and msbuild is an ongoing war between the hopeless broken records known as Microsoft haters and the mindless Microbots. Personal, I don't really care since they are both fine. I may some day switch to MSBuild but for the scope of this article that MIGHT BE A BIT STUPID AND HYPOCRITICAL.</p>
<p>Also you might wonder about why I'm using subversion instead of say Team Foundation Server. (And no you can't get ripped in two weeks) Probably has to do with the 10k I don't have to shell out for something that is about two generations behind subversion... and that's saying something since subversion is about two generations behind source control in general. But my subversion hosting is 3.95 a month. So it really comes down to what is the only thing that matters when developing: Money.</p>
<p>Say you have someone new coming in and you want to be able to have said person be able to get a project from a subversion repository without really thinking. (You can't assume new people think.) This is mostly helpful because chances are you're place of employment is a revolving door just like every other place. So the thought of automation comes to mind. What if I told you getting things from a subversion repository is as easy as a config file? "Balderdash!", you say. "The f--- is balderdash?", I reply. And at somepoint we talking an common language and I show you this:</p>
<pre>&lt;<span style="color: #800000;">project</span> <span style="color: #ff0000;">name=</span><span style="color: #0000ff;">"ToolInstall"</span> <span style="color: #ff0000;">default=</span><span style="color: #0000ff;">"download"</span>&gt;
  &lt;<span style="color: #800000;">property</span> <span style="color: #ff0000;">name=</span><span style="color: #0000ff;">"toolProject"</span> <span style="color: #ff0000;">value=</span><span style="color: #0000ff;">"ToolsProject"</span> /&gt;
  &lt;<span style="color: #800000;">property</span> <span style="color: #ff0000;">name=</span><span style="color: #0000ff;">"svnLocation"</span> <span style="color: #ff0000;">value=</span><span style="color: #0000ff;">"c:\program files\subversion\bin\svn.exe"</span> /&gt;

  &lt;<span style="color: #800000;">target</span> <span style="color: #ff0000;">name=</span><span style="color: #0000ff;">"clean"</span> <span style="color: #ff0000;">description=</span><span style="color: #0000ff;">"cleans build directory"</span>&gt;
    &lt;<span style="color: #800000;">delete</span> <span style="color: #ff0000;">dir=</span><span style="color: #0000ff;">"${toolProject}"</span> <span style="color: #ff0000;">verbose=</span><span style="color: #0000ff;">"false"</span> <span style="color: #ff0000;">failonerror</span>=<span style="color: #0000ff;">"false"</span>/&gt;
  &lt;/<span style="color: #800000;">target</span>&gt;

  &lt;<span style="color: #800000;">target</span> <span style="color: #ff0000;">name=</span><span style="color: #0000ff;">"download"</span> <span style="color: #ff0000;">description=</span><span style="color: #0000ff;">"gets projects from repository"</span> <span style="color: #ff0000;">depends=</span><span style="color: #0000ff;">"clean"</span>&gt;
   &lt;<span style="color: #800000;">exec</span> <span style="color: #ff0000;">program=</span><span style="color: #0000ff;">"${svnLocation}"</span> <span style="color: #ff0000;">commandline=</span><span style="color: #0000ff;">"checkout http://some.repository.com/trunk/src/ToolProject ToolProject --username tool --password somepassword"</span>/&gt;
  &lt;/<span style="color: #800000;">target</span>&gt;
&lt;/<span style="color: #800000;">project</span>&gt;</pre>
<p>What's all of this? Well I am here to break it down. Oh Oh Whoooaaa.</p>
<pre>&lt;<span style="color: #800000;">project</span> <span style="color: #ff0000;">name=</span><span style="color: #0000ff;">"ToolInstall"</span> <span style="color: #ff0000;">default=</span><span style="color: #0000ff;">"download"</span>&gt;</pre>
<p>First element of the file has to be project. The name isn't all that important to this example, however Default means whith taget it will run first if you don't tell it.</p>
<pre>  &lt;<span style="color: #800000;">property</span> <span style="color: #ff0000;">name=</span><span style="color: #0000ff;">"toolProject"</span> <span style="color: #ff0000;">value=</span><span style="color: #0000ff;">"ToolsProject"</span> /&gt;
  &lt;<span style="color: #800000;">property</span> <span style="color: #ff0000;">name=</span><span style="color: #0000ff;">"svnLocation"</span> <span style="color: #ff0000;">value=</span><span style="color: #0000ff;">"c:\program files\subversion\bin\svn.exe"</span> /&gt;</pre>
<p>Think of a Property as a variable. They just allow you to take out as many repeated strings as possible. You'll see that the svnLocation Property points to where subversion was installed. This will vary per computer if you didn't specify the name of the install directory.</p>
<pre>  &lt;<span style="color: #800000;">target</span> <span style="color: #ff0000;">name=</span><span style="color: #0000ff;">"clean"</span> <span style="color: #ff0000;">description=</span><span style="color: #0000ff;">"cleans build directory"</span>&gt;
    &lt;<span style="color: #800000;">delete</span> <span style="color: #ff0000;">dir=</span><span style="color: #0000ff;">"${toolProject}"</span> <span style="color: #ff0000;">verbose=</span><span style="color: #0000ff;">"false"</span> <span style="color: #ff0000;">failonerror</span>=<span style="color: #0000ff;">"false"</span>/&gt;
  &lt;/<span style="color: #800000;">target</span>&gt;</pre>
<p>A target is basically a task you need to have done. It could be anything from deleting junk, running tests, or getting you a date. (HAHA ITS FUNAY CAUSE THATS IMPOSSIBLE) For this one, it is simply removing a folder that may exist. You can use this same idea to remove bin and obj folders if you use nant to build your project or simply clean it... But I'll get to building in another post.</p>
<pre>  &lt;<span style="color: #800000;">target</span> <span style="color: #ff0000;">name=</span><span style="color: #0000ff;">"download"</span> <span style="color: #ff0000;">description=</span><span style="color: #0000ff;">"gets projects from repository"</span> <span style="color: #ff0000;">depends=</span><span style="color: #0000ff;">"clean"</span>&gt;
   &lt;<span style="color: #800000;">exec</span> <span style="color: #ff0000;">program=</span><span style="color: #0000ff;">"${svnLocation}"</span> <span style="color: #ff0000;">commandline=</span><span style="color: #0000ff;">"checkout http://some.repository.com/trunk/src/ToolProject ToolProject --username tool --password somepassword"</span>/&gt;
  &lt;/<span style="color: #800000;">target</span>&gt;</pre>
<p>And there's the best part of the post, using nant to grab something from a subversion repository. As you can see, I've used the svnLocation property to make it easier to set what Program to use. I think this target is pretty much self explanitory for anyone with an IQ higher that that of a potato.</p>
<p>Next step is just to create a batch file to call nant and run this config file. Let's assume you called it Nant.install. I know, it's so descriptive, it's genius. Shut up, I get the sarcasm.</p>
<p>Here's the batch file:</p>
<pre>@..\nant\nant.exe -buildfile:Nant.install</pre>
<p>Mind you @..\nant\nant.exe will change depending where your copy of nant.exe is, but I figured I leave that in the way it is just to show that it doesn't have to reside in the same place.</p>
<p>And there you have it, subversion and nant together like two children frolicking in the forests of Bavaria. (Assuming they have forests there and me mentioning kids isn't creepy) In my next post I'll probably go more into nant itself, this was just kind of on a whim. And I don't know why I am appologizing for this. Stop f---ing judging me.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/failure-scanning-collectiongen-dll-for-extensions/" title="Failure scanning CollectionGen.dll for extensions.">Failure scanning CollectionGen.dll for extensions.</a></li><li><a href="http://byatool.com/lessons/how-to-installusing-nantcontrib-because-the-documentation-sucks/" title="How to Install/Using NantContrib BECAUSE THE DOCUMENTATION SUCKS">How to Install/Using NantContrib BECAUSE THE DOCUMENTATION SUCKS</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/using-subversion-with-nant-automated-checkouts-from-config-file/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Use a Factory Method With Castle / WindsorContainer</title>
		<link>http://byatool.com/lessons/how-to-use-a-factory-method-with-castle-windsorcontainer/</link>
		<comments>http://byatool.com/lessons/how-to-use-a-factory-method-with-castle-windsorcontainer/#comments</comments>
		<pubDate>Fri, 02 Apr 2010 13:29:13 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Castle]]></category>
		<category><![CDATA[Mocking]]></category>
		<category><![CDATA[Test]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1316</guid>
		<description><![CDATA[In my last post, I showed you the wonder of the WindsorContainer and creating concrete objects from a config file... but I wasn't done yet. In fact, if you looked at my example and used your keen sense of observation (I'm suspending my disbelief) you might have noticed a little somethin' somethin' in the config [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://byatool.com/lessons/castle-rhino-mocking-and-possibly-you/">In my last post</a>, I showed you the wonder of the WindsorContainer and creating concrete objects from a config file... but I wasn't done yet. In fact, if you looked at <a href="http://byatool.com/Hosted/LiveDemos/CastleConfigTest.zip">my example</a> and used your keen sense of observation (I'm suspending my disbelief) you might have noticed a little somethin' somethin' in the config file that I didn't explain:</p>
<pre>  &lt;<span style="color: #800000;">component</span> <span style="color: #0000ff;">id=</span><span style="color: #ff0000;">"factoryB"
</span>    <span style="color: #0000ff;">type=</span><span style="color: #ff0000;">"CastleConfigTest.Factory.FactoryB, CastleConfigTest"</span>&gt;
  &lt;/<span style="color: #800000;">component</span>&gt;

  &lt;<span style="color: #800000;">component</span> <span style="color: #0000ff;">id=</span><span style="color: #ff0000;">"childClassB"
</span>   <span style="color: #0000ff;">type=</span><span style="color: #ff0000;">"CastleConfigTest.Interface.IBaseClassB, CastleConfigTest"</span>
   <span style="color: #0000ff;">factoryId=</span><span style="color: #ff0000;">"factoryB"</span>
   <span style="color: #0000ff;">factoryCreate=</span><span style="color: #ff0000;">"Create"</span>&gt;
  &lt;/<span style="color: #800000;">component</span>&gt;</pre>
<p>And:</p>
<pre>  &lt;<span style="color: #800000;">facilities</span>&gt;
    &lt;<span style="color: #800000;">facility</span> <span style="color: #0000ff;">id=</span><span style="color: #ff0000;">"factorysupport"</span> <span style="color: #0000ff;">type=</span><span style="color: #ff0000;">"Castle.Facilities.FactorySupport.FactorySupportFacility, Castle.Microkernel"</span> /&gt;
  &lt;/<span style="color: #800000;">facilities</span>&gt;</pre>
<p>What are these??? Could they be the proof of intelligent life we've been looking for? Sadly no, since they actually are part of something that sounds a lot more complicated then it is. Say you have this interface:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">interface</span> <span style="color: #008080;">IBaseClassB</span>
  {
    <span style="color: #008080;">String</span> ClassName();
  }</pre>
<p>And this class:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">ChildClassB </span>: <span style="color: #008080;">IBaseClassB</span>
  {
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> ClassName()
    {
      <span style="color: #0000ff;">return</span> <span style="color: #800000;">"ChildClassB"</span>;
    }
  }</pre>
<p>Which is all pretty straight forward much like that woman's answer to you asking her out, "God no."</p>
<p>If you had <a href="http://byatool.com/lessons/castle-rhino-mocking-and-possibly-you/">read this post</a>, you might guess where this is going. Or you might guess that I'm going to re-explain it because you are too lazy to go and read it. One of those is correct.</p>
<p>Once again like my last post I do something simple like this:</p>
<pre>  <span style="color: #0000ff;">var</span> test = <span style="color: #0000ff;">new</span> <span style="color: #008080;">ObjectFactory</span>().Create&lt;<span style="color: #008080;">IBaseClassB</span>&gt;();</pre>
<p>And what I get is a brand new shiny ChildClassB. I can hear the yawns from here SO I'll change it up a bit. What if I need ChildClassB to come from a Factory? How the hell would I pull that off?</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">FactoryB
</span>  {
    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">IBaseClassB</span> Create()
    {
      <span style="color: #0000ff;">var</span> test = <span style="color: #0000ff;">new</span> <span style="color: #008080;">ChildClassB</span>();
      <span style="color: #008000;">//Do some stuff to test</span>
      <span style="color: #0000ff;">return</span> test;
    }
  }</pre>
<p>I no longer can just replace IBaseClassB with ChildClassB directly because I need FactoryB to do something for me first. (I cheated by just adding a comment where code might go.  Point is, something happens to ChildClassB before the factory returns it.) OH NO! WHAT AM I TO DO? HOW CAN I SOLVE THIS? DOES THE CAPSLOCK ADD SUSPENSE?</p>
<p>Guess what? That's right, that's where that config stuff at the top comes in. Here's the config file in full:</p>
<pre>&lt;<span style="color: #800000;">configuration</span>&gt;
  &lt;<span style="color: #800000;">components</span>&gt;
    &lt;<span style="color: #800000;">component</span> <span style="color: #0000ff;">id=</span><span style="color: #ff0000;">"factoryB"</span>
      <span style="color: #0000ff;">type=</span><span style="color: #ff0000;">"CastleConfigTest.Factory.FactoryB, CastleConfigTest"</span>&gt;
    &lt;/<span style="color: #800000;">component</span>&gt;
    &lt;<span style="color: #800000;">component</span> <span style="color: #0000ff;">id=</span><span style="color: #ff0000;">"childClassB"</span>
     <span style="color: #0000ff;">type=</span><span style="color: #ff0000;">"CastleConfigTest.Interface.IBaseClassB, CastleConfigTest"</span>
     <span style="color: #0000ff;">factoryId=</span><span style="color: #ff0000;">"factoryB"</span>
     <span style="color: #0000ff;">factoryCreate=</span><span style="color: #ff0000;">"Create"</span>&gt;
    &lt;/<span style="color: #800000;">component</span>&gt;
  &lt;/<span style="color: #800000;">components</span>&gt;
  &lt;<span style="color: #800000;">facilities</span>&gt;
    &lt;<span style="color: #800000;">facility</span> <span style="color: #0000ff;">id=</span><span style="color: #ff0000;">"factorysupport"</span> <span style="color: #0000ff;">type=</span><span style="color: #ff0000;">"Castle.Facilities.FactorySupport.FactorySupportFacility, Castle.Microkernel"</span> /&gt;
  &lt;/<span style="color: #800000;">facilities</span>&gt;
&lt;/<span style="color: #800000;">configuration</span>&gt;
</pre>
<p>Ok so I lied, that's not the full thing I have in <a href="http://byatool.com/Hosted/LiveDemos/CastleConfigTest.zip"> my example that you can download</a>, but it is what you need for this part.  It's actually pretty simple too.  You just need to declare three things:</p>
<p>The factory class "FactoryB"</p>
<pre>    &lt;<span style="color: #800000;">component</span> <span style="color: #0000ff;">id=</span><span style="color: #ff0000;">"factoryB"</span>
      <span style="color: #0000ff;">type=</span><span style="color: #ff0000;">"CastleConfigTest.Factory.FactoryB, CastleConfigTest"</span>&gt;
    &lt;/<span style="color: #800000;">component</span>&gt;</pre>
<p>The interface you want to mask with the factory return (IBaseClassB)</p>
<pre>    &lt;<span style="color: #800000;">component</span> <span style="color: #0000ff;">id=</span><span style="color: #ff0000;">"childClassB"</span>
     <span style="color: #0000ff;">type=</span><span style="color: #ff0000;">"CastleConfigTest.Interface.IBaseClassB, CastleConfigTest"</span>  <span style="color: #008000;">//This is the interface to look for</span>
     <span style="color: #0000ff;">factoryId=</span><span style="color: #ff0000;">"factoryB"</span>  <span style="color: #008000;">//This is the id from above where you declared the factoryB section</span>
     <span style="color: #0000ff;">factoryCreate=</span><span style="color: #ff0000;">"Create"</span>&gt;  <span style="color: #008000;">//This is the method to use</span>
    &lt;/<span style="color: #800000;">component</span>&gt;</pre>
<p>and the Castle part for using factories</p>
<pre>  &lt;<span style="color: #800000;">facilities</span>&gt;
    &lt;<span style="color: #800000;">facility</span> <span style="color: #0000ff;">id=</span><span style="color: #ff0000;">"factorysupport"</span> <span style="color: #0000ff;">type=</span><span style="color: #ff0000;">"Castle.Facilities.FactorySupport.FactorySupportFacility, Castle.Microkernel"</span> /&gt;
  &lt;/<span style="color: #800000;">facilities</span>&gt;</pre>
<p>And that's really it.  From that, this should work:</p>
<pre>    [<span style="color: #008080;">TestMethod</span>]
    p<span style="color: #0000ff;">ublic</span> <span style="color: #0000ff;">void</span> Create_ClassB()
    {
      <span style="color: #008000;">//This will call FactoryB.Create to create the ChildClassB for me</span>
      <span style="color: #0000ff;">var</span> test = <span style="color: #0000ff;">new</span> <span style="color: #008080;">ObjectFactory</span>().Create();
      <span style="color: #008080;">Assert</span>.IsTrue(test.ClassName().Equals(<span style="color: #ff0000;">"ChildClassB"</span>));
    }</pre>
<p>Woo hoo!  Now you can run home and impress your Wife/Husband/fiance/partner/thing that lives in your apartment and always seems to pay the rent late but doesn't have any issue with eating everything in your fridge!  Enjoy!</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/castle-rhino-mocking-and-possibly-you/" title="Castle, Rhino, Mocking, and Possibly You">Castle, Rhino, Mocking, and Possibly You</a></li><li><a href="http://byatool.com/lessons/dictionary-index-lookup-vs-contains-key-vs-list-contains-vs-linq-speed-testtexas-tornado-match/" title="Dictionary Index Lookup Vs Contains Key Vs List Contains Vs Linq&#8230; Speed Test/Texas Tornado Match">Dictionary Index Lookup Vs Contains Key Vs List Contains Vs Linq&#8230; Speed Test/Texas Tornado Match</a></li><li><a href="http://byatool.com/general-coding/filling-a-private-field-on-a-base-class/" title="Filling a Private Field on a Base Class Using Reflection">Filling a Private Field on a Base Class Using Reflection</a></li><li><a href="http://byatool.com/test/mulitple-constraint-generics-and-test-base-classes/" title="Mulitple Constraint Generics and Test Base Classes">Mulitple Constraint Generics and Test Base Classes</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/how-to-use-a-factory-method-with-castle-windsorcontainer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Castle, Rhino, Mocking, and Possibly You</title>
		<link>http://byatool.com/lessons/castle-rhino-mocking-and-possibly-you/</link>
		<comments>http://byatool.com/lessons/castle-rhino-mocking-and-possibly-you/#comments</comments>
		<pubDate>Thu, 01 Apr 2010 17:17:38 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Castle]]></category>
		<category><![CDATA[Mocking]]></category>
		<category><![CDATA[Test]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1282</guid>
		<description><![CDATA[So here's the issue, you have a class that you new up within a class. class SomeClass { private HelperClass someHelperClass; public SomeClass() { someHelperClass = new HelperClass(); } public String DoSomething() { return someHelperClass.DoSomeThing(); } } You with me? Cause if you're not, you've probably made a serious error in career choice. Now what's [...]]]></description>
			<content:encoded><![CDATA[<p>So here's the issue, you have a class that you new up within a class.</p>
<pre><span style="color: #0000ff;">class</span> SomeClass
{
  <span style="color: #0000ff;">private</span> <span style="color: #008080;">HelperClass</span> someHelperClass;

  <span style="color: #0000ff;">public</span> SomeClass()
  {
    someHelperClass = <span style="color: #0000ff;">new</span> <span style="color: #008080;">HelperClass</span>();
  }

  <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> DoSomething()
  {
    <span style="color: #0000ff;">return</span> someHelperClass.DoSomeThing();
  }
}</pre>
<p>You with me?  Cause if you're not, you've probably made a serious error in career choice.</p>
<p>Now what's the problem with that situation?  Testing.  That SomeClass is tightly coupled with the HelperClass so that if you want to unit test DoSomething, you're kind of screwed.  Why?  Say HelperClass has a database connection or does something that would update the database?  Do you really want to create bad data every time you run this test?  Do you really want the overhead of creating those connections and who knows what else?  If you answered yes, again reconsider your career.</p>
<p>Now you could do something like this:</p>
<pre><span style="color: #0000ff;">class</span> SomeClass
{
  ....
  <span style="color: #0000ff;">public</span> SomeClass(<span style="color: #33cccc;">HelperClass</span> injectAHelperClass) &lt;-- Change is right here genius.
  {
    someHelperClass = injectAHelperClass;
  }
  ...
}</pre>
<p>Next step would be to mock the HelperClass in a unit test and pass in the mock object.  But there's a deeper problem.  Deeper than G.I. Joe public service announcements.  Yes that deep.  What if you can't pass in a mock through the constructor??  What if that helper class is being newed (Yes that's a f--king word on this site) up in something like an attribute?  What if your hair were to spontaneously catch on fire?    Well you are back in the world of hurt my friend, except the hair thing might be an improvement.  For the other two, there is something that can help and it's name is Castle.</p>
<p>What is Castle?  Well besides a word, it's a collection of lots of stuff that helps with anything from mocking to tooth aches, but for this example we only need something that allows instantiation from a config file.</p>
<p>Now you might ask, "How can I be awesome like this site?" to which I answer, "You can't."  Defeated you now turn your eyes back to the dilema and ask, "Config file?  Instantiate?  What will that do for me?"</p>
<p>Imagine this if you will... and I know this kind of thinking hurts you but just hang in there...  Suppose you have a factory method that creates a instance for you.  Something like this:</p>
<pre><span style="color: #0000ff;">class</span> SomeClass
{
  ....
  <span style="color: #0000ff;">public</span> SomeClass()
  {
    someHelperClass = <span style="color: #0000ff;">new</span> <span style="color: #008080;">ObjectFactory</span>().Create&lt;<span style="color: #008080;">IHelperClass</span>&gt;();
  }
  ...
}</pre>
<p>BUT HOW DO IT CREATE THEM OBJECT FROM INTERFACE?  Good question, though horribly asked.</p>
<p>Now it might seem odd since I am using a factory to create a helper but I haven't shown you how the factory finds what to create.  What if I told you there's a way that it would simple look to a config file and know the type to create?  What if I told you that in your test project the factory would create MockHelperClass but in the ui project it creates a HelperClass like before?  You might think it's magic.  You might think Over the Top is the best movie of all time.  You would be wrong on both accounts.</p>
<p>Now the answer is <a href="http://byatool.com/Hosted/LiveDemos/CastleConfigTest.zip">here</a> if you don't feel like reading the rest, and I can't really blame you since I stopped reading after the first paragraph.  However, if you actually want to see some of the magic in writing, mush on.</p>
<p>First thing you need are four dlls are Castle.Core, Castle.DynamicProxy, Castle.MicroKernel, Castle.Windsor, and Castle.ImSorryButThePrincessIsInAnother. (THERE ARE FIVE DLLS) Ok so one of those is a lie, but I'll leave it up to you to figure it out.  You could use <a href="http://byatool.com/Hosted/LiveDemos/CastleConfigTest.zip">my example</a> to get them or go to <a href="http://www.castleproject.org/container/">here</a> and try to figure out where they are.  Course you could also spin around in a chair for five minutes because that would be about as brilliant as not just using my easy to find example.  Either way, you need them.</p>
<p>Next the example needs an interface.  Why an interface? Because it's simple.  Could I do this with a class?  Far as I know as long as it's not sealed and the concrete object inherits it.  However for this example, ITS A MOOT POINT BECAUSE I'M USING AN INTERFACE.</p>
<pre><span style="color: #0000ff;">namespace</span> CastleConfigTest.Interface
{
  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">interface</span> IBaseClassA
  {
    <span style="color: #008080;">String</span> ClassName();
  }
}</pre>
<p>Wow, beautiful.  If you're getting teary over that, you're weird but I appreciate the passion.  Now what else I need is a concrete class that implements said interface.</p>
<pre><span style="color: #0000ff;">namespace</span> CastleConfigTest.Class
{
  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">ChildClassA</span> : <span style="color: #008080;">IBaseClassA</span>
  {
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> ClassName()
    {
      <span style="color: #0000ff;">return</span> <span style="color: #800000;">"ChildClassA"</span>;
    }
  }
}</pre>
<p>Good golly Miss Molly, that's fantastic.  Now what does this all mean?  It means that somehow using a config I will magically turn IBaseClassA into ChildClassA.  Now for the hell of it, and for the ease of it, I have a test too.</p>
<pre>    [<span style="color: #008080;">TestMethod</span>]
    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> Create_ClassA()
    {
      <span style="color: #0000ff;">var</span> test = <span style="color: #0000ff;">new</span> <span style="color: #008080;">ObjectFactory</span>().Create();
      <span style="color: #008080;">Assert</span>.IsTrue(test.ClassName().Equals(<span style="color: #800000;">"ChildClassA"</span>));
    }</pre>
<p>Ok so wait, what's this ObjectFactory?  It's a class I've created that uses an object (WindsorContainer) that uses a config file to pull in specified types into a collection.  Now I could get into that class, but I'd rather do the config file real fast.  It's name?  Castle.config.  AMAZING</p>
<pre>&lt;<span style="color: #800000;">configuration</span>&gt;
  &lt;<span style="color: #800000;">components</span>&gt;
    &lt;<span style="color: #800000;">component</span> <span style="color: #0000ff;">id=</span><span style="color: #ff0000;">"childClassA"</span>
     <span style="color: #0000ff;">service=</span><span style="color: #ff0000;">"CastleConfigTest.Interface.IBaseClassA, CastleConfigTest"</span>
     <span style="color: #0000ff;">type=</span><span style="color: #ff0000;">"CastleConfigTest.Class.ChildClassA, CastleConfigTest"</span>&gt;
    &lt;/<span style="color: #800000;">component</span>&gt;
  &lt;/<span style="color: #800000;">components</span>&gt;
&lt;/configuration&gt;</pre>
<p>So what does that all mean?  Really nothing complicated.  'service' says, "Look for this" and 'type' says "Replace with this". (No it doesn't literally say that in the config file so stop looking)  What's the point of that?  Simple, for every project you can have a separate Castle.config with the same 'service' value but a different 'type' value meaning that at run time you can replace the IBaseClassA with any class that implements IBaseClassA.  Say in the test project you have a config:</p>
<pre>...
     <span style="color: #0000ff;">service=</span><span style="color: #ff0000;">"CastleConfigTest.Interface.IBaseClassA, CastleConfigTest"</span>
     <span style="color: #0000ff;">type=</span><span style="color: #ff0000;">"CastleConfigTest.Class.<span style="text-decoration: underline;"><em><strong>MockClassA</strong></em></span>, CastleConfigTest"</span>&gt;
...</pre>
<p>Now anytime IBaseClassA is called upon, MockClassA is almost instantly called in it's place.  Kind of like a stunt man in any action movie involving Bill Nighy.</p>
<p>Now one thing of special note, and by special I mean far from it, it helps if you set the config to Copy Always so that you know where the file is when the project is built.  You don't have to do that if you don't want to, just like you don't have to take showers.  It's just makes life easier for everyone.</p>
<p>Seems all great and good, but slight issue...  What's ObjectFactory?  Well, here it is:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">ObjectFactory</span>
  {
    <span style="color: #008000;">//Tell it where the config file is.  Yes this is hardcoded but get over it.  You</span>
    <span style="color: #008000;">//  can change that if you like.</span>
    <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">const</span> <span style="color: #008080;">String</span> fileLocation = @"C:\Development\CastleConfigTest\CastleConfigTest\bin\Debug\";

    <span style="color: #008000;">//This is the config file name.  I really hope you could tell that already.</span>
    <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">const</span> <span style="color: #008080;">String</span> fileName = <span style="color: #800000;">"Castle.config"</span>;
    <span style="color: #0000ff;">private</span> <span style="color: #008080;">WindsorContainer</span> container;

    <span style="color: #0000ff;">public</span> ObjectFactory()
    {
      <span style="color: #008000;">//Create a new container with the config file.</span>
      container = <span style="color: #0000ff;">new</span> <span style="color: #008080;">WindsorContainer</span>(<span style="color: #0000ff;">new</span> XmlInterpreter(fileLocation + fileName));

      <span style="color: #008000;">//Get all types in the container that implement IBaseClassA and make them</span>
      <span style="color: #008000;">// transient... ie only when needed.  If you don't believe me, go <a href="http://api.castleproject.org/html/T_Castle_Core_LifestyleType.htm">here</a> and apologize later.
      // I'm sure you're used to that anyhow.</span>
      <span style="color: #0000ff;">var</span> controllerTypes =
        Assembly
          .GetExecutingAssembly()
          .GetTypes()
          .Where(item =&gt; typeof(<span style="color: #008080;">IBaseClassA</span>).IsAssignableFrom(item));
      <span style="color: #008000;">//And this I stole from someone but I can't remmeber who</span>
      <span style="color: #008000;">//  I don't really care though because chances are it was someone important</span>
      <span style="color: #008000;">//  and there's as much of a chance of someone important reading this as</span>
      <span style="color: #008000;">//  me sprouting a second me and doubling the worthless content on this site.</span>
      <span style="color: #008000;">//  After all, double of infinite is just the same damn thing.</span>
      <span style="color: #008000;">//  Not to mention this world isn't ready for that much pretty.</span>
      controllerTypes = <span style="color: #0000ff;">from</span> t <span style="color: #0000ff;">in</span> Assembly.GetExecutingAssembly().GetTypes()
                            <span style="color: #0000ff;">where</span> typeof(IBaseClassA).IsAssignableFrom(t)
                            <span style="color: #0000ff;">select</span> t;

      <span style="color: #0000ff;">foreach </span>(<span style="color: #008080;">Type</span> type <span style="color: #0000ff;">in</span> controllerTypes)
        container.AddComponentWithLifestyle(type.FullName, type, LifestyleType.Transient);
    }

    <span style="color: #008000;">//And then this is the wondrous and obviously complex method used to do the creating.</span>
    <span style="color: #0000ff;">public</span> T Create() <span style="color: #0000ff;">where</span> T : class
    {
      <span style="color: #0000ff;">return</span> (T)container.Resolve(typeof(T));
    }
  }</pre>
<p>Wait what?  That's it?  Well for the most part.  Only thing that was difficult was the ObjectFactory, but that's so easy even a... well you know the rest.  And why wouldn't you?  That f--ing phrase has burned into your skull for the last 5 years and that's a conservative guess.  And yes, there is room for improvement so save your nerd rage typing.  After all, you have plenty of room for improvement but you won't see me fist typing a list of things with disgruntled comic fan boy like intensity.</p>
<p>Anyways, that's the short of it and since I gave you an example somewhere crazy hidden in this mess I call a post, you should be able to pick it up from there.  If you can't, consult your physician because you most likely suffer from acute brain loss.  Don't worry though, you can still have a long career as a PowerPoint instructor.</p>
<p>And if you haven't figured it out yet, this post is my April Fools joke.  Actual useful content on this site.  Don't get used to it.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/how-to-use-a-factory-method-with-castle-windsorcontainer/" title="How to Use a Factory Method With Castle / WindsorContainer">How to Use a Factory Method With Castle / WindsorContainer</a></li><li><a href="http://byatool.com/lessons/dictionary-index-lookup-vs-contains-key-vs-list-contains-vs-linq-speed-testtexas-tornado-match/" title="Dictionary Index Lookup Vs Contains Key Vs List Contains Vs Linq&#8230; Speed Test/Texas Tornado Match">Dictionary Index Lookup Vs Contains Key Vs List Contains Vs Linq&#8230; Speed Test/Texas Tornado Match</a></li><li><a href="http://byatool.com/general-coding/filling-a-private-field-on-a-base-class/" title="Filling a Private Field on a Base Class Using Reflection">Filling a Private Field on a Base Class Using Reflection</a></li><li><a href="http://byatool.com/test/mulitple-constraint-generics-and-test-base-classes/" title="Mulitple Constraint Generics and Test Base Classes">Mulitple Constraint Generics and Test Base Classes</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/castle-rhino-mocking-and-possibly-you/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Child IFrame Page Interacting with Parent Page&#8230; Yeah I went there.</title>
		<link>http://byatool.com/lessons/child-iframe-page-interacting-with-parent-page-yeah-i-went-there/</link>
		<comments>http://byatool.com/lessons/child-iframe-page-interacting-with-parent-page-yeah-i-went-there/#comments</comments>
		<pubDate>Mon, 08 Mar 2010 20:07:54 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[iframe]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1241</guid>
		<description><![CDATA[Example here. File this under "Why?" but I wanted to see if a child could talk to a parent and then receive information back from the parent to update itself with. As usual, my lack of intelligent wording probably has you scratching your head... if you do that. Personally I don't get that expression as [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.byatool.com/Hosted/LiveDemos/JavascriptIframeDelegate/Parent.htm">Example here.</a></p>
<p>File this under "Why?" but I wanted to see if a child could talk to a parent and then receive information back from the parent to update itself with.  As usual, my lack of intelligent wording probably has you scratching your head... if you do that.  Personally I don't get that expression as when I'm confused I more than likely will grab a jar of peanut butter and start lathering up with it, but to each his own.</p>
<p>So here's the idea, and this post is only the start.</p>
<p>You have a parent page, Parent.htm, with an iframe and you want the parent to do something and alert the child that something happened.  For now, it's actually really simple.</p>
<p>On the parent I have a method:</p>
<pre>  <span style="color: #0000ff;">function</span> callMethod(text, methodDelgate) {
    <span style="color: #0000ff;">if</span> (methodDelgate != <span style="color: #0000ff;">null</span>) {
      methodDelgate(text);
    }
  }
</pre>
<p>And this simple markup:</p>
<pre>  &lt;iframe id="myFrame" src="Child.htm"&gt;&lt;/iframe&gt;
</pre>
<p>Wow huh?  Well on the child I have this:</p>
<pre>  <span style="color: #0000ff;">function</span> callParent(text) {
    <span style="color: #0000ff;">if</span> (top.callMethod != <span style="color: #0000ff;">null</span>) {
	  top.callMethod(text, changeText);
    }
  }
</pre>
<p>This is easy.  If the parent has the method, send the text through and a method to call when finished.  What is this method?  Well its:</p>
<pre>  <span style="color: #0000ff;">function </span>changeText(text) {
    jQuery(<span style="color: #800000;">'#returnText'</span>).text(text);
  }
</pre>
<p>Which simply sets the text on some div to show it actually worked.</p>
<p>What happens when I click a button that calls callParent?  It talks to the parent, the parent calls the passed in method, and the child updates itself.</p>
<p>Not sure this is rocket science, but there will be more on it as I add in the idea of a dynamically created pop up on the parent being used by the child.  Until then, try not to be yourself.  You embarrass your mother.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/jquery-validation-how-to-use-to-get-rid-of-even-the-toughest-stains/" title="jQuery Validation &#8211; How to Use to Get Rid Of Even The Toughest Stains">jQuery Validation &#8211; How to Use to Get Rid Of Even The Toughest Stains</a></li><li><a href="http://byatool.com/ui/556/" title="jQuery: Add a Pop Up Div to a Link Dynamically">jQuery: Add a Pop Up Div to a Link Dynamically</a></li><li><a href="http://byatool.com/ui/jquery-position-absolute-and-how-to-make-it-all-work/" title="JQuery, Position : Absolute, and How to Make It All Work">JQuery, Position : Absolute, and How to Make It All Work</a></li><li><a href="http://byatool.com/writing/byatool-com-gets-a-shiny-new-tool/" title="ByATool.com gets a shiny new tool!">ByATool.com gets a shiny new tool!</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/child-iframe-page-interacting-with-parent-page-yeah-i-went-there/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Get the jQuery DatePicker to Work With jQuery Modal Dialog</title>
		<link>http://byatool.com/lessons/get-the-jquery-datepicker-to-work-with-jquery-modal-dialog/</link>
		<comments>http://byatool.com/lessons/get-the-jquery-datepicker-to-work-with-jquery-modal-dialog/#comments</comments>
		<pubDate>Wed, 27 Jan 2010 19:35:41 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1231</guid>
		<description><![CDATA[Being that I am the man, I thought I would share this little thingy with you because... well I'm the man. So here's the issue:  You have a date picker, a modal dialog, and you can't see the calendar when you click on the icon and/or textbox. First thought, 'WHY DOES THIS HAPPEN TO ME???!?!' [...]]]></description>
			<content:encoded><![CDATA[<p>Being that I am the man, I thought I would share this little thingy with you because... well I'm the man.</p>
<p>So here's the issue:  You have a date picker, a modal dialog, and you can't see the calendar when you click on the icon and/or textbox.  First thought, 'WHY DOES THIS HAPPEN TO ME???!?!'  Second though, 'I wonder if that tool knows how to get past this.'  Good news!  I do.  Turns out it has to do with the z-index.  The modal dialog by default has a z-index of 1000ish when showing. (And any modal dialog "above that" will increase it's z-index to match.)  If the calendar isn't higher than that, no go.  </p>
<p>Now you might be using the jquery styles from <a href="http://jqueryui.com/themeroller/"> the jquery site</a> and might be putting your through your keyboard thinking about having to deal with that mess.  However, it's actually a simple fix in there... there being the ui.datepicker.css file.</p>
<pre>
  .ui-datepicker { width: 17em; padding: .2em .2em 0;<strong> z-index:9000</strong>; }
</pre>
<p>And there you have it.  Now the calendar will show up in front of anything lower than 9000, and as everyone knows: Anything over 9000 is impossible.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/writing/byatool-com-gets-a-shiny-new-tool/" title="ByATool.com gets a shiny new tool!">ByATool.com gets a shiny new tool!</a></li><li><a href="http://byatool.com/lessons/child-iframe-page-interacting-with-parent-page-yeah-i-went-there/" title="Child IFrame Page Interacting with Parent Page&#8230; Yeah I went there.">Child IFrame Page Interacting with Parent Page&#8230; Yeah I went there.</a></li><li><a href="http://byatool.com/ui/jquery-modal-dialog-hide-that-stupid-x-button-windows-close-button/" title="jQuery Modal Dialog : Hide That Stupid X Button / Windows Close Button">jQuery Modal Dialog : Hide That Stupid X Button / Windows Close Button</a></li><li><a href="http://byatool.com/ui/jquery-check-all-checkboxes-toggle-method-thingy/" title="jQuery &#8211; Check All Checkboxes Toggle Method Thingy">jQuery &#8211; Check All Checkboxes Toggle Method Thingy</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/get-the-jquery-datepicker-to-work-with-jquery-modal-dialog/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery Validation: Adding Errors to the Error Containter&#8230; With Love!</title>
		<link>http://byatool.com/lessons/jquery-validation-adding-errors-to-the-error-containter-with-love/</link>
		<comments>http://byatool.com/lessons/jquery-validation-adding-errors-to-the-error-containter-with-love/#comments</comments>
		<pubDate>Tue, 22 Dec 2009 21:28:49 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1178</guid>
		<description><![CDATA[Hello again, my wonderful audience, I have something great and fun planned for this post. If you read this post you might have been left wondering how to add custom messages to the error holder. It's ok if you did, there's nothing wrong with being confused all the time. It's what makes you so adorable. [...]]]></description>
			<content:encoded><![CDATA[<pre><img src="http://www.iheartvector.com/wp-content/vector/hearts.png" alt="" /></pre>
<p><span style="background-color: #FFFFFF;" title="Please send help, the Board of Directors is forcing me to be nice!">Hello again, my wonderful audience, I have something great and fun planned for this post. If you read <a href="http://byatool.com/lessons/jquery-validation-how-to-use-to-get-rid-of-even-the-toughest-stains/">this post</a> you might have been left wondering how to add custom messages to the error holder. It's ok if you did, there's nothing wrong with being confused all the time. It's what makes you so adorable.</span></p>
<p><span style="background-color: #FFFFFF;" title="I really don't mean the last part.">Say you have a form like this, and if you don't I cry endlessly for your loss. My heart goes out to you.</span></p>
<pre>&lt;<span style="color: #800000;">form</span> <span style="color: #0000ff;">id=</span><span style="color: #ff0000;">"ILoveEverythingForm"</span>&gt;
    &lt;<span style="color: #800000;">div</span> <span style="color: #0000ff;">id=</span><span style="color: #ff0000;">"NotSoNiceThingsDiv"</span> <span style="color: #0000ff;">style</span><span style="color: #0000ff;">=</span><span style="color: #ff0000;">"display:none;"</span>&gt;&lt;/<span style="color: #800000;">div</span>&gt;
	...
&lt;/<span style="color: #800000;">form</span>&gt;</pre>
<p><span style="background-color: #FFFFFF;" title="This is the cheesiest piece of...">As you can see, there is an error div to hold mean things that we have to print out because the system just doesn't like the user. As we both know, the user can't help but be dumb. It's just in his cute little nature. And that nature is just so darned cute.</span></p>
<p><span style="background-color: #FFFFFF;" title="Uhg, this really sucks.">Now let's assume that you have something that sent back a bunch of mean messages when you tried to validate server side after all the cute client side validation was done. You might have a method to take in those jerk face messages. How do you display them in the bad place?</span></p>
<pre>  <span style="color: #0000ff;">function</span> updateErrorDivContentWithLove(messages)
  {
    <span style="color: #0000ff;">if</span>(messages.length &gt; 0)
    {
      <span style="color: #0000ff;">var</span> validator = jQuery(<span style="color: #800000;">'#ILoveEverythingForm'</span>).validate();

      <span style="color: #0000ff;">for</span>(<span style="color: #0000ff;">var</span> loopCounter = 0; loopCounter &lt; messages.length; loopCounter ++)
      {
        validator.showErrors
        (
          {
             <span style="color: #800000;">'SomeWonderfulElementName'</span> : messages[loopCounter].Message
          }
        );
      }
    }
  }</pre>
<p><span style="background-color: #FFFFFF;" title="I wish I could stab my eyes right now...">Awwww kitties!</span></p>
<pre>  <img src="http://www.dailypets.co.uk/wp-content/uploads/2007/06/kittens-cups.jpg" alt="" /></pre>
<p><span style="background-color: #FFFFFF;" title="I am losing mad rep on this.">Only thing that may seem odd (And if it doesn't, don't worry you are still very special and loved in this world):</span></p>
<pre>  'SomeElementName' : messages[loopCounter].Message</pre>
<p><span style="background-color: #FFFFFF;" title="Oh for f--ks sake...">Not sure what element really needs to be here, basically anything in the form with a name tag. So if you're good like I know you are, you have at least one element in that little old form with a name property set. I would say that this is pretty useless in situations where all the errors are shown in one div, as opposed to right next to the element, but that would be mean and I don't do that.</span></p>
<p><span style="background-color: #FFFFFF;" title="I swear I'm not really a nice person, please believe me.">Now I know you wanted something special from this post so I just wanted you to know that even though most of the world considers you hideous, I say you should be proud of being hideous because it makes you who you are. A unique miracle that only really has issues with dogs and small children. Embrace yourself in whatever way you take that!</span></p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/jquery-validation-how-to-use-to-get-rid-of-even-the-toughest-stains/" title="jQuery Validation &#8211; How to Use to Get Rid Of Even The Toughest Stains">jQuery Validation &#8211; How to Use to Get Rid Of Even The Toughest Stains</a></li><li><a href="http://byatool.com/writing/byatool-com-gets-a-shiny-new-tool/" title="ByATool.com gets a shiny new tool!">ByATool.com gets a shiny new tool!</a></li><li><a href="http://byatool.com/lessons/child-iframe-page-interacting-with-parent-page-yeah-i-went-there/" title="Child IFrame Page Interacting with Parent Page&#8230; Yeah I went there.">Child IFrame Page Interacting with Parent Page&#8230; Yeah I went there.</a></li><li><a href="http://byatool.com/lessons/get-the-jquery-datepicker-to-work-with-jquery-modal-dialog/" title="Get the jQuery DatePicker to Work With jQuery Modal Dialog">Get the jQuery DatePicker to Work With jQuery Modal Dialog</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/jquery-validation-adding-errors-to-the-error-containter-with-love/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, "What are Data Annotations?". Well I'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, "What are Data Annotations?".  Well I'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's what you'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...) 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--king clue.  That'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't use the one above.  Whatever.</p></blockquote>
<p>Now you might want to actually pass the errors back, and why wouldn't you?  You'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're an idiot who just learned about this.  For cool people like me, it's old news.</p>
<p>What's the point this?  If "this" is data annotations:  Well it helps move some of the validation off the controller if you are looking for a more "Fat model, skinny controller" design which I'm told is a good idea.  This also gets rid of all the validation methods and saves time because of it.</p>
<p>If "this" is your life?  I have no idea.  But if you're to the point that you're asking me about the meaning of your life, you are in some serious trouble.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/writing/byatool-com-gets-a-shiny-new-tool/" title="ByATool.com gets a shiny new tool!">ByATool.com gets a shiny new tool!</a></li><li><a href="http://byatool.com/lessons/spark-view-engine-asp-net-mvc-and-you/" title="Spark View Engine, ASP.Net MVC, and You">Spark View Engine, ASP.Net MVC, and You</a></li><li><a href="http://byatool.com/mvc/custom-data-annotations-with-mvc-how-to-check-multiple-properties-at-one-time/" title="Custom Data Annotations With MVC: How to Check Multiple Properties at One Time">Custom Data Annotations With MVC: How to Check Multiple Properties at One Time</a></li><li><a href="http://byatool.com/add-on/random-add-on-automapper/" title="Random Add-On &#8211; Automapper">Random Add-On &#8211; Automapper</a></li></ul>]]></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>jQuery Validation &#8211; How to Use to Get Rid Of Even The Toughest Stains</title>
		<link>http://byatool.com/lessons/jquery-validation-how-to-use-to-get-rid-of-even-the-toughest-stains/</link>
		<comments>http://byatool.com/lessons/jquery-validation-how-to-use-to-get-rid-of-even-the-toughest-stains/#comments</comments>
		<pubDate>Sun, 06 Dec 2009 18:17:29 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1092</guid>
		<description><![CDATA[So you want to use jQuery validation, huh? What is it? Something that was added to the holy jquery site and is an easy way to validate input from users. Now this should in no way take over for server side validation, but it helps to at least catch a few things without having to [...]]]></description>
			<content:encoded><![CDATA[<p>So you want to use jQuery validation, huh?</p>
<p>What is it?  Something that was added to the<a href="http://jquery.com/"> <strong>holy jquery site</strong></a> and is an easy way to validate input from users. Now this should in no way take over for server side validation, but it helps to at least catch a few things without having to send anything to the server.  So how do ya do it?</p>
<p>Well to start, you need some files:</p>
<p><a href="http://docs.jquery.com/Release:jQuery_1.3.2">jquery-1.3.2.js</a> and <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/">jquery.validate.js</a>.</p>
<p>Now oddly enough the validation file isn't hosted on the <a href="http://jquery.com/"> <strong>holy jquery site</strong></a> but <a href="http://docs.jquery.com/Plugins/Validation">how to use it is</a>.</p>
<p>Ok now you have the files, what's next?  Well you need form, and <a href="http://byatool.com/hosted/LiveDemos/jQueryValidation/SimpleRequired.html">I can do that for you.</a></p>
<p>So basically it's a simple form with one input that is required.</p>
<pre>jQuery(document).ready
    (
      <span style="color: #0000ff;">function</span>()
      {
        jQuery(<span style="color: #800000;">"#PrimaryForm"</span>).validate
        (
          {
            errorLabelContainer: <span style="color: #800000;">"#ErrorDiv"</span>,
            wrapper: <span style="color: #800000;">"div"</span>,
            rules:
            {
              FirstName :
              {
                required : <span style="color: #0000ff;">true</span>
              }
            },
            messages:
            {
              FirstName:
              {
                required : <span style="color: #800000;">'First Name is required.'</span>
              }
            },
            onfocusout : false,
            onkeyup: false,
            submitHandler: <span style="color: #0000ff;">function</span>(label)
            {
              postSubmit();
            }
          }
        );
      }</pre>
<pre>jQuery(<span style="color: #800000;">"#PrimaryForm"</span>).validate</pre>
<p>Real simple, just setting the validator to the primary form on the page.</p>
<pre> errorLabelContainer: <span style="color: #800000;">"#ErrorDiv"</span>,</pre>
<p>This sets the errors to show up in the ErrorDiv.  Now this is optional, as you can have it show the errors next to the FirstName text box but personally I think that looks horrible.  Setting up the ErrorDiv puts all the errors in one central location and allows for styling the actual div.</p>
<pre> rules:
 {
    FirstName :
    {
      required : <span style="color: #0000ff;">true</span>
    }
  },</pre>
<p>This matches an element with the id of FirstName to the required rule, meaning that FirstName is required.  Rocket science.</p>
<pre>  messages:
  {
    FirstName:
    {
       required : <span style="color: #800000;">'First Name is required.'</span>
    }
  },</pre>
<p>If you can't figure this out, I hear circus is hiring for the "World's Dumbest Person".  You'll fit in with Jub Jub the Dog Boy.</p>
<pre>  onfocusout : <span style="color: #0000ff;">false</span>,
  onkeyup: <span style="color: #0000ff;">false</span>,</pre>
<p>Basically this prevents the validation when leaving the textbox or on every key press.  This is just another preference.</p>
<pre>  submitHandler: <span style="color: #0000ff;">function</span>(label)
  {
    postSubmit();
  }</pre>
<p>If the submit is successful, call this method.</p>
<p><strong>But... BUT WHAT IF IT'S AN EMAIL?!??! WHAT WILL I DO???!?!?</strong></p>
<p>Well for one, stop being such a child.  <a href="http://byatool.com/hosted/LiveDemos/jQueryValidation/EmailRequired.html">And two, look here.</a></p>
<p>Some what different, as you can see it's now email and there is one extra requirement in the rules:</p>
<pre>  rules:
  {
    EmailAddress :
    {
      email : <span style="color: #0000ff;">true</span>,
      required : <span style="color: #0000ff;">true</span>
    }
  },
  messages:
  {
    EmailAddress:
    {
      required : <span style="color: #800000;">'Yo, email fool.'</span>,
      email : <span style="color: #800000;">'So not an email address.'</span>
    },
  },</pre>
<p>See?  It has nice built in rule for email.  Simple.</p>
<p><strong>BUT WHAT IF I NEED A REGULAR EXPRESSION?!??! WHAT WILL I DO???!?!?</strong></p>
<p>I swear if you don't stop that, I'm turning this post around and going home.</p>
<p><a href="http://byatool.com/hosted/LiveDemos/jQueryValidation/ZipCodeRequired.html">Fine here it is.</a></p>
<pre>  jQuery.validator.addMethod
  (
    <span style="color: #800000;">"isZipCode"</span>,
    <span style="color: #0000ff;">function</span>(value, element)
    {
      <span style="color: #0000ff;">return</span> value.match(<span style="color: #0000ff;">new</span> RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/));
    }
  );</pre>
<p>Just have to create a method and "add it" to the validator itself. And then there's the use:</p>
<pre>  rules:
  {
    ZipCode :
    {
      required : <span style="color: #0000ff;">true</span>,
      isZipCode : <span style="color: #0000ff;">true</span>
    }
  },
  messages:
  {
    ZipCode:
    {
      required : <span style="color: #800000;">'For the love of me, enter a zip code!.'</span>,
      isZipCode : <span style="color: #800000;">'Serioulsy?  Do you know what a zip code is?'</span>
    },
  },</pre>
<p>Woo hoo right?</p>
<p>Don't do it... Don't you yell.</p>
<p><strong>But what if one input depends on another?</strong></p>
<p>Much better.  Well that's not as hard as it may seem and <a href="http://byatool.com/hosted/LiveDemos/jQueryValidation/TwoRequired.html">here's the example</a>.</p>
<pre>  rules:
  {
    InputB :
    {
      required :
      {
        depends : <span style="color: #0000ff;">function</span>(element) { <span style="color: #0000ff;">return</span> jQuery(<span style="color: #800000;">'#InputA'</span>).val() != <span style="color: #800000;">""</span> }
      }
    }
  },</pre>
<p>As you can see, you can change how the required method works by adding in a depends handler.  Works out pretty well.</p>
<p>Yes I will show you how to make sure two inputs match.  <a href="http://byatool.com/hosted/LiveDemos/jQueryValidation/EqualTo.html">I swear you ask for a lot.</a></p>
<pre>  rules:
  {
    Password :
    {
      equalTo : <span style="color: #800000;">"#ConfirmPassword"
</span>    },
  },</pre>
<p>Couldn't be easier unless I wrote it out for you.  Wait, I did.</p>
<p>So here you've either learned a bit about jQuery validation or have just spent the last few minutes drooling uncontrollably. Either way, I'm done with this post and you're left to do whatever it is you do, you sick f---.</p>
<p>Side note:  I haven't actually been to <a href="http://www.htmlgoodies.com">Htmlgoodies</a> since eh college?  but wow did that place sell out.  How fitting that an introduction to html page now looks like it was designed by someone just starting out... in the 90s.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/child-iframe-page-interacting-with-parent-page-yeah-i-went-there/" title="Child IFrame Page Interacting with Parent Page&#8230; Yeah I went there.">Child IFrame Page Interacting with Parent Page&#8230; Yeah I went there.</a></li><li><a href="http://byatool.com/lessons/jquery-validation-adding-errors-to-the-error-containter-with-love/" title="jQuery Validation: Adding Errors to the Error Containter&#8230; With Love!">jQuery Validation: Adding Errors to the Error Containter&#8230; With Love!</a></li><li><a href="http://byatool.com/ui/556/" title="jQuery: Add a Pop Up Div to a Link Dynamically">jQuery: Add a Pop Up Div to a Link Dynamically</a></li><li><a href="http://byatool.com/ui/jquery-position-absolute-and-how-to-make-it-all-work/" title="JQuery, Position : Absolute, and How to Make It All Work">JQuery, Position : Absolute, and How to Make It All Work</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/jquery-validation-how-to-use-to-get-rid-of-even-the-toughest-stains/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</title>
		<link>http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/</link>
		<comments>http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/#comments</comments>
		<pubDate>Wed, 28 Oct 2009 15:41:52 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[.Net 4.0]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1043</guid>
		<description><![CDATA[So something I've seen but just have now conquered is the whole complex type thing in Entity Framework. Not only that, but with the cool new Persistence Ignorance thing all the kids are talking about. (And boy am I glad there's a new kind of ignorance on this site now.) You might ask: What's a [...]]]></description>
			<content:encoded><![CDATA[<p>So something I've seen but just have now conquered is the whole complex type thing in Entity Framework.  Not only that, but with the cool new Persistence Ignorance thing all the kids are talking about.  (And boy am I glad there's a new kind of ignorance on this site now.)  You might ask:  What's a complex type?  Course you might ask:  Why is it so hard to make a decent movie about huge robots that transform into cool vehicles and have really big guns?  Well I can answer the first question.</p>
<p>Complex types, in the simple minded way I see them, are a way to split information retrieved from a table into a object within an object.  Confused yet?  I hope so.</p>
<p>Say you have a User table and on that table you have the typical user information including a bunch of stuff like Name, Sex, City, State, and Zip.  Now you could set up the user class to look like this:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">User</span>
  {
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> Name { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> City { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> State { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> Zip { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }</pre>
<p>Nothing wrong with that, but what if you have an Address class:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">Address</span>
  {
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> City { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> State { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> Zip { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }</pre>
<p>That you wanted to map the values from the User table to the User class to so that the User class looked more like this:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">User</span>
  {
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> Name { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Address</span> Address { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }</pre>
<p>Well I'm here to tell you that you can and I have plenty of pictures to back it up.</p>
<p>Keeping with the design <a href="http://byatool.com/index.php/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/">from this guy</a>, I am going to add a new class called AdDimension which will have Height and Width, effectively replacing the Height and Width properties on the Ad class.</p>
<p>RECAP - Old class diagram:</p>
<pre><img class="alignnone size-full wp-image-1054" title="AddAdtype" src="http://byatool.com/wp-content/uploads/2009/10/AddAdtype.png" alt="AddAdtype" width="421" height="528" /></pre>
<p>So the first thing I have to do is is create the complex type in the Model Browser.  That's pretty easy.  There's a section called "Complex Types" and you just add one.</p>
<pre><img class="alignnone size-full wp-image-1055" title="ComplexTypeAdd" src="http://byatool.com/wp-content/uploads/2009/10/ComplexTypeAdd.png" alt="ComplexTypeAdd" width="527" height="364" /></pre>
<p>See, there's a picture.  Next step is adding properties to the newly created complex type.</p>
<pre><img class="alignnone size-full wp-image-1062" title="ComplexTypePropertyAdd" src="http://byatool.com/wp-content/uploads/2009/10/ComplexTypePropertyAdd3.png" alt="ComplexTypePropertyAdd" width="537" height="494" /></pre>
<p>Another picture!  Ok so now you've created on, big deal.  Now what?  Well you have to add a complex type property to the main class, Ad in this case.</p>
<pre><img class="alignnone size-full wp-image-1065" title="ComplexTypeAddToEntity" src="http://byatool.com/wp-content/uploads/2009/10/ComplexTypeAddToEntity1.png" alt="ComplexTypeAddToEntity" width="643" height="525" /></pre>
<p>Now if you have more than one complex type, you might have to set the property type to the correct one.  Just right click the complex property and click on properties:</p>
<pre><img class="alignnone size-full wp-image-1063" title="ComplexTypePropertyProperties" src="http://byatool.com/wp-content/uploads/2009/10/ComplexTypePropertyProperties.png" alt="ComplexTypePropertyProperties" width="307" height="268" /></pre>
<p>Now, you'll have to adjust the mapping for the entity itself.  So click on the object and bring up mapping properties.  From there, select the correct mapping for the correct column.  In this example it's width and as you can see in the drop down there is a AdDimension.Width property to set it to.  Cool huh?</p>
<pre><img class="alignnone size-full wp-image-1059" title="ComplexTypeSetMapping" src="http://byatool.com/wp-content/uploads/2009/10/ComplexTypeSetMapping.png" alt="ComplexTypeSetMapping" width="800" height="195" /></pre>
<p>And that's it for the object model.  Next you have to add the AdDimension class and add a property to the Ad class.</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">AdDimension</span>
  {
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int32</span> Height { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int32</span> Width { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }</pre>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">Ad</span>
  {
    ...
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">AdDimension</span> <span style="color: #000000;">AdDimension</span> { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    ...
  }</pre>
<p>And then how do you set it?</p>
<pre>  someAd.AdDimension = <span style="color: #0000ff;">new</span> <span style="color: #008080;">AdDimension</span>();
  someAd.AdDimension.Height = 10;
  someAd.AdDimension.Width = 10;</pre>
<p>And it can even be used in queries:</p>
<pre>  context.Ads.Where(ad =&gt; ad.Width &gt; 10);</pre>
<p>Now there are things to be aware of.  Complex types can't inherit from other complex types and the property can't be null when saving.  Just be aware of that.</p>
<p>I'm telling you man, this s-- is the s--- man.  It's the s---.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li><li><a href="http://byatool.com/net-issues/entity-framework-linq-to-entities-only-supports-casting-entity-data-model-primitive-types/" title="Entity Framework: LINQ to Entities only supports casting Entity Data Model primitive types">Entity Framework: LINQ to Entities only supports casting Entity Data Model primitive types</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</title>
		<link>http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/</link>
		<comments>http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/#comments</comments>
		<pubDate>Tue, 27 Oct 2009 17:34:08 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[.Net 4.0]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1036</guid>
		<description><![CDATA[So the next step in the New Entity Framework saga was to make a many to one relationship and get it to save. After all, with the last version I had far more issues with many to one than any other kind of relationship. Turns out, the steak is still in tact. Taking the structure [...]]]></description>
			<content:encoded><![CDATA[<p>So the next step in the New Entity Framework saga was to make a many to one relationship and get it to save. After all, with the last version I had far more issues with many to one than any other kind of relationship. Turns out, the steak is still in tact.</p>
<p><a href="http://byatool.com/index.php/lessons/net-4-0-beta-2-entity-framework-how-to-start/">Taking the structure from the last post</a>, I added an AdType. It's very simple. Columns are AdTypeId (Int Primary) and Description (Varchar). I added a AdTypeId column to the Ad table and created a foreign key to the AdType table with it.</p>
<p>Basically Many Ads to One AdType.</p>
<p>Then I did the usual Update Model From Database with the .edmx file. Same old same old. Well this added the AdType class and the relationship:</p>
<pre><img class="alignnone size-full wp-image-1054" title="AddAdtype" src="http://byatool.com/wp-content/uploads/2009/10/AddAdtype.png" alt="AddAdtype" width="421" height="528" /></pre>
<p>So far, so good. Now with this it also means that I need to create the AdType class and add the AdType property to the Ad class along with the AdTypeId property.</p>
<blockquote><p>Side Note:</p>
<p>Far as I can tell, you need the AdTypeId property despite also having the AdType property. Don't forget this.</p></blockquote>
<p>Here's the AdType class:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">AdType
</span>  {
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int32</span> Id { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> Description { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }

    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">virtual</span> <span style="color: #008080;">IList</span>&lt;<span style="color: #008080;">Ad</span>&gt; Ads { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }</pre>
<p>And on the Ad class I had to "Ad" (HARHRHARHR) the AdType property along with the AdTypeId property:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">Ad</span>
  {
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int32</span> Id { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">DateTime</span> CreatedDate { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> Name { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">DateTime</span>? LastUpdated { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int32</span> Height { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int32</span> Width { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }

    <span style="color: #008000;">//Interesting note: Works even if this is private and non virtual</span>
    <span style="color: #0000ff;">private</span> <span style="color: #008080;">Int32</span> AdTypeId { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }

    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">virtual</span> <span style="color: #008080;">AdType</span> AdType { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #008000;">//Note:</span>
    <span style="color: #008000;">//If properties are to be lazy loaded, must be virtual</span>
    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">virtual</span> <span style="color: #008080;">IList</span>&lt;<span style="color: #008080;">Newpaper</span>&gt; Newspapers { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }</pre>
<p>Classes are done. Should be good to go right? WRONG YOU ARE SO F-ING WRONG! Just try this, I dare you:</p>
<pre>   <span style="color: #008080;">Ad</span> ad = <span style="color: #0000ff;">new</span> <span style="color: #008080;">Ad</span>();

   ...
   ad.AdType = someAdType();
   context.Ads.Add(ad);
   context.SaveChanges();</pre>
<p><strong>DUN DUN DUUUUN INSERT statement conflicted with the FOREIGN KEY constraint.</strong></p>
<p>You try it? Idiot. You just got stuffed by a foreign key error. Why? <a href="http://blogs.msdn.com/adonet/archive/2009/06/10/poco-in-the-entity-framework-part-3-change-tracking-with-poco.aspx">Well The Big M has an answer:</a></p>
<blockquote><p>In this example, Customer is a pure POCO type. Unlike with EntityObject or IPOCO based entities, making changes to the entity doesn't automatically keep the state manager in sync because there is no automatic notification between your pure POCO entities and the Entity Framework. Therefore, upon querying the state manager, it thinks that the customer object state is Unchanged even though we have explicitly made a change to one of the properties on the entity.</p></blockquote>
<p>Basically because these objects aren't really being watched by the State Manager, it has no idea anything has changed and should be persisted. Therefore, it has no idea that the AdType property has changed and that the AdTypeId should be updated to reflect this. That's right, it just ignored the AdType property and left the AdTypeId to it's default... 0 (That's a Zero or as the English say, Zed).  How do you get around this? <a href="http://msdn.microsoft.com/en-us/library/system.data.objects.saveoptions(VS.100).aspx">This little option.</a></p>
<pre>  context.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);</pre>
<p>This tells it to persist the changes that it didn't know about.  Now I'm still picking this up as I go so bare with me as I might have the best explanations yet on why things work with the New Entity Framework.  Then again, this is a site by a tool.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li><li><a href="http://byatool.com/net-issues/entity-framework-linq-to-entities-only-supports-casting-entity-data-model-primitive-types/" title="Entity Framework: LINQ to Entities only supports casting Entity Data Model primitive types">Entity Framework: LINQ to Entities only supports casting Entity Data Model primitive types</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</title>
		<link>http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/</link>
		<comments>http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 20:41:19 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[4.0]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1017</guid>
		<description><![CDATA[So I just recently turned my laptop into a 4.0 workstation since it is kind of expendable and I won't feel inclined to nerd rage if it gets tooled. With this step forward, I decided that I probably won't be doing much with the old Entity Framework version since the new one is supposed to [...]]]></description>
			<content:encoded><![CDATA[<p>So I just recently turned my laptop into a 4.0 workstation since it is kind of expendable and I won't feel inclined to nerd rage if it gets tooled. With this step forward, I decided that I probably won't be doing much with the old Entity Framework version since the new one is supposed to be the end all/be all until the next end all/be all version comes out. What does this mean for you? This post could be filled with useful information or f--- all. Just depends on what you care about.</p>
<p>After doing a little reading, and by little I mean as little as humanly possible while still having an idea of what I'm doing, I got the new EF to persist an object. Mind you, it took a bit of patience followed by slamming my head into my desk and then more patience, but I did it.</p>
<p>First off, the actual creating of the edmx file is the same, there's really no difference. You still go through the wizard, you still go through the connection set up, and you still grab the tables you want. No change there.</p>
<p>However, once you have it created, click on the .edmx file in your solution explorer, right click, then click properties. You'll see something like this:</p>
<pre><img class="alignnone size-full wp-image-1021" title="BAT - EntityFramework_RemoveCustomTool" src="http://byatool.com/wp-content/uploads/2009/10/BAT-EntityFramework_RemoveCustomTool.png" alt="BAT - EntityFramework_RemoveCustomTool" width="380" height="355" /></pre>
<p>You can see where there is nothing in the Custom Tool area of properties. That's because I deleted the text. That's the first part of what you need to do. Next is creating the needed classes. For this example I have two, Ad and Newspaper:</p>
<pre><span style="color: #0000ff;">namespace</span> Beta2Test.Data.Entity
{
  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">Ad</span>
  {
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int32</span> Id { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">DateTime</span> CreatedDate { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> Name { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">DateTime</span>? LastUpdated { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int32</span> Height { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int32</span> Width { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }

    <span style="color: #008000;">//Note:</span>
    <span style="color: #008000;">//If properties are to be lazy loaded, must be virtual</span>
    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">virtual</span> <span style="color: #008080;">IList</span>&lt;<span style="color: #008080;">Newspaper</span>&gt; Newspapers { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }
}</pre>
<p>and</p>
<pre><span style="color: #0000ff;">namespace</span> Beta2Test.Data.Entity
{
  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">Newspaper</span>
  {
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int32</span> Id { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int32</span> Circulation { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">DateTime</span> CreatedDate { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">DateTime</span> LastUpdated { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> Name { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }

    <span style="color: #008000;">//Note:
</span>    <span style="color: #008000;">//If properties are to be lazy loaded, must be virtual</span>
    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">virtual</span> <span style="color: #008080;">IList</span>&lt;<span style="color: #008080;">Ad</span>&gt; Ads { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }
}</pre>
<p>Three things you might notice:</p>
<ol>
<li>The classes don't inherit from anything. Yay</li>
<li>The namespace is Beta2Test.Data.Entity. Fact is, I left it there to show that the namespace can now be anything. Yay</li>
<li>Both collection properties are virtual. This is a must when dealing with collections that represent a relationship and you have lazy loading enabled (See below context class). For this, there is a many to many relationship between Ads and Newpapers. The Ads and Newspapers collection represent that. Why do that have to be virtual? Has to do with Entity Framework needing a way to override the properties so it can tell when they are accessed. (Read: Lazy Loading)</li>
<li>There is no fourth thing. You are wrong if you think there is.</li>
</ol>
<p>So far so good, but what about that like whole linking to that persistence layer stuff. You know like them entity objects yo.</p>
<p>Thank you for that poorly worded inquiry, but valid none the less. Remember those entity context classes that it used to generate for you? Well that whole "custom tool" dohickey I removed would have built it for me. However, that's not the path we're going down anymore. It's now time to brave the unknown. We, yes we, will build the context. Yes the context.</p>
<pre><span style="color: #0000ff;">using</span> System.Data.Objects;
<span style="color: #0000ff;">using</span> Beta2Test.Data.Entity;

<span style="color: #0000ff;">namespace</span> Beta2Test.Data
{
  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">Beta2TestContext</span> : <span style="color: #008080;">ObjectContext</span>
  {
    <span style="color: #0000ff;">private</span> <span style="color: #008080;">ObjectSet</span>&lt;<span style="color: #008080;">Ad</span>&gt; _ads;
    <span style="color: #0000ff;">private</span> <span style="color: #008080;">ObjectSet</span>&lt;<span style="color: #008080;">Newspaper</span>&gt; _newspapers;

    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Beta2TestContext</span>() : <span style="color: #0000ff;">base</span>(<span style="color: #800000;">"name=InterviewDemoEntities"</span>, <span style="color: #800000;">"InterviewDemoEntities"</span>)
    {
      _ads = <span style="color: #008080;">CreateObjectSet</span>&lt;<span style="color: #008080;">Ad</span>&gt;();
      _newspapers = <span style="color: #008080;">CreateObjectSet</span>&lt;<span style="color: #008080;">Newspaper</span>&gt;();

      <span style="color: #008000;">//This makes sure the context lazy loads by default</span>
      ContextOptions.LazyLoadingEnabled = <span style="color: #0000ff;">true</span>;
    }

    <span style="color: #008000;">///
</span>    <span style="color: #008000;">/// This is used to set up the "queryable" collection.</span>
    <span style="color: #008000;">///</span>
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">ObjectSet</span>&lt;<span style="color: #008080;">Ad</span>&gt; Ads
    {
      <span style="color: #0000ff;">get</span>
      {
        <span style="color: #0000ff;">return</span> _ads;
      }
    }

    <span style="color: #0000ff;">public</span> <span style="color: #008080;">ObjectSet</span>&lt;<span style="color: #008080;">Newspaper</span>&gt; Newspapers
    {
      <span style="color: #0000ff;">get</span>
      {
        <span style="color: #0000ff;">return</span> _newspapers;
      }
    }

    <span style="color: #008000;">///</span>
    <span style="color: #008000;">/// This creates an ad that allows it "to be used with the Entity Framework."</span>
    <span style="color: #008000;">///</span>
    <span style="color: #008000;">///</span>
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Ad</span> CreateAttachedAd()
    {
      <span style="color: #0000ff;">return</span> <span style="color: #008080;">EntityContext</span>.Context.CreateObject&lt;<span style="color: #008080;">Ad</span>&gt;();
    }

    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Newspaper</span> CreateAttachedNewspaper()
    {
      <span style="color: #0000ff;">return</span> <span style="color: #008080;">EntityContext</span>.Context.CreateObject&lt;<span style="color: #008080;">Newspaper</span>&gt;();
    }
  }
}</pre>
<p>The CreateAttached methods aren't needed on the Context class itself, I just put them there. They could go on the Ad/Newspaper class but at this point I'm not sure if that blurs the lines or not. Haven't gotten into best practices mode yet.</p>
<p>You may notice the ObjectSet collections on the context. These are the collections you will query to get items most likely, much like the old context class from the last version:</p>
<pre>Context.Ads.Where(ad =&gt; ad.Id == 1)</pre>
<p>Pretty nice, huh?</p>
<p>Also, I noted above about the virtual properties on the Ad/Newspaper classes and how it had to do with lazy loading.</p>
<pre>ContextOptions.LazyLoadingEnabled = <span style="color: #0000ff;">true</span>;</pre>
<p>That line and the virtual properties ensure that lazy loading will occur when the property is used. Both have to be used together. Now you don't have to put that line in the constructor if you do create a context every time you are retrieving things, you could just set it on a case by case basis. Up to you. I use a <a href="http://byatool.com/index.php/pontification/singleton-objectcontext-the-remix/">singleton like context</a> so I just set it true in the constructor and don't worry about it.</p>
<p>The main thing I had trouble with was this line:</p>
<pre><span style="color: #0000ff;">public</span> <span style="color: #008080;">Beta2TestContext</span>() : <span style="color: #0000ff;">base</span>(<span style="color: #800000;">"name=InterviewDemoEntities"</span>, <span style="color: #800000;">"InterviewDemoEntities"</span>)</pre>
<p>Because I wasn't sure what the second string should be. First one is easy, it's whatever the key in the config file for the connection string. Second, chances are, is the same depending on how you set it all up in the wizard. I think it's the same name when you right click on the opened .edmx file and view properties. There should be a property named "Entity Container Name".</p>
<p>Here's a method I used for testing to create an Ad:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #008080;">Ad</span> CreateAd(<span style="color: #008080;">Boolean</span> persist)
  {
    <span style="color: #008080;">Ad</span> ad = <span style="color: #0000ff;">null</span>;

    <span style="color: #0000ff;">if</span> (persist)
    {
      ad = <span style="color: #008080;">EntityContext</span>.Context.CreateAttachedAd();  <span style="color: #008000;">//This is the CreateAttachedAd method above in use
</span>    }
    <span style="color: #0000ff;">else
</span>    {
      ad = <span style="color: #0000ff;">new</span> <span style="color: #008080;">Ad</span>();
    }

    ad.CreatedDate = <span style="color: #008080;">DateTime</span>.UtcNow;
    ad.Height = <span style="color: #008080;">RandomTool</span>.RandomInt32(0, 10);
    ad.LastUpdated = <span style="color: #008080;">DateTime</span>.UtcNow;
    ad.Name = <span style="color: #008080;">RandomTool</span>.RandomString(10);
    ad.Width = <span style="color: #008080;">RandomTool</span>.RandomInt32(0, 10);

    <span style="color: #0000ff;">if</span> (persist)
    {
      AddEntityForRemoval(ad);  <span style="color: #008000;">//Ignore, for persistence removal after testing is completed</span>
      <span style="color: #008080;">EntityContext</span>.Context.Ads.AddObject(ad);  <span style="color: #008000;">//Ad the ... ad to the context</span>
      <span style="color: #008080;">EntityContext</span>.Context.SaveChanges();  <span style="color: #008000;">//Persist</span>
    }

    <span style="color: #0000ff;">return</span> ad;
  }</pre>
<p>There are some things you can ignore because I didn't feel like removing code. As you can see though, it's not very complicated. Use the CreateAttachedAd, fill in the properties, ad to the Ad collection on the context, and save.</p>
<p><strong>The End</strong></p>
<p>Sure you had to do more work than in the earlier version of Entity Framework, but on the other hand I have a fully detached class that can inherit from any class I WANT it to as opposed to the EntityObject class. Not to mention I now have an easy way to do lazy loading. Far cleaner than the <a href="http://byatool.com/index.php/pontification/entity-framework-possible-lazy-loading-solution/">old way I did it</a>. The other interesting thing to note, and this may not be a big deal to anyone else, but above I have a note about this:</p>
<pre>  AddEntityForRemoval(ad);  <span style="color: #008000;">//Ignore, for persistence removal after testing is completed</span></pre>
<p>This method just adds the object to a collection of EntityObjects that later I use to delete the object from the database on test cleanup. After moving to this version of EF, I had to change it to a collection of Objects. Interesting thing is:</p>
<pre>  <span style="color: #008080;">EntityContext</span>.Context.DeleteObject(currentObject);</pre>
<p>Didn't care. It still knew that the object was attached to the context somehow, despite the CLASS not being an EntityObject. Just an odd note.</p>
<p>Two Errors I came across:</p>
<blockquote><p>System.InvalidOperationException: Mapping and metadata information could not be found for EntityType 'Beta2Test.Data.Ad'.</p></blockquote>
<p>If you get this, there is a really good chance you screwed up a property name or are missing it completely. If the property name doesn't exactly match one in the .edmx class designer template, you're screwed. If you don't have it on the class but it's on the class designer template, you're screwed. If you add it to the class designer template, it has to be on the class as far as I can tell. Now, it doesn't have to be public. I have tested it as private and it works just fine.</p>
<blockquote><p>The required property 'Newspapers' does not exist on the type 'Beta2Test.Data.Ad'.</p></blockquote>
<p>This most likely happens if you didn't remember to make it a property:</p>
<pre><span style="color: #0000ff;">public</span> <span style="color: #008080;">IList</span>&lt;<span style="color: #008080;">Newpaper</span>&gt; Newpapers;  <span style="color: #008000;">//Forgot the { get; set; }</span></pre>
<pre><span style="color: #0000ff;">public</span> <span style="color: #008080;">IList</span>&lt;<span style="color: #008080;">Newpaper</span>&gt; Newpapers { get; set; };  <span style="color: #008000;">//Forgot the Virtual</span></pre>
<p>Opps.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li><li><a href="http://byatool.com/net-issues/entity-framework-linq-to-entities-only-supports-casting-entity-data-model-primitive-types/" title="Entity Framework: LINQ to Entities only supports casting Entity Data Model primitive types">Entity Framework: LINQ to Entities only supports casting Entity Data Model primitive types</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>ASP.Net MVC: Attributes, ActionFilterAttribute, and Why You Might Want To Use Them</title>
		<link>http://byatool.com/lessons/asp-net-mvc-attributes-actionfilterattribute-and-why-you-might-want-to-use-them/</link>
		<comments>http://byatool.com/lessons/asp-net-mvc-attributes-actionfilterattribute-and-why-you-might-want-to-use-them/#comments</comments>
		<pubDate>Tue, 04 Aug 2009 21:49:23 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Attributes]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=793</guid>
		<description><![CDATA[So if you've used MVC, and I know you have because you want to be cool like me, you've most likely run into an error like this: Certain parameter wasn't found. Make [parameter] nullable. In other words, the parameter didn't show up in the URL and therefor MVC can't assign a value to it. This [...]]]></description>
			<content:encoded><![CDATA[<p>So if you've used MVC, and I know you have because you want to be cool like me, you've most likely run into an error like this:</p>
<blockquote><p>Certain parameter wasn't found. Make [parameter] nullable.</p></blockquote>
<p>In other words, the parameter didn't show up in the URL and therefor MVC can't assign a value to it. This would of course happen with anything that isn't nullable. Now you could do this:</p>
<pre>  <span style="color: #0000ff;">void</span> SomeAction(<span style="color: #008080;">Int32</span>? pageNumber)
  {
    <span style="color: #0000ff;">if</span>(someParameter.HasValue)
    {
      ..
    }
  }</pre>
<p>But do you really feel like putting that in every stupid method that happens to have the same parameter? Say the parameter is something simple like pageNumber. Taking the above code, you would have to see if pageNumber has a value and if it doesn't, continue to set some variable to a default. Kind of annoying to have to repeat that over and over again when you know you will be looking for pageNumber on many actions. Well Attributes, or more importantly ActionFilterAttribute, are the way to get around this.</p>
<p>Say with the pageNumber example you want a default of 1 if it doesn't exist. Well that's easy to do, it would be something like this:</p>
<pre>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">sealed</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">CheckPageNumberAttribute</span> : <span style="color: #008080;">ActionFilterAttribute</span>
    {
        <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">const</span> <span style="color: #008080;">String</span> DefaultPageNumber = 0;

        <span style="color: #008000;">//This will fire automatically on page load.
</span>        <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">override</span> <span style="color: #0000ff;">void</span> OnActionExecuting(<span style="color: #008080;">ActionExecutingContext</span> filterContext)
        {
            base.OnActionExecuting(filterContext);
            <span style="color: #008000;">//ActionParameters.Values holds all the request parameters after the ? as in ?pageNumber=1</span>
            <span style="color: #008000;">//See if it exists first.  If not, add it</span>
            <span style="color: #0000ff;">if</span> (!filterContext.ActionParameters.ContainsKey(<span style="color: #800000;">"pageNumber"</span>))
            {
                filterContext.ActionParameters.Add(RequestConstants.PageNumber, <span style="color: #0000ff;">null</span>);
            }

            <span style="color: #008000;">//Set to default if it's not null</span>
            filterContext.ActionParameters[<span style="color: #800000;">"pageNumber"</span>] = filterContext.ActionParameters[<span style="color: #800000;">"pageNumber"</span>] ?? DefaultPageNumber;
        }
    }</pre>
<p>So the method looks more like this now:</p>
<pre>  [<span style="color: #008080;">CheckPageNumberAttribute</span>]
  <span style="color: #0000ff;">void</span> SomeAction(<span style="color: #008080;">Int32</span> someParameter)
  {
    ...
  }</pre>
<p>And you can now do your ... without worry.</p>
<p>But what if the url is like this?</p>
<blockquote><p>ShowMeACoolRoom/Index/1/</p></blockquote>
<p>And you have your route set up like:</p>
<pre>  <span style="color: #800000;">{controller}/{action}/{roomId}</span></pre>
<p>And you want to make sure that not only does that userId exist in the url, but the user actually exists. Well you don't look to the ActionParameters.</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">sealed</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">RoomExistsAttribute</span> : <span style="color: #008080;">ActionFilterAttribute</span>
  {
    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">override</span> <span style="color: #0000ff;">void</span> OnActionExecuting(<span style="color: #008080;">ActionExecutingContext</span> context)
    {
      base.OnActionExecuting(context);

      <span style="color: #008080;">ChatRoom</span> foundRoom = <span style="color: #0000ff;">null</span>;
      <span style="color: #008000;">//RouteData.Values holds all the values in the url it was able to match to a route</span>
      <span style="color: #008000;">//Check the Values list in the RouteData for the id
</span>      <span style="color: #0000ff;">if</span>(context.RouteData.Values.ContainsKey(<span style="color: #800000;">"id"</span>))
      {
        <span style="color: #008000;">//Convert to an integer, ConvertTo <a href="http://byatool.com/index.php/utilities/duck-typing-my-way-to-a-universal-string-convert/">is just a method I've made</a>.</span>
        <span style="color: #008080;">Int32</span>? roomId =
          Convert.ToString(context.RouteData.Values[<span style="color: #800000;">"id"</span>]).ConvertTo();
        <span style="color: #0000ff;">if</span>(roomId.HasValue)
        {
            foundRoom = ChatRoom.GetRoomByID(roomId.Value);
        }
     }

     <span style="color: #008000;">//If the room isn't found, handle the error.</span>
     <span style="color: #0000ff;">if</span> (foundRoom == <span style="color: #0000ff;">null</span>)
     {
       <span style="color: #008000;">//redirect on error...</span>
       context.Result =
         <span style="color: #0000ff;">new</span> <span style="color: #008080;">RedirectToRouteResult</span>
         (
           GeneralConstants.RouteName,
           <span style="color: #0000ff;">new</span> <span style="color: #008080;">RouteValueDictionary</span>
           {
              { <span style="color: #800000;">"controller"</span>, <span style="color: #800000;">"sharedError"</span> },
              {  <span style="color: #800000;">"action"</span>, <span style="color: #800000;">"error"</span> },
              { <span style="color: #800000;">"name"</span>, <span style="color: #800000;">"someErrorKey"</span> }
            }
          );
       }
    }
  }</pre>
<p>Now the new method looks something like this:</p>
<pre>  [<span style="color: #008080;">RoomExistsAttribute</span>]
  [<span style="color: #008080;">CheckPageNumberAttribute</span>]
  <span style="color: #0000ff;">void</span> SomeAction(<span style="color: #008080;">Int32</span> roomId, <span style="color: #008080;">Int32</span> someParameter)
  {
    ...
  }</pre>
<p>And once again you are free to ... without worry of the room not existing. Next post I plan on adding some more "advanced" attributes... hahaha advanced? This site? hahahaha sorry. But I will be adding a new post about certain attribute solutions I've found that work well.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/pointless/asp-net-mvc-attibute-to-check-if-route-value-exists-and-and-means-something/" title="ASP.Net MVC: Attibute to Check if Route Value Exists and&#8230; and Means Something!">ASP.Net MVC: Attibute to Check if Route Value Exists and&#8230; and Means Something!</a></li><li><a href="http://byatool.com/c/asp-net-mvc-attributes-and-semi-dynamic-check-for-request-parameters/" title="ASP.NET MVC:  Attributes and Semi Dynamic Check for Request Parameters">ASP.NET MVC:  Attributes and Semi Dynamic Check for Request Parameters</a></li><li><a href="http://byatool.com/lessons/spark-view-engine-asp-net-mvc-and-you/" title="Spark View Engine, ASP.Net MVC, and You">Spark View Engine, ASP.Net MVC, and You</a></li><li><a href="http://byatool.com/writing/byatool-com-gets-a-shiny-new-tool/" title="ByATool.com gets a shiny new tool!">ByATool.com gets a shiny new tool!</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/asp-net-mvc-attributes-actionfilterattribute-and-why-you-might-want-to-use-them/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>ASP.Net MVC: Routes, Route Contraints, and My Love Hate Relationship</title>
		<link>http://byatool.com/lessons/aspnet-mvc-routes-route-contraints-and-my-love-hate-relationship/</link>
		<comments>http://byatool.com/lessons/aspnet-mvc-routes-route-contraints-and-my-love-hate-relationship/#comments</comments>
		<pubDate>Mon, 03 Aug 2009 16:29:05 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Routing]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=786</guid>
		<description><![CDATA[So something that has been somewhat of an uphill climb as of late is routing in MVC. I think part of it is the way it works and part of it is that I've approached MVC like a 10 year old with a new game; F- the instructions, I'm all up in this. What goes [...]]]></description>
			<content:encoded><![CDATA[<p>So something that has been somewhat of an uphill climb as of late is routing in MVC. I think part of it is the way it works and part of it is that I've approached MVC like a 10 year old with a new game; F- the instructions, I'm all up in this.</p>
<p><strong>What goes out must come in...</strong></p>
<p>The biggest misconception I had with routes is that the route definitions meant something when a page is loading. This is bad. Now before the nerd rage starts to build, I will qualify that statement. Route definitions mean nothing beyond a simple mapping of values. What? Well suppose I have two routes:</p>
<pre>   routes.MapRoute
   (
     ...
      <span style="color: #800000;">"{controller}/{action}/{roomId}/{name}"</span>,
     ...
   );</pre>
<p>and</p>
<pre>   routes.MapRoute
   (
     ...
     <span style="color: #800000;">"{controller}/{action}/{userId}/{name}"</span>,
     ...
   );</pre>
<p>Now on the way out, the system can find the route easy if you supply the correct route data: (Lets say for the second route)</p>
<pre>  routeValues = <span style="color: #0000ff;">new</span> <span style="color: #008080;">RouteDicationary</span>()
  routeValues.Add(<span style="color: #800000;">"controller"</span>, <span style="color: #800000;">"Room"</span>);
  routeValues.Add(<span style="color: #800000;">"action"</span>, <span style="color: #800000;">"Index"</span>);
  routeValues.Add(<span style="color: #800000;">"userId"</span>, 1);
  routeValues.Add(<span style="color: #800000;">"name"</span>, <span style="color: #800000;">"ProgramminTool"</span>);

  neededHelper.RouteUrl("SecondRoute", routeValues);</pre>
<p>Which will give me a wonderful address of:</p>
<pre>  /User/Index/1/ProgramminTool</pre>
<p>Awesome, the routing system did what I wanted. Problem is, I assumed too much coming in, ie when the page is loading from the url. (Say from a clicked link) I kept getting an error like:</p>
<blockquote><p>RoomId doesn't exist. Make roomId nullable. Blah blah blah I hate you and you should quit programming and do something more equal to your ability level like spinning in circles.</p></blockquote>
<p>Though I might have take some artist license on the error, the meaning was simple: it was trying to run that url against the Room controller and it couldn't find the roomId parameter in the request. Well that doesn't make sense, after all it's obvious that it should be looking for the user controller and use the route with the userId paramter. Sadly, it doesn't work that way and not sure it could. Why? Well look at the url.</p>
<blockquote><p>/User/Index/1/ProgramminTool</p></blockquote>
<p>Now if you were too look at that, what would you think? You have four values, values that you can't really guess the type since you have no real context. After all there could easily be a method that takes in a string userId as opposed to an integer userId. On top of that, it has no idea what the 1 is. There's no userId=1 to tell it what it is. So what does it do? It goes down the route table and finds the best fit. Now you tell me, which does this url fit better?</p>
<pre>  <span style="color: #800000;">"{controller}/{action}/{roomId}/{name}"</span></pre>
<p>Or</p>
<pre>  <span style="color: #800000;">"{controller}/{action}/{userId}/{name}"</span></pre>
<p>It's kind of a trick question since the answer is neither. It will just fit it to the first one that it likes, and in this example it's the roomId one. Problem is, now the user controller method that is looking for the userId fails because there is no userId. Uhg.</p>
<p><strong>Computers are dumb, they can only do what we tell them.</strong></p>
<p>Fact is, in this situation I have to make some rules for the routing system to take in and start digesting the url properly, and there's a way to do this: IRouteConstraint.</p>
<p>Say that you have certain controllers or actions you don't want to use the first route. For this example I'll use user actions from my current project. On the room index view there is a button for adding the room as a favorite. Now the action/method it needs is on the user controller, not the room controller. Therefore I have to post some information to the user controller using a route that looks like this:</p>
<pre>  <span style="color: #800000;">"{controller}/{action}/{userId}/{roomId}"</span></pre>
<p>But it is preceded by one that looks like:</p>
<pre>  <span style="color: #800000;">"{controller}/{action}/{id}/{name}"</span></pre>
<p>See the issue? Now when MVC generates the url, everything is fine. After all it uses the route name and the parameters to pick the correct route. On the way in, not so good. It naturally tries to conform the url to the id/name route. BOOM HEADSHOT! Now the solution.</p>
<pre><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">NotGivenAction</span> : <span style="color: #008080;">IRouteConstraint</span>
{
  <span style="color: #008000;">//This is the action that we want to prevent from the route accepting</span>
  <span style="color: #0000ff;">private</span> <span style="color: #008080;">String</span> GivenAction { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }

  <span style="color: #0000ff;">public</span> NotGivenAction(<span style="color: #008080;">String</span> givenAction)
  {
    GivenAction = givenAction;
  }

  <span style="color: #0000ff;">public</span> <span style="color: #008080;">Boolean</span> Match(<span style="color: #008080;">HttpContextBase</span> httpContext, <span style="color: #008080;">Route</span> route, <span style="color: #008080;">String</span> parameterName, <span style="color: #008080;">RouteValueDictionary</span> values, <span style="color: #008080;">RouteDirection</span> routeDirection)
  {
    <span style="color: #008080;">String</span> parameterValue = values[parameterName].ToString();
    <span style="color: #008000;">//Make sure the parameter exists and it doesn't match the bad action
</span>    <span style="color: #0000ff;">return</span> values.ContainsKey(parameterName) &amp;&amp; parameterValue != GivenAction;
  }
}</pre>
<p>The IRouteConstraint interface has a method Match that has to be given life. The short of it is take in the parameter name and find it's value and then see if the value is the same as the action it's looking for. For example, if I had an action of AddToFavorites, this would go through and make sure it isn't that action. If it is, it knows to not use the current route for this action.</p>
<pre>routes.MapRoute
(
  <span style="color: #008080;">GeneralConstants</span>.RouteIdName,
  <span style="color: #800000;">"{controller}/{action}/{id}/{name}"</span>,
  <span style="color: #0000ff;">new</span> { controller = <span style="color: #800000;">"Room"</span>, action = <span style="color: #800000;">"Index"</span>, id = <span style="color: #800000;">"0"</span>, name = <span style="color: #800000;">"None"</span> },
  <span style="color: #0000ff;">new</span> { action = <span style="color: #0000ff;">new</span> <span style="color: #008080;">NotGivenAction</span>(<span style="color: #008080;">UserControllerConstants</span>.AddToUserFavorite) }
);

routes.MapRoute
(
  <span style="color: #008080;">GeneralConstants</span>.RouteUserIdRoomId,
  <span style="color: #800000;">"{controller}/{action}/{userId}/{roomId}"</span>,
  <span style="color: #0000ff;">new</span> { controller = <span style="color: #008080;">GeneralConstants</span>.ControllerUser, action =   <span style="color: #008080;">UserControllerConstants</span>.AddToFavorites, userId = <span style="color: #800000;">"-1"</span>, roomId = <span style="color: #800000;">"-1"</span> }
);</pre>
<p>So now it will skip the first and push to the second when the url looks like:</p>
<pre>  /User/routes.MapRoute/AddToFavorites/1/2/</pre>
<p>Take that you f-ing routes. KING KONG AIN'T GOT S- ON ME!</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/spark-view-engine-asp-net-mvc-and-you/" title="Spark View Engine, ASP.Net MVC, and You">Spark View Engine, ASP.Net MVC, and You</a></li><li><a href="http://byatool.com/writing/byatool-com-gets-a-shiny-new-tool/" title="ByATool.com gets a shiny new tool!">ByATool.com gets a shiny new tool!</a></li><li><a href="http://byatool.com/lessons/data-annotations-mvc-and-why-you-might-like-them/" title="Data Annotations, MVC, and Why You Might Like Them">Data Annotations, MVC, and Why You Might Like Them</a></li><li><a href="http://byatool.com/pontification/asp-net-mvc-quick-overview-of-controller-structure/" title="ASP.Net MVC:  Quick Overview of Controller Structure">ASP.Net MVC:  Quick Overview of Controller Structure</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/aspnet-mvc-routes-route-contraints-and-my-love-hate-relationship/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dictionary Index Lookup Vs Contains Key Vs List Contains Vs Linq&#8230; Speed Test/Texas Tornado Match</title>
		<link>http://byatool.com/lessons/dictionary-index-lookup-vs-contains-key-vs-list-contains-vs-linq-speed-testtexas-tornado-match/</link>
		<comments>http://byatool.com/lessons/dictionary-index-lookup-vs-contains-key-vs-list-contains-vs-linq-speed-testtexas-tornado-match/#comments</comments>
		<pubDate>Thu, 30 Jul 2009 17:26:32 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Hash]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Test]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=777</guid>
		<description><![CDATA[Ok so with MVC comes the use of Routes which calls in the need to compare request values to see which route to use. Now before I even bother with that headache (Although it's getting better AND will be a post) I ran into a situation where I would have to check a passed in [...]]]></description>
			<content:encoded><![CDATA[<p>Ok so with MVC comes the use of Routes which calls in the need to compare request values to see which route to use. Now before I even bother with that headache (Although it's getting better AND will be a post) I ran into a situation where I would have to check a passed in string against a list of strings to see if it matches any of them.</p>
<p>One thing I like to do is use Dictionaries. They are just plain convenient when it comes to looking things up or <a href="http://byatool.com/index.php/general-coding/the-switch-remover/">matching values to get methods</a>. But what if I don't really have a value to find with a key? What if finding the key is all that matters? Say I have a list of strings and I just want to know if the list contains that string, sounds like a job for an array or list right? Wouldn't it be silly to create a dictionary like:</p>
<pre>  <span style="color: #008080;">Dictiontary</span>&lt;<span style="color: #008080;">String</span>, <span style="color: #008080;">String</span>&gt; someList = <span style="color: #0000ff;">new</span> <span style="color: #008080;">Dictiontary</span>&lt;<span style="color: #008080;">String</span>, <span style="color: #008080;">String</span>&gt;();
  someList.Add(<span style="color: #800000;">"INeedThis"</span>, <span style="color: #800000;">""</span>); someList.Add(<span style="color: #800000;">"ThisToo"</span>, <span style="color: #800000;">""</span>);</pre>
<p>and do this:</p>
<pre>  if(someList.ContainsKey(<span style="color: #800000;">"INeedThis"</span>))</pre>
<p>If I don't actually care about the attached value? I'm sure I'm breaking a rule somewhere... but what if it was faster overall? What if ContainsKey is faster than a list using Any, Contains, FirstOrDefault, or where? Turns out it is. Here's the method I used.</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> TimeRun(<span style="color: #008080;">Holder</span> toHold)
  {
    <span style="color: #008080;">Int32</span> maxLength = 1000;

    <span style="color: #008080;">Dictionary</span>&lt;<span style="color: #008080;">String</span>, <span style="color: #008080;">String</span>&gt; stringDictionary = Enumerable.Range(0, maxLength).Select(item =&gt; RandomTool.RandomString(item)).ToDictionary(item =&gt; item, item =&gt; item);
    <span style="color: #008080;">List</span>&lt;<span style="color: #008080;">String</span>&gt; stringList = stringDictionary.Select(item =&gt; item.Key).ToList();

    <span style="color: #008080;">String</span> chosenString = stringList[RandomTool.RandomInt32(0, maxLength)];

    <span style="color: #008080;">Stopwatch</span> runTime = <span style="color: #0000ff;">new</span> <span style="color: #008080;">Stopwatch</span>();

    runTime.Start();
    stringDictionary.ContainsKey(chosenString);
    runTime.Stop();
    toHold.DictionaryContainsKeyTime = runTime.ElapsedTicks;
    runTime.Reset();

    runTime.Start();
    <span style="color: #008080;">String</span> junk = stringDictionary[chosenString];
    runTime.Stop();
    toHold.DictionaryStraightIndexCheck = runTime.ElapsedTicks;
    runTime.Reset();

    runTime.Start();
    <span style="color: #008080;">Boolean</span> junkThree = stringList.Contains(chosenString);
    runTime.Stop();
    toHold.ListContains = runTime.ElapsedTicks;
    runTime.Reset();

    runTime.Start();
    <span style="color: #008080;">Boolean</span> junkTwo = stringList.Any(item =&gt; item == chosenString);
    runTime.Stop();
    toHold.ListLinqAny = runTime.ElapsedTicks;
    runTime.Reset();

    runTime.Start();
    <span style="color: #008080;">String</span> junkFour = stringList.First(item =&gt; item == chosenString);
    runTime.Stop();
    toHold.ListLinqFirst = runTime.ElapsedTicks;
    runTime.Reset();

    runTime.Start();
    <span style="color: #008080;">IEnumerable</span>&lt;<span style="color: #008080;">String</span>&gt; junkFive = stringList.Where(item =&gt; item == chosenString);
    <span style="color: #0000ff;">if</span> (junkFive.FirstOrDefault() != String.Empty)
    {

    }
    runTime.Stop();
    toHold.ListLinqWhere = runTime.ElapsedTicks;
    runTime.Reset();
  }</pre>
<p>Crazy simple, and why shouldn't it? Am I right? Am I right? Ok. As you can see, I gave all the methods a run and timed them using StopWatch. And then I ran it a given amount of times, 200 in this code but I tried up to 10000 also. (I'll put the test code at the end) The test was to go through a list of a thousand strings, each string increasing in length. (Yeah I could have done random size strings but I'm lazy)</p>
<p>What did I find out? Well if it didn't throw an exception, a straight index search on a dictionary is fastest:</p>
<pre>someList[<span style="color: #800000;">"INeedThis"</span>]</pre>
<p>And pretty consistently fast. Around 2600 ticks or so on average on multiple runs. (so 10 iterations of parent method running 200-10000 interations of the test method) Next fastest was the ContainsKey method on the dictionary, usually around 2-4 times faster than the next in line good old List.Contains. What I did find surprising is that all the Linq methods failed on this one. I figured that once the first run was through, it would be at least as fast as Contains. (Linq always sucks the first time through) Yeah not so much though. Contains was always faster. Sometimes it was close. Sometimes not even. Here are some example runs:</p>
<pre>Dictionary_ContainsKey: 15805
Dictionary_StraightIndexCheck: 2926
List_Contains: 34559
List_LinqAny: 96575
List_LinqFirst: 56541
List_LinqWhere: 64678 

Dictionary_ContainsKey: 7264
Dictionary_StraightIndexCheck: 2676
List_Contains: 29970
List_LinqAny: 41280
List_LinqFirst: 58313
List_LinqWhere: 45669 

Dictionary_ContainsKey: 6773
Dictionary_StraightIndexCheck: 2636
List_Contains: 32366
List_LinqAny: 38670
List_LinqFirst: 33859
List_LinqWhere: 41288</pre>
<p>All in ticks. Now mind you, none of these are horribly slow so it probably just comes down to reability and ease of understanding. Personally I like the Dictionary way, so at least speed wise I'm on track. As for looks? That's a personal thing.</p>
<p>Rest of the code. Here is the parent method. This is a unit test hense the .Assert but it could easily be adapted to any output.</p>
<pre>  [<span style="color: #008080;">TestMethod</span>]
  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> RunTime()
  {
    <span style="color: #008080;">Int64</span> overallDictionaryContainsKeyTime = 0;
    <span style="color: #008080;">Int64</span> overallDictionaryStraightIndexCheck = 0;
    <span style="color: #008080;">Int64</span> overallListContains = 0;
    <span style="color: #008080;">Int64</span> overallListLinqAny = 0;
    <span style="color: #008080;">Int64</span> overallListLinqFirst = 0;
    <span style="color: #008080;">Int64</span> overallListLinqWhere = 0;
    <span style="color: #008080;">Int32</span> loopMax = 200;

    <span style="color: #0000ff;">for</span> (<span style="color: #008080;">Int32</span> loopCounter = 0; loopCounter &lt; loopMax; loopCounter++)
    {
      <span style="color: #008080;">Holder</span> currentHolder = <span style="color: #0000ff;">new</span> <span style="color: #008080;">Holder</span>();

      TimeRun(currentHolder);
      overallDictionaryContainsKeyTime += currentHolder.DictionaryContainsKeyTime;
      overallDictionaryStraightIndexCheck += currentHolder.DictionaryStraightIndexCheck;
      overallListContains += currentHolder.ListContains;
      overallListLinqAny += currentHolder.ListLinqAny;
      overallListLinqFirst += currentHolder.ListLinqFirst;
      overallListLinqWhere += currentHolder.ListLinqWhere;
    }

    Assert.IsTrue
    (
      <span style="color: #0000ff;">false</span>,
      <span style="color: #800000;">" Dictionary_ContainsKey: "</span> + (overallDictionaryContainsKeyTime / loopMax) +
      <span style="color: #800000;">" Dictionary_StraightIndexCheck: "</span> + (overallDictionaryStraightIndexCheck / loopMax) +
      <span style="color: #800000;">" List_Contains: "</span> + (overallListContains / loopMax) +
      <span style="color: #800000;">" List_LinqAny: "</span> + (overallListLinqAny / loopMax) +
      <span style="color: #800000;">" List_LinqFirst: "</span> + (overallListLinqFirst / loopMax) +
      <span style="color: #800000;">" List_LinqWhere: "</span> + (overallListLinqWhere / loopMax)
    );
  }</pre>
<p>And the holder class which is a nothing class. I just didn't care for having to add parameters to the child mehod.</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> Holder
  {
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int64</span>DictionaryContainsKeyTime { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int64</span>DictionaryStraightIndexCheck { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int64</span>ListLinqAny { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int64</span>ListContains { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int64</span>ListLinqFirst { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int64</span>ListLinqWhere { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }</pre>
<p>Couple Notes:</p>
<ul>
<li>StopWatch is in System.Diagnostics</li>
<li>RandomTool is actual a class of mine. Nothing special about it. Just makes a string of X length with all random letters.</li>
<li>This can not be rebroadcast or retransmitted without the express written permission of my mom.</li>
</ul>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/how-to-use-a-factory-method-with-castle-windsorcontainer/" title="How to Use a Factory Method With Castle / WindsorContainer">How to Use a Factory Method With Castle / WindsorContainer</a></li><li><a href="http://byatool.com/lessons/castle-rhino-mocking-and-possibly-you/" title="Castle, Rhino, Mocking, and Possibly You">Castle, Rhino, Mocking, and Possibly You</a></li><li><a href="http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-3/" title="Paging and the Entity Framework, Skip, and Take Part 3">Paging and the Entity Framework, Skip, and Take Part 3</a></li><li><a href="http://byatool.com/c/linq-join-method-and-how-to-use-it/" title="Linq Join Extension Method and How to Use It&#8230;">Linq Join Extension Method and How to Use It&#8230;</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/dictionary-index-lookup-vs-contains-key-vs-list-contains-vs-linq-speed-testtexas-tornado-match/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Asp.net Mvc Master Page: System.Data.Entity Must Be Referenced</title>
		<link>http://byatool.com/lessons/aspnet-mvc-master-page-systemdataentity-must-be-referenced/</link>
		<comments>http://byatool.com/lessons/aspnet-mvc-master-page-systemdataentity-must-be-referenced/#comments</comments>
		<pubDate>Fri, 17 Jul 2009 20:13:11 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=728</guid>
		<description><![CDATA[Ok maybe you're better at figuring out the obvious than I am, but this was annoying me. On my master page I happened to be using an object from another assembly that used the Entity Framework. Now by habit, I have this assembly: System.Data.Entity, Version=3.5.0.0 Referenced to the UI project, so it was a little [...]]]></description>
			<content:encoded><![CDATA[<p>Ok maybe you're better at figuring out the obvious than I am, but this was annoying me. On my master page I happened to be using an object from another assembly that used the Entity Framework. Now by habit, I have this assembly:</p>
<p>System.Data.Entity, Version=3.5.0.0</p>
<p>Referenced to the UI project, so it was a little of a surpise to me that I was getting this error on the master page. (And the views, but I don't use anything in Views not supplied by Models) I was at a loss as to how to get the thing to work.</p>
<p>Now I could use this:</p>
<p><span style="color: #ffcc00;">&lt;%</span><span style="color: #0000ff;">@</span> <span style="color: #800000;">Assembly</span> <span style="color: #ff0000;">Name</span>="<span style="color: #0000ff;">System.Data.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089</span>" <span style="color: #ffcc00;">%&gt;</span></p>
<p>On the page, but would be silly to do that all the thing, and DUH in WebForms... or ASP.Net Classic, is to put it in the stupid web config.</p>
<pre>  &lt;<span style="color: #800000;">system.web</span>&gt;
    ...
    &lt;<span style="color: #800000;">assemblies</span>&gt;
      ...
      &lt;<span style="color: #800000;">add</span> <span style="color: #ff0000;">assembly</span>="<span style="color: #0000ff;">System.Data.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089</span>"/&gt;
      ...
    &lt;/<span style="color: #800000;">assemblies</span>&gt;
  ...</pre>
<p>No more problems.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/spark-view-engine-asp-net-mvc-and-you/" title="Spark View Engine, ASP.Net MVC, and You">Spark View Engine, ASP.Net MVC, and You</a></li><li><a href="http://byatool.com/writing/byatool-com-gets-a-shiny-new-tool/" title="ByATool.com gets a shiny new tool!">ByATool.com gets a shiny new tool!</a></li><li><a href="http://byatool.com/lessons/data-annotations-mvc-and-why-you-might-like-them/" title="Data Annotations, MVC, and Why You Might Like Them">Data Annotations, MVC, and Why You Might Like Them</a></li><li><a href="http://byatool.com/pontification/asp-net-mvc-quick-overview-of-controller-structure/" title="ASP.Net MVC:  Quick Overview of Controller Structure">ASP.Net MVC:  Quick Overview of Controller Structure</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/aspnet-mvc-master-page-systemdataentity-must-be-referenced/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Mythical ++ Situation: ++ vs +=1</title>
		<link>http://byatool.com/lessons/the-mythical-situation-vs-1/</link>
		<comments>http://byatool.com/lessons/the-mythical-situation-vs-1/#comments</comments>
		<pubDate>Fri, 15 May 2009 15:01:44 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Operators]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=700</guid>
		<description><![CDATA[So this may be a post that most good programmers will think, "Well duh" but as I'm a tool this finally caught me. I'd always heard that ++ evaluates differently than +=1, but I'd never run into a situation that would turn the old light bulb on so I really didn't care. Well I met [...]]]></description>
			<content:encoded><![CDATA[<p>So this may be a post that most good programmers will think, "Well duh" but as I'm a tool this finally caught me.</p>
<p>I'd always heard that ++ evaluates differently than +=1, but I'd never run into a situation that would turn the old light bulb on so I really didn't care. Well I met that situation today.</p>
<p>I was writing a method that basically checks to see if all the dates in a list are in order by creating a dictionary, assigning the index as the key, and sorting by the date. I then convert the keys to an array and make sure that the index is the same as the key. After all, if the dates are in order, the keys should mimic an index.</p>
<pre>  Key     Date
  0        6-27-2008
  1        6-28-2008
  2        6-29-2008</pre>
<p>So that the new array would be:</p>
<pre>  [0]    0
  [1]    1
  [2]    2</pre>
<p>And if anything was out of order, you would get something like this:</p>
<pre>  [0]    0
  [1]    2
  [2]    1</pre>
<p>So the code is basically:</p>
<pre>  <span style="color: #0000ff;">int</span> loopCounter = -1;

  <span style="color: #008080;">IDictionary</span>&lt;<span style="color: #008080;">DateTime</span>&gt; timeSequence =
                dateList
                .ToDictionary(item =&gt; loopCounter++);
  <span style="color: #0000ff;">var</span> sequenceList =
                 timeSequence
                 .OrderBy(item =&gt; item.Value)
                 .Select(item =&gt; item.Key).ToArray();
  <span style="color: #0000ff;">return</span> sequenceList.Any(item =&gt; item != sequenceList[item]);</pre>
<p>Now right off the bat you'll see that I used loopCounter ++. The thought was that in order to get this correctly inline (Meaning the key would mock an index) I would have to keep adding to the loopCounter. Well my thought was simply to use ++ and thus I would have to set the loopCounter to -1 at first otherwise the first key would be 1. Well that's not what happened. Turned out it looked like:</p>
<pre>  [0]  -1
  [1]   0
  [2]   1</pre>
<p>Wait what? -1? But I added to it! And here was the catcher. Turns out in this situation, the ++ acts out like:</p>
<ul>
<li>Set the key to what the loopCounter equals right now.</li>
<li>Add 1 too the loopCounter</li>
<li>Continue with loop</li>
</ul>
<p>It actually set the key BEFORE adding the 1 to it. So in reality with this I really needed loopCounter to start at 0 OR use +=1 which would actually add the 1 THEN set the key to the value. Guess I should have paid more attention in school instead of checking NBA message boards.</p>
<p>Side note: Light bulb apparently is two words.  I learned TWO things today.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li>No Related Posts</li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/the-mythical-situation-vs-1/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Entity Framework, Include, and Data Item classes</title>
		<link>http://byatool.com/lessons/entity-framework-include-and-data-item-classes/</link>
		<comments>http://byatool.com/lessons/entity-framework-include-and-data-item-classes/#comments</comments>
		<pubDate>Thu, 14 May 2009 14:33:27 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=694</guid>
		<description><![CDATA[So found something interesting out the other day, and maybe you already knew this but I didn't so I'm going to post about it. Don't like it? Too bad. One things nice about the Entity Framework is the ability to create or fill a class on the fly with the Linq query methods/language. You.. you [...]]]></description>
			<content:encoded><![CDATA[<p>So found something interesting out the other day, and maybe you already knew this but I didn't so I'm going to post about it.  Don't like it?  Too bad.</p>
<p>One things nice about the <span class="showItLink" xmlns:comment="And really NHibernate does this too... I would assume LLBLGEN also.">Entity Framework</span> is the ability to create or fill a class on the fly with the Linq query methods/language. You.. you have no idea what I'm trying to say. Fine. I'll put it in programming speak:</p>
<pre>  someList.Select(item =&gt; <span style="color: #0000ff;">new</span> { item.Name, item.ID })

  or

  <span style="color: #0000ff;">from</span> item <span style="color: #0000ff;">in</span> someList
  <span style="color: #0000ff;">select</span> <span style="color: #0000ff;">new</span> { item.Name, item.ID }</pre>
<p>OR</p>
<pre>  someList.Select(item =&gt; <span style="color: #0000ff;">new</span> DataItemClass { Name = item.Name, ID = item.ID })

  or

  <span style="color: #0000ff;">from</span> item <span style="color: #0000ff;">in</span> someList
  <span style="color: #0000ff;">select</span> <span style="color: #0000ff;">new</span> DataItemClass { Name = item.Name, ID = item.ID }</pre>
<p>As you can see, they are two slightly different examples. One will create a list of anonymous types and the other a list of DataItemClass objects. Now that's not really the point of this, the point is something like this:</p>
<pre>  context.Topics
    .Select(topic =&gt;
                <span style="color: #0000ff;">new</span> TopicItem
                {
                  TopicName = topic.Name ,
                  Creator = topic.User.UserName,
                  Category = topic.Category.Description
                }
              )</pre>
<p>Now, here's the thing that I assumed. When you select out a bunch of topics and you want to make sure that the one to on properties are "include"ed like thus:</p>
<pre>  topicList
   .Include(<span style="color: #800000;">"User"</span>)
   .Include(<span style="color: #800000;">"Category"</span>)
   .Select(item =&gt; item);</pre>
<p>Other wise when you try to access that User property  <span class="showItLink" xmlns:comment="This is unless the Context already has that user in memory, but you can't count on that.">you'll get a null reference exception</span>. So with this I thought that when you query like I did above to fill the TopicItem object, I would get the same problem as I would if I tried just accessing the property on a hydrated Topic. In other words:</p>
<pre>  Creator = topic.User.UserName,</pre>
<p>Would blow up mid query after all calling that property after a query would sans include. Come to find out, and I probably should have already known this, Entity Framework is just fine without having to have the Include method or any kind of join. Infact, adding the include method in the method chain:</p>
<pre>  context.Topics
    .Include(<span style="color: #800000;">"User"</span>)
    .Include(<span style="color: #800000;">"Category"</span>)
    .Select(topic =&gt;
                <span style="color: #0000ff;">new</span> TopicItem
                {
                  TopicName = topic.Name ,
                  Creator = topic.User.UserName,
                  Category = topic.Category.Description
                }
              )</pre>
<p>Did nothing when I profiled the query. The SQL was exactly the same with or without the include. So it's smart enough to know that if I am not actually hydrating an entire Topic object, it doesn't need to bother with the includes. Go figure.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/entity-framework-include-and-data-item-classes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Framework: Querying issue follow up.</title>
		<link>http://byatool.com/lessons/entity-framework-querying-issue-follow-up/</link>
		<comments>http://byatool.com/lessons/entity-framework-querying-issue-follow-up/#comments</comments>
		<pubDate>Thu, 19 Feb 2009 20:07:15 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=483</guid>
		<description><![CDATA[So in THIS MIGHTY POST I asked why Entity Framework context likes to query the database despite the object (data row) already being loaded into the context. Well even though it's not a perfect answer, Craig Stuntz had an answer at The O that gave some light to the situation: context.SiteUser is an property of [...]]]></description>
			<content:encoded><![CDATA[<pre>                <img title="threedoors" src="http://byatool.com/wp-content/uploads/2009/02/threedoors.png" alt="threedoors" width="337" height="230" /></pre>
<p>So in <a href="http://byatool.com/index.php/lessons/entity-framework-odd-things-during-querying" target="_blank">THIS MIGHTY POST</a> I asked why Entity Framework context likes to query the database despite the object (data row) already being loaded into the context.  Well even though it's not a perfect answer, <a href="http://blogs.teamb.com/craigstuntz" target="_blank">Craig Stuntz</a> had an answer at <a href="http://www.stackoverflow.com" target="_blank">The O</a> that gave some light to the situation:</p>
<blockquote><p>context.SiteUser is an property of type ObjectQuery. When you execute an ObjectQuery, it will always hit the backing store. That's what they do. If you don't want to execute a database query, then don't use an ObjectQuery.</p></blockquote>
<p>Furthermore I could use GetObjectByKey:</p>
<blockquote><p>GetObjectByKey tries to retrieve an object that has the specified EntityKey from the ObjectStateManager. If the object is currently not loaded into the object context, a query is executed in an attempt to return the object from the data source.</p></blockquote>
<p>Which actually seems to me like how it should work naturally. After all, if it's in the context and I am positive I don't want to update the <a href="http://byatool.com/index.php/lessons/entity-framework-concurrency-mode-and-fun-observations" target="_blank">object from changes in the database</a>, wouldn't it make sense to not bother with the database at all? Seems like a wasted action. Again, I am guessing that the reason it does this is that it's an all or nothing thing. It either does it all the time (IE query no matter the reason) or never. Grey area just doesn't seem to fit Entity Framework design in this matter.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/entity-framework-querying-issue-follow-up/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Framework: Concurrency Mode and fun observations</title>
		<link>http://byatool.com/lessons/entity-framework-concurrency-mode-and-fun-observations/</link>
		<comments>http://byatool.com/lessons/entity-framework-concurrency-mode-and-fun-observations/#comments</comments>
		<pubDate>Wed, 18 Feb 2009 21:52:29 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=478</guid>
		<description><![CDATA[Ok so you have this thing that you want to do and it involved stuff. And when you do that stuff you want something to happen. And when that happens you want to know that it happened and tell someone, "Hey I did stuff and something happened." That, in essence, is what Concurrency Mode is [...]]]></description>
			<content:encoded><![CDATA[<p>Ok so you have this thing that you want to do and it involved stuff. And when you do that stuff you want something to happen. And when that happens you want to know that it happened and tell someone, "Hey I did stuff and something happened." That, in essence, is what Concurrency Mode is for provided all this had to do with the Entity Framework and updating records.</p>
<p>Concurrency Mode allows you to make sure that nothing has changed in the database before or during the current save. Basically it checks the database to make sure the record being updated still is in the same condition it was when you loaded it to the context. If it isn't, then an exception is thrown. (Maybe not the way I would prefer handling this situation, but hey I don't work for the M) How do I get this to happen? Well it's a pretty easy change, though it has an annoying short coming. First the change.</p>
<p>Open up the model browser (IE double click on the .edmx file) and select any property on any entity. Then view the properties.</p>
<pre><img title="concurencymode" src="http://byatool.com/wp-content/uploads/2009/02/concurencymode.jpg" alt="concurencymode" width="372" height="238" /></pre>
<p>And in the image you can see that there is a property surprisingly named "Concurrency Mode" and there are two options: Fixed and None. Guess which one I'm talking about in this post.</p>
<p>Now if I just left you with that, you'd have everything you need to know and you wouldn't waste the next minute you're going to waste on my findings. Good thing you aren't smart enough to walk away.</p>
<p>You might wonder how the Entity Framework is able to do that, after all even I did and as we all know, I am genius.<br />
Say you have a User entity where the UserName and MainEmail properties had Fixed Concurrency. Now suppose the old values of these were 'oldValue' and you just changed them (UI Side) to 'HIHIHI'. At this point you want to save the changes. Well if you use profiler and a watch as it saves, you'll see something like this:</p>
<pre><span style="color: #0000ff;">exec</span> sp_executesql
<span style="color: #800000;">N'update [TIDBA].[TI_USER]
set
  [MainEmail] = @0,
  [UserName] = @1
where
  ((([UserID] = @2)
</span><span style="color: #800000;">and
  ([MainEmail] = @3))
and
  ([UserName] = @4))
'</span>,N<span style="color: #800000;">'@0 nchar(6),
@1 varchar(6),
@2 int,
@3 nchar(6),
@4 varchar(6)'</span>,
@0=N<span style="color: #800000;">'HIHIHI'</span>,
@1=<span style="color: #800000;">'HIHIHI'</span>,
@2=1,
@3=N<span style="color: #800000;">'oldValue'</span>,
@4=<span style="color: #800000;">'oldValue'</span></pre>
<p>Which cleans up into:</p>
<pre><span style="color: #0000ff;">update</span> [TIDBA].[TI_USER]
<span style="color: #0000ff;">set</span>
  [MainEmail] = <span style="color: #800000;">'HIHIHI'</span>,
  [UserName] = <span style="color: #800000;">'HIHIHI'</span>
<span style="color: #0000ff;">where</span>
  ((([UserID] = 1)
<span style="color: #0000ff;">and</span>
  ([MainEmail] = <span style="color: #800000;">'oldValue'</span>))
<span style="color: #0000ff;">and</span>
  ([UserName] = <span style="color: #800000;">'oldValue'</span>))</pre>
<p>As you can see, the Entity Framework matches the originally loaded values against the database (Only on Fixed Concurrency properties) and sees if it can find a record. If it can't, it means those values have changed. The exception follows.</p>
<p>Now besides the exception part (A bit much but can be handled), the only annoying thing is that you have to do this property by property. I don't see a way yet to make it standard for the entire entity. Such is life.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/entity-framework-concurrency-mode-and-fun-observations/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Entity Framework: Odd things during querying</title>
		<link>http://byatool.com/lessons/entity-framework-odd-things-during-querying/</link>
		<comments>http://byatool.com/lessons/entity-framework-odd-things-during-querying/#comments</comments>
		<pubDate>Mon, 16 Feb 2009 21:13:31 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=457</guid>
		<description><![CDATA[So in THIS POST I talked about how querying worked on a conceptual level but turns out there is something going on that's not expected. Remember how I said that if the object is in the context, the database won't be hit? Turns out that isn't true to an extent. With the help of profiler, [...]]]></description>
			<content:encoded><![CDATA[<pre><img title="serverdatabasehitit1" src="http://byatool.com/wp-content/uploads/2009/02/serverdatabasehitit1.jpg" alt="serverdatabasehitit1" width="453" height="255" /></pre>
<p>So in <a href="http://byatool.com/index.php/lessons/entity-framework-concepts-and-headaches-querying" target="new">THIS POST</a> I talked about how querying worked on a conceptual level but turns out there is something going on that's not expected.  Remember how I said that if the object is in the context, the database won't be hit?  Turns out that isn't true to an extent.  With the help of profiler, I found outconfusing thing or two, and neither have to do with why <a href="http://www.cnn.com/2009/LIVING/worklife/02/13/careereoki/index.html" target="new">this is was on the front page of CNN</a>.</p>
<p>Say you for some reason want to select a user like so:</p>
<pre>    <span style="color: #008080;">SiteUser</span> someUser = context.SiteUser.First(role =&gt; role.UserID == 1);</pre>
<p>WOW THAT IS NEW AND AMAZING!!!117!</p>
<p>Right off the bat, I bet you can guess what happens. If not (You know, if you didn't read <a href="http://byatool.com/index.php/lessons/entity-framework-concepts-and-headaches-querying" target="new">THIS POST</a> or you have difficulties with revolving doors), here's the idea in script form:</p>
<pre>            CONTEXT
    Am I having this Object?

Context looks into its bag, notices it doesn't have the object,
and then looks over at Database with confused look.

            DATABASE
   No but I gots it for you.

Database hands object to Context.  Context looks happy.

            CONTEXT
  I has a object now.</pre>
<p>At this point, two things are obvious: I've lost it and Context now has a User with an UserID of one and it got this by querying the database.   Now suppose for no real reason you want the same user. (Assume it is the same context and the user is already in the context.)</p>
<pre>            CONTEXT
    Am I having this Object?

Context looks into his bag and pulls out the object.  Database walks over.

           CONTEXT
    You has object?

            DATABASE
   Yes but I gots it for you.

Database hands object to Context.  Context doesn't take it.

            CONTEXT
  I has it already.</pre>
<p>So in this stunning display, we can see that even though the context already has the user, it still asks the database for the thing. How do I know this? Well I used profiler on both statements. What I thought would happen is on the first eh First it would hit the database, hydrate the object, and go on its merry. Second First would just grab it from the context and give it to me. Fact is, it STILL HITS THE DATABASE. Now the next possible idea is that it's going to the database to see if the record has changed and then will update the object with any changes EXCEPT what has been changed on the object. Yeah not so much. (Although there is a way you can force that, but I'll post that in the next post) Fact is, it really doesn't do anything with it as long as you have the default settings. In fact, (FACT FACT FACT FACT) the default settings say that:</p>
<pre>Objects that already exist in the object context are not loaded from the data source.
This is the default behavior for queries or when calling the Load method on an
EntityCollection&lt;(Of &lt;(TEntity&gt;)&gt;).</pre>
<p>Seems kind of odd that by default something in the context will not be loaded if it's already there but it still hits the database regardless. So what this default really means is that it may or may not hit the database, but any changes in the database will not be reflected in the object. It really doesn't mean that the database won't be queried. Seems kind of odd.</p>
<p>What not good enough?  Fine, <a href="http://www.cnn.com/2009/US/02/16/texas.sky.debris/index.html" target="_blank">figure this out.</a></p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/entity-framework-odd-things-during-querying/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Framework: Concepts and Headaches.  Querying</title>
		<link>http://byatool.com/lessons/entity-framework-concepts-and-headaches-querying/</link>
		<comments>http://byatool.com/lessons/entity-framework-concepts-and-headaches-querying/#comments</comments>
		<pubDate>Thu, 12 Feb 2009 15:37:27 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=454</guid>
		<description><![CDATA[So in the first part of this life changing tutorial, I explained what lazy loading was and how it worked with the Entity Framework. Now I wanted to get into querying/loading and how it's handled. At least at a very simplistic angle. (Simplistic is what I do best. Day-oh!) Something that has to be understood [...]]]></description>
			<content:encoded><![CDATA[<p>So in the<a href="http://byatool.com/index.php/general-coding/entity-framework-concepts-and-headaches-lazy-loading" target="_blank"> first part</a> of this life changing tutorial, I explained what lazy loading was and how it worked with the Entity Framework. Now I wanted to get into querying/loading and how it's handled.  At least at a very simplistic angle.  (Simplistic is what I do best.  Day-oh!)  Something that has to be understood is how the Entity Framework handles the hydrating/loading of objects and how it relates to the ObjectContext.  Say you have the same User/Site example from the<a href="http://byatool.com/index.php/general-coding/entity-framework-concepts-and-headaches-lazy-loading" target="_blank"> first part</a> and you load a site:</p>
<pre>    <span style="color: #0000ff;">using</span>(<span style="color: #008080;">SomeEntities</span> context = new <span style="color: #008080;">SomeEntities</span> ())
    {
       <span style="color: #008000;">//where SomeEntities  : ObjectContext</span>
       <span style="color: #008080;">Site</span> neededSite = context.Site.Where(site =&gt; site.ID = siteID);
    }</pre>
<p>Ok so what happens here? Well basically the context will check itself to see if it holding said Site and if it isn't, it will grab it from the database. This doesn't seem like a big deal since it's pretty obvious it won't have the given Site yet since the context was just created. Now let's get a silly example going for the sake of learning.</p>
<pre>    <span style="color: #0000ff;">using</span>(<span style="color: #008080;">SomeEntities</span> context = <span style="color: #0000ff;">new</span> <span style="color: #008080;">SomeEntities</span> ())
    {
       <span style="color: #008000;">//where SomeEntities  : ObjectContext</span>
       <span style="color: #008080;">Site</span> neededSite = context.Site.Where(site =&gt; site.ID = siteID);
       neededSite.SiteName = someString;

       <span style="color: #0000ff;">if</span>(context.Site.Any(site =&gt; siteName == neededSite.SiteName))
       {
          <span style="color: #008000;">//return error since the name already exists in the table.</span>
       }

    }</pre>
<p>Now as it is, this doesn't seem too bad right? I change the name of the site and then see if that name is taken already in the database. If these seems ok to you it just means you don't yet understand how the Entity Framework eh... works. The first time you go to get the Site, it fills it's Site list with the Sites from the database, then checks the list for the one you want. It will then proceed to give you a reference to the Site in that list. Next time you do a query on the Sites list, it will NOT query the database but rather it will just query the Sites list it has in memory. Next, the line:</p>
<pre>    neededSite.SiteName = someString;</pre>
<p>Is updating the object in that list. Now you would think (If you are used to say not caching results from database queries) that the next query:</p>
<pre>    context.Site.Any(site =&gt; siteName == neededSite.SiteName)</pre>
<p>Would hit the database again and check the items there and make sure that SiteName doesn't exist. But far as Entity Framework is concerned it already loaded that list, so it doesn't need to hit the database again. This is good to save the performance hit of getting from the database but dangerous if you don't understand this. Fact is, the context is just going to look at it's cached list of Sites and run that query and guess what's in that list? The object that you just changed. So basically that query will compare the object to itself at some point as it iterates through the list and yee haw it will find a Site that already has that SiteName... the one you just changed. Solution?</p>
<p>You can include the SiteID in the query:</p>
<pre>    context.Sites
            .Any(
                  site =&gt; siteName == neededSite.SiteName
                  &amp;&amp; site.SiteID != neededSite.SiteID
                 )</pre>
<p>This way you know that you won't compare the same object to itself.</p>
<p>OR You can create a new context if you really want to get a fresh look at the database. This will allow you to have a context with the new changes and a context pre changes so you can be sure you are comparing the object to a list without it.</p>
<p>Now you might look down the list of methods on the context and see the Refresh method. This might be temping because you might think that a refresh would give you what you want, a completely new list to compare against. There are two ways you can handle this:</p>
<pre>     context.Refresh(<span style="color: #008080;">RefreshMode</span>.Store, context.Site);</pre>
<p>Seems like this would be good since it basically means I want to completely restore the list from the database and clear out any changes I made in the list. Oh wait, what was that? " clear out any changes I made in the list". This means those changes we made to the object, yeah gone. So now the:</p>
<pre>    context.Sites
           .Any(
                  site =&gt; siteName == neededSite.SiteName
                  &amp;&amp; site.SiteID != neededSite.SiteID
                )</pre>
<p>Query is hosed because the neededSite.SiteName has been reverted to whatever was in the database originally.</p>
<p>You could try this:</p>
<pre>     context.Refresh(<span style="color: #008080;">RefreshMode</span>.ClientWins, context.Site);</pre>
<p>In which any changes made to the objects will overwrite any information being brought in from the database. Hmm, 6 of one and a half dozen of the other. This just brings us back to the same problem. The list will still contain the changes to the object and therefore we will once again compare the object to itself.</p>
<p>Now you might think that maybe you should just check the list BEFORE applying the changes to the object, and that would be a good way of going about it:</p>
<pre>    <span style="color: #0000ff;">using</span>(<span style="color: #008080;">SomeEntities</span> context = <span style="color: #0000ff;">new</span> <span style="color: #008080;">SomeEntities</span> ())
    {
       <span style="color: #008000;">//where SomeEntities  : ObjectContext</span>
       <span style="color: #008080;">Site</span> neededSite = context.Site.Where(site =&gt; site.ID = siteID);

       <span style="color: #0000ff;">if</span>(context.Site.Any(site =&gt; siteName == someString))
       {
          <span style="color: #008000;">//return error since the name already exists in the table.</span>
       }
       <span style="color: #0000ff;">else</span>
       {
          neededSite.SiteName = someString;
          <span style="color: #008000;">//Continue or save</span>
       }
    }</pre>
<p>This would work since you are checking the list before the object has been changed. This might work if you do your saving in the same layer that you have your UI, but if you do something like this:</p>
<pre>    ...
    <span style="color: #008080;">Site</span> someSite = <span style="color: #008080;">Site</span>.GetSiteById(id);
    someSite.SiteName = txtSiteName.Text;
    someSite.Save();
    ...</pre>
<p>In this example, I have created a Save method on the Site object that will take care of validation and saving all in one. It also means that I either am sharing a context between the GetSiteId method and the Save method, or that I am using two contexts. If it's the latter, then it won't matter since the context in the Save method will not "own" the current someSite object. (And therefore will not have the changes to the someSite object reflected in its list) However, if they do share the same context then you will run into the above problem.</p>
<p>In the next post, I'll talk about how to share a context... which I won't try to sell you as the right thing to do.  Just something to think about.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/entity-framework-concepts-and-headaches-querying/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Framework: Concepts and headaches. Lazy Loading</title>
		<link>http://byatool.com/lessons/entity-framework-concepts-and-headaches-lazy-loading/</link>
		<comments>http://byatool.com/lessons/entity-framework-concepts-and-headaches-lazy-loading/#comments</comments>
		<pubDate>Thu, 12 Feb 2009 14:32:35 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=447</guid>
		<description><![CDATA[So when I wrote this and this I didn't really have a precursor to some of the concepts in the posts so I figured I'd get them out of the way now since I'll be posting a bunch on the Entity Framework. First off is lazy loading. Now I could put the obligatory stupid joke [...]]]></description>
			<content:encoded><![CDATA[<p>So when I wrote <a href="http://byatool.com/index.php/lessons/entity-framework-objectcontext-observations-on-caching" target="_blank">this</a> and <a href="http://byatool.com/index.php/lessons/entity-framework-many-to-one-property-and-how-to-load" target="_blank">this</a> I didn't really have a precursor to some of the concepts in the posts so I figured I'd get them out of the way now since I'll be posting a bunch on the Entity Framework.</p>
<p>First off is lazy loading. Now I could put the obligatory stupid joke here that gives some kind of novel, but incorrect, explanation of the phrase (Like say making someone else wash your clothes) but I so much better than that. So what is lazy loading? Simply put it's not getting something until you need it. Kind of like "If it ain't broke then don't fix it" instead you trade "broke" with "needed" and "fix" with "get". So it's really not like that phrase. It is however, when talking about objects being hydrated (ie loaded) from some kind of storage (ie database) in a program written by some idiot. (ie me) Let's say you have a User table and a Site table in which there are many Users to one Site. Now with an ORM this will be represented by an User object, a Site object, and a property on User that is of type Site. It would look something like this:</p>
<pre>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">User</span>
    {
      <span style="color: #0000ff;">private</span> <span style="color: #008080;">Site</span> _site = <span style="color: #0000ff;">null</span>;

      <span style="color: #0000ff;">public</span> <span style="color: #008080;">Site</span> ParentSite
      {
         <span style="color: #0000ff;">get</span>
         {
            <span style="color: #0000ff;">if</span>(_site == <span style="color: #0000ff;">null</span>)
            {
               _site = SomeMethodToGetSite();
            }

            <span style="color: #0000ff;">return</span> _site;
         }
      }
    }</pre>
<p>When you load the User from storage, initially the Site object on the User object is null. This is done because if you don't need the Site yet, why take up space until you do? This is the concept of lazy loading. Now in most ORMs, the Site would automatically be hydrated the first time the Site property was accessed. Entity Framework is slightly more complicated when dealing with the many to many or one to many situation.</p>
<p>This happens when you have a Users list on the Site object that basically represents every User in the User table that has the same SiteID as the Site in question. OR maybe you have a hanging table UserSite that allows for one Site to have many Users and one User to have many Sites. Either way, you will be left with a collection that represents this relationship. (Users list on the Site object) Now say you do this:</p>
<pre>  <span style="color: #008080;">Site</span> someSite = LoadSiteByID(siteID);</pre>
<p>and then you try to do this:</p>
<pre>  someGrid.DataSource = someSite.Users;
  someGrid.DataBind();</pre>
<p>When the page loads, there are no records in the grid. In a normal ORM this wouldn't be a problem. It would see that you are accessing the .Users property and hit the database to fill the list. Entity Framework requires you to take one more step in this case.</p>
<pre>  someGrid.DataSource = someSite.Users.Load();</pre>
<p>Not that big of a deal. Now there is a check even to see if it is loaded in the first place:</p>
<pre>  order.Users.IsLoaded</pre>
<p>This is a boolean property that says true when it has been loaded. Next post I'll hit on what happens when you query and how that relates to this situation.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/entity-framework-concepts-and-headaches-lazy-loading/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Framework: ObjectContext observations on caching</title>
		<link>http://byatool.com/lessons/entity-framework-objectcontext-observations-on-caching/</link>
		<comments>http://byatool.com/lessons/entity-framework-objectcontext-observations-on-caching/#comments</comments>
		<pubDate>Tue, 10 Feb 2009 15:53:33 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=433</guid>
		<description><![CDATA[I thought that my journey with the Entity Framework was going to be like falling off a cliff, fast and painless but instead it's been more like driving a Hummer in a Smart car convention, just have to plow my way through. The latest bump in my path has been the ObjectContext. Just to let [...]]]></description>
			<content:encoded><![CDATA[<p>I thought that my journey with the Entity Framework was going to be like falling off a cliff, fast and painless but instead it's been more like driving a Hummer in a Smart car convention, just have to plow my way through.</p>
<p>The latest bump in my path has been the ObjectContext.  Just to let it be known, I'm like most kids with a new game, I don't bother to read the instructions and the throw the controller when I don't have a clue what I'm doing.  My use of the Entity Framework has been no different.  So using "o' skool" standards, I immediately decided that I would have some kind of Singleton context so that I didn't keep making new ones, and assumedly new connections.  Everything seemed fine and dandy until <a title="http://byatool.com/index.php/uncategorized/entity-framework-many-to-one-property-and-how-to-load" href="http://" target="_blank">I hit this</a> situation which brought some, at the time, unexplainable or difficult issues.</p>
<p>First off, say you have a Site and Role class, and Role is Many to One with Site.  Now let's say you are creating a page that is used to create/update/delete roles.  On this page you have the usual section for updating or creating a new role that involves a Name for the Role and a drop down list to pick a Site from.  Now on the update side of it you have basic rules:  The Role must have a name, the Role must have a Site, and the Name of the Role can't already exist in the database for the site.  So a new role might look like:</p>
<pre>  <span style="color: #008080;">Role</span> editRole = Role.GetByID(someID);
  editRole.RoleName = txtRoleName.Text;
  editRole.Site = GetSiteFromID(ddlSite.SelectedValue.ConvertTo&lt;<span style="color: #008080;">Int32</span>&gt;);</pre>
<p>The GetByID is just a query that gets the Role by and ID by using the Singleton ObjectContext. (KEY POINT) Beyond that, nothing special except my <a title="http://byatool.com/index.php/utilities/duck-typing-my-way-to-a-universal-string-convert" href="http://" target="_blank">awesome string convert. Yah.</a> Now the next step before committing to the database is something like:</p>
<pre>  <span style="color: #0000ff;">if</span>
  (
    context.Any
    (
      role =&gt; role.Name == editRole.RoleName
      &amp;&amp; role.Site == editRole.Site
    )
  )
  {
     <span style="color: #008000;">//return error or whatever</span>
  }</pre>
<p>So right there I'm checking to see if the new name for the role exists already. Now say I'm updating a role and that I KNOW the new name doesn't exist. You would think that query would return false and life would be good. Unfortunately two things happened... and they will change your life forever.  (EDIT:  I realize I could also check to make sure the ID doesn't match and should do that, but if I had done that initially I wouldn't have figured out the next part)</p>
<p>First:</p>
<p>I got back an error saying the name already exists. Now as I said, I know it didn't so how could that happen? Well remember that Singleton ObjectContext idea? First time I grab the Role, it doesn't exist in the ObjectContext.Role list. So it grabs it from the database and then stores it so that every time I now run that GetByID method, I am actually getting the object from the context NOT THE PERSISTENCE LAYER. (IE database or whatever) Therefore, any changes I make are changes to the object in that context. So what does that mean? Well say I do update the RoleName on that object and then run a query to see if that name exists, guess where that query is looking? Yup the context. And since it's looking at the same stupid object I just changed, of course the name is going to exist now. Basically I comparing the object to itself to see if it's name exists. Ouch.</p>
<p>B:</p>
<p>After cancelling, (IE not saving) The grid that I had displaying all the Roles now has that new RoleName in it. What the f? My code specifically says NOT to save unless that (name already exists) query returns false. So how the hell has the name changed? Well just like before, the query that gets the list of Roles is no longer looking at the database but now at the Roles list in the context. That same Roles list that has the Role I changed earlier. Therefore any change to that object will now be reflected when getting the list from the context. Uhg.</p>
<p>So what can you learn about this? Once a list is "loaded" for the first time, it is held in the context until (presumably) you use the Refresh method on the context to refresh the given list. (Not sure how well this works). Therefore, any queries after the first will reflect all changes to the objects in the context, whether you saved to the database or not. The Singleton idea isn't looking real great right now.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/entity-framework-objectcontext-observations-on-caching/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Framework: Many to One property and how to load</title>
		<link>http://byatool.com/lessons/entity-framework-many-to-one-property-and-how-to-load/</link>
		<comments>http://byatool.com/lessons/entity-framework-many-to-one-property-and-how-to-load/#comments</comments>
		<pubDate>Mon, 09 Feb 2009 17:54:03 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=430</guid>
		<description><![CDATA[Ok so this is the situation, you've just stolen 50 billion dollars from various wealthy people using a ponzi scheme and you've been caught. What do you do? I have no idea but if that's your situation and you've ended up at this site, I'm guessing your escape route has something to do with the [...]]]></description>
			<content:encoded><![CDATA[<p>Ok so this is the situation, you've just stolen 50 billion dollars from various wealthy people using a ponzi scheme and you've been caught.  What do you do?   I have no idea but if that's your situation and you've ended up at this site, I'm guessing your escape route has something to do with the Entity Framework and how to load a many to one relationship.  Or maybe you're just interested in the latter anyhow. </p>
<p>So here's the problem I ran into the other day.  I have a Site table and a Role table, and every Role record has a SiteID (Foreign Key) that the Entity Map represents in a property.  (Site Class)  Now, when I "hydrate" a Role, the Site property is null.  This is because Entity Framework, in a round about way, supports lazy loading sort of.  (Lazy Loading meaning that any relationship, be it a Site object on a Role or say a Users list on a Role, will not be loaded at the time you "hydrate" the main object and will only be loaded when the property is accessed.)  So it makes sense that the Site object exposed by the property is not loaded yet because I haven't accessed the property. </p>
<p>With the Entity Framework, and one to many relationships (Say a Users list on a Role object) you have to not only access the property, but you have use the Load method to make sure it gets loaded:</p>
<pre>    <span style="color: #0000ff;">from</span> user <span style="color: #0000ff;">in</span> someRole.Users.Load()</pre>
<p>Well with a many to one relationship (Many Roles to one Site) this is a propblem since the Site property returns only a single Site:</p>
<pre>    someRole.Site.Load(); <span style="color: #008000;">//Boom, not possible</span></pre>
<p>Load can't be used since Site isn't a collection. So how the hell do I load this stupid thing? Well that has to be done in the query itself. Kind of annoying:</p>
<pre>    context.Role.Include(<span style="color: #800000;">"Site"</span>).Where(someClause).ToList();</pre>
<p>As you can see, in that query I had to add the Include method and the value is actually the property name. Now when I look at the list of roles returned, the roles now have the Site property loaded. As I said, kind of annoying, but there is something interesting about these relationships that I'll post about next.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/entity-framework-many-to-one-property-and-how-to-load/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Beyond the wall</title>
		<link>http://byatool.com/lessons/beyond-the-wall/</link>
		<comments>http://byatool.com/lessons/beyond-the-wall/#comments</comments>
		<pubDate>Tue, 02 Sep 2008 13:41:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Func]]></category>
		<category><![CDATA[Select]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/09/02/beyond-the-wall/</guid>
		<description><![CDATA[So I never gave a solution to this problem and thought I might do that real fast. If you recall, this was the main sticking point of creating a Func for a select clause: Func&#60;User, EHH??&#62; selectUserID = currentUser =&#62; new { currentUser.ID, currentUser.UserName }; Well there is no one solution to this, but there [...]]]></description>
			<content:encoded><![CDATA[<p>So I never gave a solution to<a href="http://byatool.blogspot.com/2008/08/and-then-you-hit-wall.html"> this problem</a> and thought I might do that real fast.</p>
<p>If you recall, this was the main sticking point of creating a Func for a select clause:</p>
<pre><span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">EHH??</span>&gt; selectUserID = currentUser =&gt;  <span style="color: #3333ff;">new</span> { currentUser.ID, currentUser.UserName };</pre>
<p>Well there is no one solution to this, but there is an easy and clean solution:</p>
<pre> <span style="color: #3333ff;">public</span> <span style="color: #3333ff;">class</span> UserQueryItem
 {
   <span style="color: #3333ff;">public</span> UserQueryItem ( <span style="color: #00cccc;">Int32</span> userID, <span style="color: #00cccc;">String</span> userName )
   {
      UserID = userID;
      UserName = userName;
   }

   <span style="color: #3333ff;">public</span> <span style="color: #00cccc;">Int32</span> UserID { <span style="color: #3333ff;">get</span>; <span style="color: #3333ff;">set</span>; }
   <span style="color: #3333ff;">public</span> <span style="color: #00cccc;">String</span> UserName { <span style="color: #3333ff;">get</span>; <span style="color: #3333ff;">set</span>; }
 }</pre>
<p>Create a class to hold the information.</p>
<pre> <span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">UserQueryItem</span>&gt; selectUserID = currentUser =&gt;  <span style="color: #3333ff;">new</span> <span style="color: #00cccc;">UserQueryItem</span> { UserID = currentUser.ID, UserName = currentUser.UserName };</pre>
<p>Or</p>
<pre>
 <span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">UserQueryItem</span>&gt; selectUserID = currentUser =&gt;  <span style="color: #3333ff;">new</span> <span style="color: #00cccc;">UserQueryItem</span> (currentUser.ID, currentUser.UserName);</pre>
<p>Pretty simple, just a little more work.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/pontification/what-is-readable/" title="What Is Readable">What Is Readable</a></li><li><a href="http://byatool.com/general-coding/linq-extension-methods-versus-linq-query-language-deathmatch/" title="Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH">Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH</a></li><li><a href="http://byatool.com/general-coding/uhg-it-wont-end/" title="Uhg It Won&#8217;t End">Uhg It Won&#8217;t End</a></li><li><a href="http://byatool.com/pontification/what-is-readable-addon/" title="What Is Readable Addon">What Is Readable Addon</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/beyond-the-wall/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
