<?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>Blog</title>
	<atom:link href="http://www.binaryforge-software.com/wpblog/Index.php?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://www.binaryforge-software.com/wpblog</link>
	<description></description>
	<lastBuildDate>Fri, 18 May 2012 14:40:25 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Doubleclick tags &#8211; how it works</title>
		<link>http://www.binaryforge-software.com/wpblog/?p=181</link>
		<comments>http://www.binaryforge-software.com/wpblog/?p=181#comments</comments>
		<pubDate>Fri, 18 May 2012 14:40:25 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Web Design]]></category>

		<guid isPermaLink="false">http://www.binaryforge-software.com/wpblog/?p=181</guid>
		<description><![CDATA[Quite note, more to myself really, about how Doubleclick ad tagging works. &#8211; ad set up in DFP &#8211; targetingcriteria set using various key-value pairs &#8211; server side calls marketing service provider web service to get data about customer, passing in user ID from cookie &#8211; server side component written to dynamically generate javascript code; [...]]]></description>
			<content:encoded><![CDATA[<p>Quite note, more to myself really, about how Doubleclick ad tagging works.</p>
<p> &#8211; ad set up in DFP<br />
 &#8211; targetingcriteria set using various key-value pairs</p>
<p> &#8211; server side calls marketing service provider web service to get data about customer, passing in user ID from cookie<br />
 &#8211; server side component written to dynamically generate javascript code; this javascript code contains the dynamic key-value pairs &#8211; this js code is along the lines of ad.doubleclick.net/gender=m<br />
 &#8211; when javascript code runs, it injects html via document.write(&#8216;&#8230;the ad content&#8230;&#8217;)<br />
 &#8211; html displays the actual ad</p>
]]></content:encoded>
			<wfw:commentRss>http://www.binaryforge-software.com/wpblog/?feed=rss2&#038;p=181</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>HTTP Slow Vulnerability</title>
		<link>http://www.binaryforge-software.com/wpblog/?p=179</link>
		<comments>http://www.binaryforge-software.com/wpblog/?p=179#comments</comments>
		<pubDate>Thu, 19 Apr 2012 11:18:08 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://www.binaryforge-software.com/wpblog/?p=179</guid>
		<description><![CDATA[A relatively new vulnerability is the appropriately named HTTP slow attack that exploits how HTTP works. HTTP slow vulnerability is a DDos attack based on the way HTTP works. HTTP will only process requests once it has received a full header. If an attacker sends this in chunks over a large period of time then [...]]]></description>
			<content:encoded><![CDATA[<p>A relatively new vulnerability is the appropriately named HTTP slow attack that exploits how HTTP works.</p>
<p>HTTP slow vulnerability is a DDos attack based on the way HTTP works.  HTTP will only process requests once it has received a full header.  If an attacker sends this in chunks over a large period of time then they can open multiple connections and time out the web server, blocking genuine requests going through.  There are 2 main changes advised:</p>
<p>  Set a minimum HTTP header length in IIS – this will ensure that HTTP header requests have to be AT LEAST x bytes<br />
  Reduce the maximum server request length (in seconds) </p>
<p>Of course, adjusting these values to extremes could result in legitimate requests being rejected, so there is no magic value to set.  The only way to figure this out for sure is to measure, over a period of time, what are acceptable boundaries and set accordingly.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.binaryforge-software.com/wpblog/?feed=rss2&#038;p=179</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Multiple submit buttons in a single ASP.NET MVC Form</title>
		<link>http://www.binaryforge-software.com/wpblog/?p=173</link>
		<comments>http://www.binaryforge-software.com/wpblog/?p=173#comments</comments>
		<pubDate>Mon, 16 Apr 2012 16:08:23 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[ASP.NET]]></category>

		<guid isPermaLink="false">http://www.binaryforge-software.com/wpblog/?p=173</guid>
		<description><![CDATA[Thanks to Andrey Shchekin for this, copied below in case his blog disappears. public class HttpParamActionAttribute : ActionNameSelectorAttribute { public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo) { if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase)) return true; if (!actionName.Equals("Action", StringComparison.InvariantCultureIgnoreCase)) return false; var request = controllerContext.RequestContext.HttpContext.Request; return request[methodInfo.Name] != null; } } How to use it? Just have [...]]]></description>
			<content:encoded><![CDATA[<p>Thanks to <a href="http://blog.ashmind.com/2010/03/15/multiple-submit-buttons-with-asp-net-mvc-final-solution/">Andrey Shchekin</a> for this, copied below in case his blog disappears.</p>
<pre language="csharp">
public class HttpParamActionAttribute : ActionNameSelectorAttribute {
    public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo) {
        if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
            return true;

        if (!actionName.Equals("Action", StringComparison.InvariantCultureIgnoreCase))
            return false;

        var request = controllerContext.RequestContext.HttpContext.Request;
        return request[methodInfo.Name] != null;
    }
}
</pre>
<p>How to use it? Just have a form similar to this:</p>
<pre language="xml">
<% using (Html.BeginForm("Action", "Post")) { %>
  <!— …form fields… -->
<input type="submit" name="saveDraft" value="Save Draft" />
<input type="submit" name="publish" value="Publish" />
<% } %>
</pre>
<p>and controller with two methods</p>
<pre language="csharp">
public class PostController : Controller {
    [HttpParamAction]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult SaveDraft(…) {
        //…
    }

    [HttpParamAction]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Publish(…) {
        //…
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.binaryforge-software.com/wpblog/?feed=rss2&#038;p=173</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MVC Mailer and Specified Pickup Directory</title>
		<link>http://www.binaryforge-software.com/wpblog/?p=169</link>
		<comments>http://www.binaryforge-software.com/wpblog/?p=169#comments</comments>
		<pubDate>Mon, 16 Apr 2012 16:06:05 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[ASP.NET]]></category>

		<guid isPermaLink="false">http://www.binaryforge-software.com/wpblog/?p=169</guid>
		<description><![CDATA[MVC Mailer will complain about SMTP settings, even when using SpecifiedPickupDirectory settings that appear that they should work. The following code snippet will work with MVC Mailer: &#60;smtp from=&#34;some-email@gmail.com&#34; deliveryMethod=&#34;SpecifiedPickupDirectory&#34;&#62; &#60;network host=&#34;localhost&#34; /&#62; &#60;specifiedPickupDirectory pickupDirectoryLocation=&#34;c:\temp\&#34;/&#62; &#60;/smtp&#62;]]></description>
			<content:encoded><![CDATA[<p>MVC Mailer will complain about SMTP settings, even when using SpecifiedPickupDirectory settings that appear that they should work.</p>
<p>The following code snippet will work with MVC Mailer:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;smtp</span> <span style="color: #000066;">from</span>=<span style="color: #ff0000;">&quot;some-email@gmail.com&quot;</span> <span style="color: #000066;">deliveryMethod</span>=<span style="color: #ff0000;">&quot;SpecifiedPickupDirectory&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;network</span> <span style="color: #000066;">host</span>=<span style="color: #ff0000;">&quot;localhost&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;specifiedPickupDirectory</span> <span style="color: #000066;">pickupDirectoryLocation</span>=<span style="color: #ff0000;">&quot;c:\temp\&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/smtp<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.binaryforge-software.com/wpblog/?feed=rss2&#038;p=169</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>mySQL Entity Framework driver and LazyLoading problem</title>
		<link>http://www.binaryforge-software.com/wpblog/?p=163</link>
		<comments>http://www.binaryforge-software.com/wpblog/?p=163#comments</comments>
		<pubDate>Sat, 14 Apr 2012 11:22:51 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.binaryforge-software.com/wpblog/?p=163</guid>
		<description><![CDATA[Just experienced an issue with the Entity Framework driver for mySQL &#8211; it appears that simple operations such as iterating over a lazy loaded list will result in a &#8220;There is already an open DataReader associated with this Connection which must be closed first&#8221; error. The reason for this is that the mySQL driver does [...]]]></description>
			<content:encoded><![CDATA[<p>Just experienced an issue with the Entity Framework driver for mySQL &#8211; it appears that simple operations such as iterating over a lazy loaded list will result in a &#8220;There is already an open DataReader associated with this Connection which must be closed first&#8221; error.</p>
<p>The reason for this is that the mySQL driver does not support the MultipleActiveResultSets property that SQL Server supports, therefore when iterating over a list containing lazy loaded items the driver attempts to open another connection to fetch the new items and falls over.</p>
<p>Sadly the only way around this is to eager fetch the items, like so:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">var q <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">from</span> t <span style="color: #0600FF; font-weight: bold;">in</span> dc<span style="color: #008000;">.</span><span style="color: #0000FF;">testresults</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Include</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;entity&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Include</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;scheduledtest&quot;</span><span style="color: #008000;">&#41;</span> <span style="color: #0600FF; font-weight: bold;">where</span> t<span style="color: #008000;">.</span><span style="color: #0000FF;">ScheduledTestID</span> <span style="color: #008000;">==</span> scheduledTestID <span style="color: #0600FF; font-weight: bold;">select</span> t<span style="color: #008000;">;</span></pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://www.binaryforge-software.com/wpblog/?feed=rss2&#038;p=163</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jsTestDriver &amp; WebStorm</title>
		<link>http://www.binaryforge-software.com/wpblog/?p=156</link>
		<comments>http://www.binaryforge-software.com/wpblog/?p=156#comments</comments>
		<pubDate>Fri, 13 Apr 2012 15:22:28 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://www.binaryforge-software.com/wpblog/?p=156</guid>
		<description><![CDATA[Following up on the previous post, I was trying to test my new prototype.js based classes without any success. The error I kept getting was &#8220;TypeError: myClass is not a constructor&#8221;. Thanks to the JetBrains community, a fix was at hand quickly. I had to make sure that a test-config.jstd config file was in the [...]]]></description>
			<content:encoded><![CDATA[<p>Following up on the previous post, I was trying to test my new prototype.js based classes without any success.</p>
<p>The error I kept getting was &#8220;TypeError: myClass is not a constructor&#8221;.</p>
<p>Thanks to the JetBrains community, a fix was at hand quickly.</p>
<p>I had to make sure that a test-config.jstd config file was in the root, which loads the prototype.js framework.</p>
<p>The content of this file is:</p>
<p>load:<br />
- prototype.js<br />
- src/myGlobal.js<br />
- src/myClass.js</p>
<p>test:<br />
- test/Test.js</p>
<p>UPDATE: Further work on this revealed a bit of a UI snafu which cost me a bit of time. The above configuration is set on each configuration &#8211; NOTE: FOR EVERY UNIT TEST CREATED THERE IS A NEW CONFIGURATION CREATED.</p>
<p>So sometimes it would run the above configuration, other times it would run the default (where it would be looking for prototype.js in the same folder as the class files).</p>
<p><a href="http://www.binaryforge-software.com/wpblog/wp-content/uploads/2012/04/WebStorm_TestDriver.png"><img src="http://www.binaryforge-software.com/wpblog/wp-content/uploads/2012/04/WebStorm_TestDriver-300x228.png" alt="" title="WebStorm_TestDriver" width="300" height="228" class="alignnone size-medium wp-image-160" /></a></p>
<p>Be careful when running your unit tests and always double check where the config file is pointing to.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.binaryforge-software.com/wpblog/?feed=rss2&#038;p=156</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JS Unit Testing</title>
		<link>http://www.binaryforge-software.com/wpblog/?p=154</link>
		<comments>http://www.binaryforge-software.com/wpblog/?p=154#comments</comments>
		<pubDate>Fri, 13 Apr 2012 14:58:39 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://www.binaryforge-software.com/wpblog/?p=154</guid>
		<description><![CDATA[I&#8217;ve been using the superb WebStorm 4.0 EAP recently, and started to dabble in some JS unit testing, using the jsTestDriver that is integrated with the IDE. On looking at some of the tutorials I found this article. Have copied some of it here for future reference. Automate, automate, automate! By moving from a logging [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been using the <a href="http://www.jetbrains.com/webstorm/">superb WebStorm</a> 4.0 EAP recently, and started to dabble in some JS unit testing, using the jsTestDriver that is integrated with the IDE.</p>
<p>On looking at some of the tutorials I found this <a href="http://msdn.microsoft.com/en-us/magazine/gg655487.aspx">article</a>.</p>
<p>Have copied some of it here for future reference.</p>
<p>Automate, automate, automate!<br />
By moving from a logging based debugging routine to unit testing we have made sure that our experiments are repeatable and self-checking. Doing so takes a lot of manual labour off our backs, but there are still ways to improve. Running the HTML file containing the tests in a browser is fairly painless, but as you might have noticed, today&#8217;s web developers can&#8217;t simply test in a single browser and call it a day. Depending on your environment, you may have to test the 2+ most recent versions of 5+ browsers on 3+ platforms. Suddenly, running that one HTML file is a bit of work.</p>
<p>As mentioned, the test case object above is written for JsTestDriver, a JavaScript testing framework and test runner from Google. What sets JsTestDriver apart from the pack is the way it runs tests. Rather than the standard HTML file to load sources and tests, JsTestDriver runs a server that can help you run tests on multiple browsers all at once. The best way to understand how this works is to see it in action.</p>
<p>Assume that the jQuery plugin lives in src/difference_in_words.jquery.js and the test case lives in test/difference_in_words_test.js. In order to run this test we add a configuration file, jsTestDriver.conf in our project&#8217;s root directory. It contains the following:</p>
<p>server: http://localhost:4224</p>
<p>load:<br />
  &#8211; src/*.js<br />
  &#8211; test/*.js<br />
Now download the latest JsTestDriver jar file. You will need Java installed to use it. Then issue the following command in a shell (if you are on Windows, cmd.exe will do):</p>
<p>java -jar JsTestDriver-1.2.2.jar &#8211;port 4224<br />
You have now started a JsTestDriver server on your machine. The next step is to point a browser to http://localhost:4224/capture which will turn the browser into an idle test running slave. Do this with all the browsers you have available. Then open a new shell, cd into the project directory and issue:</p>
<p>java -jar JsTestDriver-1.2.2.jar &#8211;tests all<br />
After a short while you should see some output indicating that JsTestDriver ran two tests in all available browsers, and show you whether they passed or not. Congratulations, you have just automated testing on multiple browsers! If your machine is reachable from other devices on the network, you can also use this server to test other platforms (OS X, Windows, Linux), your iPhone, Android phone and other mobile devices. And you can verify them all with a single shell command. That is pretty exciting!</p>
<p>JsTestDriver is not your only choice for test automation. If you don&#8217;t like its assertion framework, it can also run tests written using QUnit, YUI Test and Jasmine. Additionally, Yahoo has YETI, a similar tool built specifically for YUI Test, and Nicholas Zakas recently released YUI Test Standalone, which includes a similar runner based on Selenium Web Driver.</p>
<p>Continuous integration<br />
When practicing TDD, we require tight feedback. Feedback comes from our tests, which means that tests need to run effortlessly and fast. JsTestDriver already makes it both easy and fast to run tests, but as always there are limitations. The limitations come in the form of multiple browsers. While JsTestDriver can easily run tests on as many browsers as you want, doing so is inconvenient for the TDD workflow for a couple of reasons:</p>
<p>Having test reports from more than one browser at a time makes it harder to see what&#8217;s happening, and takes away from the momentum TDD is supposed to provide you with.<br />
Some less capable browsers &#8211; which are usually highly important to test &#8211; are slow. And I mean slow. Slow ruins the TDD flow.<br />
One solution to this problem is continuous integration. Continuous integration is the practice of automatically and frequently controlling the quality of your project. This could include tools such as JsLint, and it most definitely should include running tests.</p>
<p>A continuous integration (CI) server can make sure that the work of all developers combined work as intended and it can also be the one in charge of running tests in a wide selection of browsers. A &#8220;build&#8221; on a CI server is usually triggered by version control systems such as Git or Subversion, and will often offer to send emails to project members when it discovers problems.</p>
<p>I recently wrote a guide to setting up the Hudson CI server for JsTestDriver. Using Hudson and JsTestDriver, it&#8217;s easy to build a workflow that is time-efficient and promotes quality.</p>
<p>Personally, I use TDD for basically anything I do, and usually I run tests locally against Firefox, as it is the browser I find to have the best error messages and stack traces. Every time I finish a feature, often a small one, I push it to the code repository. At this point, Hudson checks out the change I just committed and runs all the unit tests on a wide range of browsers. If anything fails, I get an email explaining what happened. Additionally, I can visit the Hudson server anytime to view graphs of the project&#8217;s builds, see console output for individual builds and so on.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.binaryforge-software.com/wpblog/?feed=rss2&#038;p=154</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MVC and TempData</title>
		<link>http://www.binaryforge-software.com/wpblog/?p=143</link>
		<comments>http://www.binaryforge-software.com/wpblog/?p=143#comments</comments>
		<pubDate>Thu, 29 Mar 2012 10:30:44 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.binaryforge-software.com/wpblog/?p=143</guid>
		<description><![CDATA[Couple of gotchas/HOWTOs with TempData: Use TempData when you want to display a notification to a user. When MVC accesses the TempData dictionary, it will delete the corresponding key-value pair. In order to determine if a TempData value has been set, don’t check for null (!) but use ContainsKey. You can’t pass TempData values to [...]]]></description>
			<content:encoded><![CDATA[<p>Couple of gotchas/HOWTOs with TempData:</p>
<p>Use TempData when you want to display a notification to a user. When MVC accesses the TempData dictionary, it will delete the corresponding key-value pair. In order to determine if a TempData value has been set, don’t check for null (!) but use ContainsKey.</p>
<p>You can’t pass TempData values to an HTML Helper, e.g. within a @Html.ActionLink.</p>
<p>To get around this, use a standard a tag and the Url.Action helper, e.g.</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">@if (TempData.ContainsKey(&quot;LatestActionJobID&quot;))
{
&lt;div id=&quot;divLatestAction&quot; class=&quot;info&quot;&gt;
    &lt;h1&gt;
        &lt;a href=&quot;@Url.Action(&quot;Index&quot;, &quot;Job&quot;, new { id = @TempData[&quot;LatestActionJobID&quot;] })&quot;&gt;@TempData[&quot;LatestAction&quot;]&lt;/a&gt;
    &lt;/h1&gt;
    &lt;span class=&quot;close&quot;&gt;X&lt;/span&gt;
&lt;/div&gt;
}</pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.binaryforge-software.com/wpblog/?feed=rss2&#038;p=143</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>N-tier Entity Framework and debugging WCF problems</title>
		<link>http://www.binaryforge-software.com/wpblog/?p=129</link>
		<comments>http://www.binaryforge-software.com/wpblog/?p=129#comments</comments>
		<pubDate>Sun, 29 Jan 2012 11:32:32 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[Patterns]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[wcf]]></category>

		<guid isPermaLink="false">http://www.binaryforge-software.com/wpblog/?p=129</guid>
		<description><![CDATA[Our latest project involves a number of different app clients, for example Web, Phone, Tablet, Facebook app etc. This calls for an n-tier architecture, where we split the code base into logical modules. We can then swap in a different application client and re-use all of the same business and data access code. The architecture [...]]]></description>
			<content:encoded><![CDATA[<p>Our latest project involves a number of different app clients, for example Web, Phone, Tablet, Facebook app etc.  This calls for an n-tier architecture, where we split the code base into logical modules.  We can then swap in a different application client and re-use all of the same business and data access code.</p>
<p><strong>The architecture</strong></p>
<p>Borrowing on ideas from <a href="http://www.toplinestrategies.com/dotneters/net/wcf-entity-framework-and-n-tier-solutions-part-2/?lang=en">this post</a>, we want our architecture to resemble something like:</p>
<p><a href="http://www.binaryforge-software.com/wpblog/wp-content/uploads/2012/01/EFTopLevelArchitecture.png"><img src="http://www.binaryforge-software.com/wpblog/wp-content/uploads/2012/01/EFTopLevelArchitecture-791x1024.png" alt="" title="EFTopLevelArchitecture" width="603" height="780" class="alignnone size-large wp-image-130" /></a></p>
<p><strong>The problem</strong></p>
<p>However achieving this is not as straightforward as it sounds.  If we want to use the Entity Framework as our ORM, then we have to be aware of what happens when WCF tries to serialize/deserialize this to and from our application layer.  The first sign of trouble was when I got this message:</p>
<blockquote><p>System.Xml.XmlException: The maximum read depth (32) has been exceeded because XML data being read has more levels of nesting than is allowed by the quota. This quota may be increased by changing the MaxDepth property on the XmlDictionaryReaderQuotas object used when creating the XML reader. Line 1, position 5230.<br />
   at System.Xml.XmlExceptionHelper.ThrowXmlException
</p></blockquote>
<p>The hack would have been to increase the read depth to a higher level, but that isn&#8217;t addressing the real problem, and of course there is no guarantee what might happen later.</p>
<p>The reason this exception is occurring in the first place is due to the entire object graph being deserialized by WCF.  There is probably a cyclic navigation path between two objects (e.g. object A has reference to object B, and object B has reference to object A) and so the XML goes on for ever.</p>
<p>Easy fix?  Detach the object before sending them back across the wire from the WCF service.</p>
<p>Okay, that will work and give you the top level entity, but what I found was that the children of this entity were all NULL.  So that didn&#8217;t work for me.</p>
<p><strong>POCO</strong></p>
<p>Going back to the architecture above, what we want to do is work with Entity Objects in our DAL, but by the time we get to the service/app level we want to work with POCOs &#8211; Plain Old CLR Objects.  Problem with this is that <a href="http://msdn.microsoft.com/en-us/library/ee705457.aspx">WCF cannot directly serialize or deserialize the POCO proxy type</a>.</p>
<p>This is because the proxy types are dynamic types, and the serializer can only, as ever, work with known types.  The above workaround, applying ProxyDataContractResolver, did NOT work for me, although that&#8217;s perhaps because of my slightly different approach.</p>
<p>Following the steps in the first article, I set up my Entity Data Model as normal, although this time I download the <a href="http://visualstudiogallery.msdn.microsoft.com/23df0450-5677-4926-96cc-173d02752313">POCO Entity Generator</a>  so that I can then create POCO classes from my EDMX.</p>
<p>Move the .tt template into the Model project and change the source to point to the original EDMX in the Data project.</p>
<p>For those classes that need custom business logic, I then create partial classes to correspond with the relevant auto-generated POCO partial data class.</p>
<p>So, to recap, I now have an app layer which calls methods on my WCF service to return a list of POCO data objects.  The WCF service in turn calls the data layer, which gets the data but puts this into POCO objects in the Model.  The WCF service then returns these POCO Model objects, instead of the Entity Objects.</p>
<p><strong>More problems</strong></p>
<p>Everything should have worked&#8230;. but it didn&#8217;t.</p>
<p>I received a generic error message:</p>
<blockquote><p>
An error occurred while receiving the HTTP response to http://localhost/FtyDataService/MainService.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.<br />
The underlying connection was closed: A connection that was expected to be kept alive was closed by the server.</p></blockquote>
<p>Debugging the WCF service didn&#8217;t help at all &#8211; it would happily get to the end of the method and it was only on the return (serialization routines) that something was going wrong.  But what?  I&#8217;m sure those of you more adept at WCF than myself will know the answer straight away, but I had to debug the problem using the SvcTraceViewer tool.</p>
<p><strong>SvcTraceViewer</strong></p>
<p>The SvcTraceViewer is a great tool to debug inside WCF services.  To use it, you need to:</p>
<ul>
<li><a href="http://professionalaspnet.com/archive/2010/09/02/Turn-on-WCF-Tracing-for-WCF-Troubleshooting.aspx">Set up Trace in the web/app.config</a></li>
<li><a href="http://www.microsoft.com/download/en/details.aspx?id=8279">Install .NET 4.0/Windows 7 SDK</a></li>
<li>Run the service; this will generate diagnostic files in the root of the service solution, and open the tracelog.svclog in SvcTraceViewer (probably in C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin)</li>
</ul>
<p>This will show each activity, and any exceptions will show up inside each activity in red.  The inner exceptions are then displayed.</p>
<p>The exception is uncovered:</p>
<blockquote><p>There was an error while trying to serialize parameter http://tempuri.org/:GetUserDataResult. The InnerException message was &#8216;Object graph for type &#8216;FtyModel.Team&#8217; contains cycles and cannot be serialized if reference tracking is disabled.&#8217;.  Please see InnerException for more details.
</p></blockquote>
<p><a href="http://www.binaryforge-software.com/wpblog/wp-content/uploads/2012/01/SvcTraceViewer.png"><img src="http://www.binaryforge-software.com/wpblog/wp-content/uploads/2012/01/SvcTraceViewer-1024x742.png" alt="" title="SvcTraceViewer" width="603" height="436" class="alignnone size-large wp-image-136" /></a></p>
<p>To eliminate this error, I had to add</p>
<p>[DataContract(IsReference = true)]</p>
<p>to the top of the .tt file, so that each POCO class had this attribute.</p>
<p>(reason why explained in <a href="http://stackoverflow.com/questions/4335834/solve-a-circular-reference-in-wcf-from-my-pocos">this SO post</a>)</p>
<p>The next run worked, but didn&#8217;t return any data.  The obvious reason for this was that no property had [DataMember] marked around them.  Once fixed, data was returned.</p>
<p>UPDATE: Marking the POCOs as DataContract, DataMember is unnecessary (and not even correct!).  POCOs should be clean, unmarked classes.</p>
<p>The &#8220;cyclical references&#8221; error can only be sorted out by stopping WCF from getting in a bind (infinite references when it tries to serialize) by using an  attribute &#8211; <a href="http://chabster.blogspot.com/2008/02/wcf-cyclic-references-support.html">http://chabster.blogspot.com/2008/02/wcf-cyclic-references-support.html</a></p>
<p>However, IMPORTANT &#8211; this attribute is NOT respected when using the in-built WCF service client!  </p>
]]></content:encoded>
			<wfw:commentRss>http://www.binaryforge-software.com/wpblog/?feed=rss2&#038;p=129</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Framework 4.1, Repository and Specification patterns</title>
		<link>http://www.binaryforge-software.com/wpblog/?p=125</link>
		<comments>http://www.binaryforge-software.com/wpblog/?p=125#comments</comments>
		<pubDate>Wed, 21 Dec 2011 11:37:14 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://www.binaryforge-software.com/wpblog/?p=125</guid>
		<description><![CDATA[Working on a new long-term project, and we need a data access layer that will be extensible over a number of years. There are plenty of resources available for the Repository and Specification patterns, although each one seems to be slightly different. So keeping with tradition I&#8217;ll take you through my version! I want two [...]]]></description>
			<content:encoded><![CDATA[<p>Working on a new long-term project, and we need a data access layer that will be extensible over a number of years.</p>
<p>There are plenty of resources available for the Repository and Specification patterns, although each one seems to be slightly different.  So keeping with tradition I&#8217;ll take you through my version!</p>
<p>I want two &#8220;types&#8221; of repository &#8211; a repository bound to a SQL Server datasource via EntityFramework and a repository bound to an in memory data set.  This will allow us to quickly simulate the application by detaching from the underlying database.  The workflow for the app has several ETL routines running, so actually testing the flow of the application will be difficult without being able to instantly put the application into a particular state.</p>
<p>For this I will be using Spring.NET a my IoC container, however this is beyond the scope of this article.</p>
<p>My base repository will expose methods FindOne and FindMany &#8211; these will take a ISpecification<T> as input.  The ISpecification classes contain the query logic.  This keeps the query logic self contained, and also means they only need to be written ONCE across multiple repositories.</p>
<p><strong>The base repository therefore looks like:</strong></p>
<pre lang="C#">
    public interface IRepository<T>
    {
        void Add(T owner);
        IQueryable<T> All { get; }
        void Delete(T owner);

        ///
<summary>
        /// Finds entities based on provided criteria.
        /// </summary>

        IList<T> FindMany(ISpecification<T> criteria);

        ///
<summary>
        /// Finds one entity based on provided criteria.
        /// </summary>

        T FindOne(ISpecification<T> criteria);
    }
</pre>
<p><strong>ISpecification:</strong></p>
<pre lang="C#">
    public interface ISpecification<T>
    {
        Expression<Func<T, bool>> IsSatisfied { get; }
    }
</pre>
<p><strong>In Memory Repository:</strong></p>
<pre lang="C#">
    public abstract class IMRepository<T> : IRepository<T> where T : class
    {
        protected List<T> all;

        public IMRepository()
        {
            all = new List<T>();
        }

        public void Add(T owner)
        {
            all.Add(owner);
        }

        public IQueryable<T> All
        {
            get
            {
                return all.AsQueryable();
            }
        }

        public void Delete(T owner)
        {
            all.Remove(owner);
        }

        public IList<T> FindMany(ISpecification<T> criteria)
        {
            var query = All.Where(criteria.IsSatisfied);
            return query.ToList();
        }

        public T FindOne(ISpecification<T> criteria)
        {
            var query = All.Where(criteria.IsSatisfied);
            return query.FirstOrDefault();
        }
    }
</pre>
<p><strong>Status Specification (query Order records):</strong></p>
<pre lang="C#">

    public class StatusSpecification: ISpecification<Order>
    {
        private int _statusId;

        public StatusSpecification(int statusId)
        {
            _statusId = statusId;
        }

        public Expression<Func<Order, bool>> IsSatisfied
        {
            get
            {
                return p => p.Status == "test";
            }
        }
    }
</pre>
<p><strong>To use, our unit test looks like:</strong></p>
<pre lang="C#">
IUnitOfWork uw = new IMUnitOfWork();
var spec = new StatusSpecification(1);
var list = uw.Orders.FindMany(spec);
</pre>
<p>At the moment, this works really well, however time will tell if it can handle more complex real-world scenarios.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.binaryforge-software.com/wpblog/?feed=rss2&#038;p=125</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

