<?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>Davepoint</title>
	<atom:link href="http://blog.ceredir.com/index.php/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.ceredir.com</link>
	<description></description>
	<lastBuildDate>Thu, 15 Jan 2015 12:10:51 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=4.2.2</generator>
	<item>
		<title>Problem after update to Framework v4.5.2</title>
		<link>http://blog.ceredir.com/index.php/2015/01/15/problem-after-update-to-framework-v4-5-2/</link>
		<comments>http://blog.ceredir.com/index.php/2015/01/15/problem-after-update-to-framework-v4-5-2/#comments</comments>
		<pubDate>Thu, 15 Jan 2015 12:08:40 +0000</pubDate>
		<dc:creator><![CDATA[admin]]></dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Azure]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://blog.ceredir.com/?p=171</guid>
		<description><![CDATA[After installing the update to .Net Framework v4.5.2 and rebooting, Visual Studio 2013 would no longer load my Azure SDK 2.3 cloud service, complaining that &#8220;The CctSharedPackage did not load correctly&#8221;.  The fix was to go to the Control Panel and select ‘Azure Tools for Microsoft Visual Studio 2013 – v2.3’, then hit change and repair. [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>After installing the update to .Net Framework v4.5.2 and rebooting, Visual Studio 2013 would no longer load my Azure SDK 2.3 cloud service, complaining that &#8220;The CctSharedPackage did not load correctly&#8221;.  The fix was to go to the Control Panel and select ‘Azure Tools for Microsoft Visual Studio 2013 – v2.3’, then hit change and repair.</p>
<p>&nbsp;</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="https://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.ceredir.com%2Findex.php%2F2015%2F01%2F15%2Fproblem-after-update-to-framework-v4-5-2%2F&amp;title=Problem%20after%20update%20to%20Framework%20v4.5.2" id="wpa2a_2"><img src="http://blog.ceredir.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.ceredir.com/index.php/2015/01/15/problem-after-update-to-framework-v4-5-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Keeping Web Applications out of the load balancer pool until they have initialized</title>
		<link>http://blog.ceredir.com/index.php/2015/01/09/keeping-web-applications-out-of-the-load-balancer-pool-until-they-have-initialized/</link>
		<comments>http://blog.ceredir.com/index.php/2015/01/09/keeping-web-applications-out-of-the-load-balancer-pool-until-they-have-initialized/#comments</comments>
		<pubDate>Fri, 09 Jan 2015 10:01:00 +0000</pubDate>
		<dc:creator><![CDATA[admin]]></dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Azure]]></category>

		<guid isPermaLink="false">http://blog.ceredir.com/?p=164</guid>
		<description><![CDATA[Some of our web applications take a little while to start-up.  Unity resolution, cache warming, configuration build etc. all take time.  Normally Azure will put a web role in the load balanced pool as soon as its OnStart has completed, which means a user may hit a cold application and have to wait 30-60s for [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Some of our web applications take a little while to start-up.  Unity resolution, cache warming, configuration build etc. all take time.  Normally Azure will put a web role in the load balanced pool as soon as its <code>OnStart</code> has completed, which means a user may hit a cold application and have to wait 30-60s for their request to be processed.</p>
<p>AppPools also recycle at least every 29 hours by default.  This can be overridden but the periodic recycle is intended to cope with memory leaks, LOH fragmentation etc., so this may be counter-productive.</p>
<p>This is one way of dealing with it.</p>
<ol>
<li>Call the application on the internal (i.e. non-load balanced endpoint) from the role&#8217;s <code>OnStart</code> method synchronously.  This means that OnStart won&#8217;t return until the application has completed a request, and so the role won&#8217;t be marked as Ready and added to the pool until it&#8217;s warm.</li>
<li>In the <code>Application_End</code> method, request a page from the application.  The role&#8217;s <code>OnStart</code> method isn&#8217;t called on a AppPool recycle, so doing this will ensure that the AppPool immediately restarts.</li>
<li>Register a <code>RoleEnvironmentStatusCheck</code> callback that will make sure that if the application is in the pool while it is initialising, it will be immediately removed.</li>
</ol>
<p>Here&#8217;s the code.</p>
<p>In your <code>WebRole.cs</code> (or whatever derives from <code>RoleEntryPoint</code>), call the main application.  Note that we are ignoring SSL errors, because we aren&#8217;t using the domain name.  I&#8217;ve also found that hitting it on localhost or 127.0.0.1 won&#8217;t work.  Your mileage may vary here.</p>
<p>&nbsp;</p>
<pre class="brush: csharp; ruler: true;">public override bool OnStart()
{
    try
    {
        // If the app pool is recycling, make sure we start up again straight away.  Note that
        // we need to do this by IP address, local host name or localhost or 127.0.0.1 won't work.
        ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslpolicyerrors) =&gt; true;
        var ipEntry = Dns.GetHostEntry(Dns.GetHostName());
        foreach (var address in ipEntry.AddressList)
        {
            if (address.AddressFamily == AddressFamily.InterNetwork)
            {
                if (address.Equals(IPAddress.Loopback)) continue;
                var client = new WebClient();
                client.DownloadString(string.Format("https://{0}/", address));
            }
        }
    }
    catch (Exception exception)
    {
        System.Diagnostics.Trace.WriteLine(exception);
        // Don't deal with errors here.  The main application will do that.
    }
    return base.OnStart();
}

</pre>
<p>In <code>Global.asax.cs</code></p>
<pre class="brush: csharp; ruler: true;">protected void Application_End()
{
    try
    {
        // If the app pool is recycling, make sure we start up again straight away.  Note that
        // we need to do this by IP address, local host name or localhost or 127.0.0.1 won't work.
        ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslpolicyerrors) =&gt; true;
        var ipEntry = Dns.GetHostEntry(Dns.GetHostName());
        foreach (var address in ipEntry.AddressList)
        {
            if (address.AddressFamily == AddressFamily.InterNetwork)
            {
                if (address.Equals(IPAddress.Loopback)) continue;

                var client = new WebClient();
                client.DownloadString(string.Format("https://{0}/?", address));
            }
        }
    }
    catch(Exception exception)
    {
        _logger.Log(exception, "Error trying to restart application");
    }
}</pre>
<p>In <code>Global.asax.cs</code> add this callback:</p>
<pre class="brush: csharp; ruler: true;">/// &lt;summary&gt;
/// Keep the instance out of the load balancer pool until initialisation is complete.
/// &lt;/summary&gt;
/// &lt;param name="sender"&gt;&lt;/param&gt;
/// &lt;param name="e"&gt;&lt;/param&gt;
private void RoleEnvironmentStatusCheck(object sender, RoleInstanceStatusCheckEventArgs e)
{
    if (_isBusy)
    {
        e.SetBusy();
    }
}</pre>
<p>Add this field to the class:</p>
<pre class="brush: csharp; ruler: true;"> private volatile bool _isBusy = true;</pre>
<p>And modify <code>Application_Start</code> to look like this:</p>
<pre class="brush: csharp; ruler: true;">protected void Application_Start()
{
    RoleEnvironment.StatusCheck += RoleEnvironmentStatusCheck;
 
    // Initialisation code
    _isBusy = false;
}</pre>
<p>&nbsp;</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="https://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.ceredir.com%2Findex.php%2F2015%2F01%2F09%2Fkeeping-web-applications-out-of-the-load-balancer-pool-until-they-have-initialized%2F&amp;title=Keeping%20Web%20Applications%20out%20of%20the%20load%20balancer%20pool%20until%20they%20have%20initialized" id="wpa2a_4"><img src="http://blog.ceredir.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.ceredir.com/index.php/2015/01/09/keeping-web-applications-out-of-the-load-balancer-pool-until-they-have-initialized/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SCSS Gotchas</title>
		<link>http://blog.ceredir.com/index.php/2013/09/03/scss-gotchas/</link>
		<comments>http://blog.ceredir.com/index.php/2013/09/03/scss-gotchas/#comments</comments>
		<pubDate>Tue, 03 Sep 2013 12:18:09 +0000</pubDate>
		<dc:creator><![CDATA[David Bending]]></dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[gotchas]]></category>
		<category><![CDATA[SCSS]]></category>

		<guid isPermaLink="false">http://blog.ceredir.com/?p=160</guid>
		<description><![CDATA[If you use a @charset directive, it must be the first line in the file.  don&#8217;t even put a comment in front of it. Right: @charset "UTF-8"; Wrong: // Set up my charset @charset "UTF-8";]]></description>
				<content:encoded><![CDATA[<p>If you use a @charset directive, it <strong>must</strong> be the first line in the file.  don&#8217;t even put a comment in front of it.</p>
<p>Right:</p>
<pre>@charset "UTF-8";</pre>
<p>Wrong:</p>
<pre>// Set up my charset
@charset "UTF-8";</pre>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="https://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.ceredir.com%2Findex.php%2F2013%2F09%2F03%2Fscss-gotchas%2F&amp;title=SCSS%20Gotchas" id="wpa2a_6"><img src="http://blog.ceredir.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.ceredir.com/index.php/2013/09/03/scss-gotchas/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Azure Gotchas II</title>
		<link>http://blog.ceredir.com/index.php/2013/07/19/azure-gotchas-ii/</link>
		<comments>http://blog.ceredir.com/index.php/2013/07/19/azure-gotchas-ii/#comments</comments>
		<pubDate>Fri, 19 Jul 2013 07:47:52 +0000</pubDate>
		<dc:creator><![CDATA[David Bending]]></dc:creator>
				<category><![CDATA[Azure]]></category>
		<category><![CDATA[azure]]></category>
		<category><![CDATA[gotchas]]></category>

		<guid isPermaLink="false">http://blog.ceredir.com/?p=154</guid>
		<description><![CDATA[When you build a VM in the Azure Portal, don&#8217;t choose the username &#8216;tester&#8217;.  If you do the machine won&#8217;t start and will remain stuck in the provisioning phase.]]></description>
				<content:encoded><![CDATA[<p>When you build a VM in the Azure Portal, don&#8217;t choose the username &#8216;tester&#8217;.  If you do the machine won&#8217;t start and will remain stuck in the provisioning phase.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="https://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.ceredir.com%2Findex.php%2F2013%2F07%2F19%2Fazure-gotchas-ii%2F&amp;title=Azure%20Gotchas%20II" id="wpa2a_8"><img src="http://blog.ceredir.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.ceredir.com/index.php/2013/07/19/azure-gotchas-ii/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Azure Gotchas</title>
		<link>http://blog.ceredir.com/index.php/2013/07/18/azure-gotchas/</link>
		<comments>http://blog.ceredir.com/index.php/2013/07/18/azure-gotchas/#comments</comments>
		<pubDate>Thu, 18 Jul 2013 09:46:45 +0000</pubDate>
		<dc:creator><![CDATA[David Bending]]></dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[azure]]></category>
		<category><![CDATA[gotchas]]></category>

		<guid isPermaLink="false">http://blog.ceredir.com/?p=150</guid>
		<description><![CDATA[Having fun getting your Azure startup tasks to run?  One things to beware of when debugging this is to know where your code runs.  If you are deploying a web role you&#8217;ll likely see your startup script in e:\approot.  However, most likely it&#8217;s actually running the copy in e:\approot\bin that got there because you selected [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Having fun getting your Azure startup tasks to run?  One things to beware of when debugging this is to know where your code runs.  If you are deploying a web role you&#8217;ll likely see your startup script in <code>e:\approot</code>.  However, most likely it&#8217;s actually running the copy in <code>e:\approot\bin</code> that got there because you selected &#8216;Build Action&#8217; as &#8216;Content&#8217; and &#8216;Copy to Output Directory&#8217; as &#8216;Always&#8217; or &#8216;If Newer&#8217;.</p>
<p>Similarly you&#8217;ll see your <code>Web.config</code> in <code>e:\approot</code>.  But that isn&#8217;t what the site is using, which will be somewhere lower down (check from IIS).</p>
<p>Finally Azure is fussy about encodings for startup scripts.  Try using codepage 1252 and you should be OK.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="https://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.ceredir.com%2Findex.php%2F2013%2F07%2F18%2Fazure-gotchas%2F&amp;title=Azure%20Gotchas" id="wpa2a_10"><img src="http://blog.ceredir.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.ceredir.com/index.php/2013/07/18/azure-gotchas/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The type TraceListener cannot be constructed</title>
		<link>http://blog.ceredir.com/index.php/2013/05/22/the-type-tracelistener-cannot-be-constructed/</link>
		<comments>http://blog.ceredir.com/index.php/2013/05/22/the-type-tracelistener-cannot-be-constructed/#comments</comments>
		<pubDate>Wed, 22 May 2013 07:47:04 +0000</pubDate>
		<dc:creator><![CDATA[David Bending]]></dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://blog.ceredir.com/?p=146</guid>
		<description><![CDATA[If you are using the Enterprise Library Logging block and you get this error: The type TraceListener cannot be constructed. You must configure the container to supply this value. It&#8217;s because you&#8217;ve referenced a listener in your sources block that isn&#8217;t defined in the listeners block. e.g.: &#60;loggingConfiguration name="" tracingEnabled="true" defaultCategory="Error"&#62;   &#60;listeners&#62;     &#60;add listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.SystemDiagnosticsTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"   type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"   name="Azure Diagnostics Trace Listener" /&#62;   &#60;/listeners&#62;   &#60;categorySources&#62;     &#60;add switchValue="All" name="Error"&#62; [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>If you are using the Enterprise Library Logging block and you get this error:</p>
<p>The type TraceListener cannot be constructed. You must configure the container to supply this value.</p>
<p>It&#8217;s because you&#8217;ve referenced a listener in your sources block that isn&#8217;t defined in the listeners block.</p>
<p>e.g.:</p>
<pre>&lt;loggingConfiguration name="" tracingEnabled="true" defaultCategory="Error"&gt;
  &lt;listeners&gt;
    &lt;add listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.SystemDiagnosticsTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
  type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
  name="Azure Diagnostics Trace Listener" /&gt;
  &lt;/listeners&gt;
  &lt;categorySources&gt;
    &lt;add switchValue="All" name="Error"&gt;
      &lt;listeners&gt;
        &lt;add name="Azure Diagnostics Trace Listener" /&gt;
      &lt;/listeners&gt;
    &lt;/add&gt;</pre>
<p>is OK, but</p>
<pre>        &lt;add name="Foo" /&gt;</pre>
<p>is wrong.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="https://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.ceredir.com%2Findex.php%2F2013%2F05%2F22%2Fthe-type-tracelistener-cannot-be-constructed%2F&amp;title=The%20type%20TraceListener%20cannot%20be%20constructed" id="wpa2a_12"><img src="http://blog.ceredir.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.ceredir.com/index.php/2013/05/22/the-type-tracelistener-cannot-be-constructed/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RhinoMocks 3.6 with &#8220;Just My Code&#8221; disabled</title>
		<link>http://blog.ceredir.com/index.php/2012/07/17/rhinomocks-3-6-with-just-my-code-disabled/</link>
		<comments>http://blog.ceredir.com/index.php/2012/07/17/rhinomocks-3-6-with-just-my-code-disabled/#comments</comments>
		<pubDate>Tue, 17 Jul 2012 10:10:10 +0000</pubDate>
		<dc:creator><![CDATA[David Bending]]></dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[RhinoMocks]]></category>

		<guid isPermaLink="false">http://blog.ceredir.com/?p=142</guid>
		<description><![CDATA[When I turned off the debug &#8216;Just My Code&#8217; setting, RhinoMocks started throwing an exception claiming it can&#8217;t mock sealed classes.  This is very mysterious, because my mock is a multi-mock of two interfaces.  Bizarre.  Equally as bizarre is the fix, which is to close Visual Studio, delete the .suo file, and restart &#8211; at [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>When I turned off the debug &#8216;Just My Code&#8217; setting, RhinoMocks started throwing an exception claiming it can&#8217;t mock sealed classes.  This is very mysterious, because my mock is a multi-mock of two interfaces.  Bizarre.  Equally as bizarre is the fix, which is to close Visual Studio, delete the .suo file, and restart &#8211; at which everything is fine&#8230;</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="https://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.ceredir.com%2Findex.php%2F2012%2F07%2F17%2Frhinomocks-3-6-with-just-my-code-disabled%2F&amp;title=RhinoMocks%203.6%20with%20%E2%80%9CJust%20My%20Code%E2%80%9D%20disabled" id="wpa2a_14"><img src="http://blog.ceredir.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.ceredir.com/index.php/2012/07/17/rhinomocks-3-6-with-just-my-code-disabled/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Concurrent Sessions in MVC2</title>
		<link>http://blog.ceredir.com/index.php/2010/09/21/concurrent-sessions-in-mvc2/</link>
		<comments>http://blog.ceredir.com/index.php/2010/09/21/concurrent-sessions-in-mvc2/#comments</comments>
		<pubDate>Tue, 21 Sep 2010 14:19:41 +0000</pubDate>
		<dc:creator><![CDATA[David Bending]]></dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[mvc]]></category>

		<guid isPermaLink="false">http://blog.ceredir.com/?p=138</guid>
		<description><![CDATA[There’s lots of rules that control how many concurrent connections you can have in an ASP.net MVC2 application. Firstly the browser itself limits the number of connections it will make to the same domain.  The limit used to be 2 (as per the HTTP specification).  Some browsers increase this limit, but older browsers like IE6 [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>There’s lots of rules that control how many concurrent connections you can have in an ASP.net MVC2 application.</p>
<p>Firstly the browser itself limits the number of connections it will make to the same domain.  The limit used to be 2 (as per the HTTP specification).  Some browsers increase this limit, but older browsers like IE6 will still stick to it.</p>
<p>Secondly you have the number of threads available in IIS to content with.  <a href="http://blogs.msdn.com/b/tmarq/archive/2007/07/21/asp-net-thread-usage-on-iis-7-0-and-6-0.aspx">Thomas Masquardt’s Blog</a> gives a very detailed explanation of this.</p>
<p>Finally MVC itself has some limitations. Basically you can only have a single request using a read-write session at any given time.  This means that if you have a controller serving up images, and you don’t take any steps to avoid the problem, you will only ever serve up one image at a time.  <a href="http://weblogs.asp.net/imranbaloch/archive/2010/07/10/concurrent-requests-in-asp-net-mvc.aspx">Imran Baloch’s Blog</a> gives a lot more information about this and shows how to create session-less actions to avoid the issue.  For me the solution is quite simple.  By placing the following code in Global.asax.cs:</p>
<pre class="brush: csharp; ruler: true;">protected void Application_BeginRequest()
{
    if((Request.Url.AbsoluteUri.ToUpperInvariant().Contains("REFRESHPRICES")
        &amp;&amp; Request.Cookies["ASP.NET_SessionId"] != null))
    {
        Context.SetSessionStateBehavior(SessionStateBehavior.ReadOnly);
    }
}</pre>
<p>I can make the session for my action read-only, and sidestep the limit.</p>
<h3>Warning</h3>
<p>Just marking the session sate as read-only doesn’t prevent you from trying to modify the session.  It’s up to you to maintain thread-safety if you decide to lie to the framework.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="https://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.ceredir.com%2Findex.php%2F2010%2F09%2F21%2Fconcurrent-sessions-in-mvc2%2F&amp;title=Concurrent%20Sessions%20in%20MVC2" id="wpa2a_16"><img src="http://blog.ceredir.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.ceredir.com/index.php/2010/09/21/concurrent-sessions-in-mvc2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MVC2 Cross Field Validation</title>
		<link>http://blog.ceredir.com/index.php/2010/08/10/mvc2-cross-field-validation/</link>
		<comments>http://blog.ceredir.com/index.php/2010/08/10/mvc2-cross-field-validation/#comments</comments>
		<pubDate>Tue, 10 Aug 2010 08:07:43 +0000</pubDate>
		<dc:creator><![CDATA[David Bending]]></dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[mvc]]></category>

		<guid isPermaLink="false">http://blog.ceredir.com/index.php/2010/08/10/mvc2-cross-field-validation/</guid>
		<description><![CDATA[Introduction to Validation Nearly all web applications require some form of validation. Validation performs two main purposes: helping the user to enter correct values on a web page, and protecting the application from invalid or malicious input. Validation can take place client-side within the browser, or server-side when the page is posted to the server. [&#8230;]]]></description>
				<content:encoded><![CDATA[<h3>Introduction to Validation</h3>
<p>Nearly all web applications require some form of validation. Validation performs two main purposes: helping the user to enter correct values on a web page, and protecting the application from invalid or malicious input.</p>
<p>Validation can take place client-side within the browser, or server-side when the page is posted to the server. ASP.NET MVC2 comes with a flexible framework for applying validation using data annotations on the view model. Scott Gu has written an excellent tutorial on basic MVC validation here: <a href="http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx">http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx</a>.</p>
<h3>Limitations of Built-in MVC Validation</h3>
<p>The built-in validation works well for standard scenarios, but there are a few common scenarios it can’t cope with. One of the main issues is that validation can only be done on a model property in isolation. Often we will want to validate a property based on the current value of some other property: for instance we may want our <em>confirm password</em> field value to be the same as the <em>password</em> box.</p>
<p>In this article we will extend the MVC validation framework to provide support for cross-field validation. We’ll do this in part by creating custom validation attributes as described in Phil Haack’s article (<a href="http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx">http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx</a>) but we’ll also need to extend the validator framework to allow us to validate across fields.</p>
<h3>Extending the Framework to Support Cross-Field Validation</h3>
<p>To create a custom validation attribute we usually derive from ValidationAttribute and override the IsValid method, however IsValid only gets passed the value of the property to validate and we are going to need to see the value of other fields in the model. To accommodate this we’ll create an interface ICrossFieldValidationAttribute that has an IsValid method with access to the entire view model (note these code snippets only show significant lines – download the example solution to get the whole files):</p>
<pre class="brush: csharp; ruler: true;">public interface ICrossFieldValidationAttribute
{
    bool IsValid(ControllerContext controllerContext, object model, ModelMetadata modelMetadata);
}</pre>
<p>Next we build a base class for cross-field validators. This base class uses the extended IsValid defined above, rather than the narrower method used in the framework’s DataAnnotationsModelValidator class.</p>
<pre class="brush: csharp; ruler: true;">public abstract class CrossFieldValidator&lt;TAttribute&gt; : DataAnnotationsModelValidator&lt;TAttribute&gt;
        where TAttribute : ValidationAttribute, ICrossFieldValidationAttribute
{
    public override IEnumerable&lt;ModelValidationResult&gt; Validate(object container)
    {
        var attribute = Attribute as ICrossFieldValidationAttribute;

        if (!attribute.IsValid(ControllerContext, container, Metadata))
        {
            yield return new ModelValidationResult {Message = ErrorMessage};
        }
    }
}</pre>
<h3>Building the Validation</h3>
<p>Now that we have a cross-field validation framework in place, we can build our new attribute.</p>
<pre class="brush: csharp; ruler: true;">[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class EqualToPropertyAttribute : ValidationAttribute, ICrossFieldValidationAttribute
{
    public string OtherProperty { get; set; }

    public bool IsValid(ControllerContext controllerContext, object model, ModelMetadata modelMetadata)
    {
        var propertyInfo = model.GetType().GetProperty(OtherProperty);
        var otherValue = propertyInfo.GetGetMethod().Invoke(model, null);

        if (modelMetadata.Model == null) modelMetadata.Model = string.Empty;
        if (otherValue == null) otherValue = string.Empty;

        return modelMetadata.Model.ToString() == otherValue.ToString();
    }
}</pre>
<p>And apply it to the view model:</p>
<pre class="brush: csharp; ruler: true;">public class Account
{
    public string Password { get; set; }

    [EqualToProperty(OtherProperty = "Password")]
    public string ConfirmPassword { get; set; }
}</pre>
<p>We also need to create a validator class to emit the correct client-side rules, and to invoke the IsValid method.</p>
<pre class="brush: csharp; ruler: true;">public class EqualToPropertyValidator : CrossFieldValidator&lt;EqualToPropertyAttribute&gt;
{
    public override IEnumerable&lt;ModelClientValidationRule&gt; GetClientValidationRules()
    {
        var rule = new ModelClientValidationRule
        {
            ValidationType = "equaltoproperty",
            ErrorMessage = Attribute.FormatErrorMessage(Metadata.PropertyName),
        };

        rule.ValidationParameters.Add("otherProperty", Attribute.OtherProperty);

        return new[] { rule };
    }
}</pre>
<p>Finally we need to create a JavaScript function to evaluate the rule client-side:</p>
<pre class="brush: js; ruler: true;">jQuery.validator.addMethod("equaltoproperty", function (value, element, params) {
    if (this.optional(element)) {
        return true;
    }

    var otherPropertyControl = $("#" + params.otherProperty);
    if (otherPropertyControl == null) {
        return false;
    }

    var otherPropertyValue = otherPropertyControl[0].value;
    return otherPropertyValue == value;
});

function testConditionEqual(element, params) {
    var otherPropertyControl = $("#" + params.otherProperty);
    if (otherPropertyControl == null) {
        return false;
    }

    var otherPropertyValue;
    if (otherPropertyControl[0].type == "checkbox") {
        otherPropertyValue = (otherPropertyControl[0].checked) ? "True" : "False";
    } else {
        otherPropertyValue = otherPropertyControl[0].value;
    }

    return otherPropertyValue == params.comparand;
}</pre>
<p>And the final step is to register our new attribute with MVC. We do this in Global.asax Application_Start method like this:</p>
<pre class="brush: csharp; ruler: true;">DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EqualToPropertyAttribute),
                                                      typeof(EqualToPropertyValidator));</pre>
<pre class="brush: csharp; ruler: true;"> </pre>
<h2 class="brush: csharp; ruler: true;">Example</h2>
<p class="brush: csharp; ruler: true;">The example code is here <a href="http://blog.ceredir.com/wp-content/uploads/2010/08/CrossFieldValidation1.zip">CrossFieldValidation</a>.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="https://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.ceredir.com%2Findex.php%2F2010%2F08%2F10%2Fmvc2-cross-field-validation%2F&amp;title=MVC2%20Cross%20Field%20Validation" id="wpa2a_18"><img src="http://blog.ceredir.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.ceredir.com/index.php/2010/08/10/mvc2-cross-field-validation/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Exception in WCF Service (HRESULT: 0x80131045)</title>
		<link>http://blog.ceredir.com/index.php/2010/08/02/exception-in-wcf-service-hresult-0x80131045/</link>
		<comments>http://blog.ceredir.com/index.php/2010/08/02/exception-in-wcf-service-hresult-0x80131045/#comments</comments>
		<pubDate>Mon, 02 Aug 2010 13:30:05 +0000</pubDate>
		<dc:creator><![CDATA[David Bending]]></dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://blog.ceredir.com/?p=122</guid>
		<description><![CDATA[I couldn&#8217;t understand why I could call my WCF service from WcfTestClient, but when I hit it with integration tests built using the unit test framework I got this message: Test method Lookup.IntegrationTests.HttpLabelTests.GetLabel threw exception: System.ServiceModel.ProtocolException: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding (text/xml; [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>I couldn&#8217;t understand why I could call my WCF service from WcfTestClient, but when I hit it with integration tests built using the unit test framework I got this message:</p>
<pre>Test method Lookup.IntegrationTests.HttpLabelTests.GetLabel threw exception:
System.ServiceModel.ProtocolException: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first 1024 bytes of the response were: '&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Common' or one of its dependencies. Strong name signature could not be verified. &amp;nbsp;The assembly may have been tampered with, or it was delay signed but not fully signed with the correct private key. (Exception from HRESULT: 0x80131045)&lt;/title&gt;
        &lt;style&gt;
         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
         p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
         pre {font-family:"Lucida Console";font-size: .9em}
         .marker {font-weight: bold; color: black;text-decoration: none;}
         .version {color: gray;}
         .error {margin-bottom: 10px;}
         .expandabl'. ---&gt; System.Net.WebException: The remote server returned an error: (500) Internal Server Error.</pre>
<p>The answer is CodeCoverage.  By default Visual Studio 2010 tries to measure coverage for every assembly in the service bin.  To avoid the problem turn this off, and add coverage for each assembly you are interested in individually.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="https://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.ceredir.com%2Findex.php%2F2010%2F08%2F02%2Fexception-in-wcf-service-hresult-0x80131045%2F&amp;title=Exception%20in%20WCF%20Service%20%28HRESULT%3A%200x80131045%29" id="wpa2a_20"><img src="http://blog.ceredir.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.ceredir.com/index.php/2010/08/02/exception-in-wcf-service-hresult-0x80131045/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
