<?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>Shawson&#039;s Code Blog &#187; C#.net</title>
	<atom:link href="http://codeblog.shawson.co.uk/category/c-sharp-net/feed/" rel="self" type="application/rss+xml" />
	<link>http://codeblog.shawson.co.uk</link>
	<description>development notes for my failing memory</description>
	<lastBuildDate>Wed, 01 Feb 2012 11:00:16 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Conditional logic in ListView ItemTemplate with DataBinder.Eval</title>
		<link>http://codeblog.shawson.co.uk/conditional-logic-in-listview-itemtemplate-with-databinder-eval/</link>
		<comments>http://codeblog.shawson.co.uk/conditional-logic-in-listview-itemtemplate-with-databinder-eval/#comments</comments>
		<pubDate>Fri, 13 Jan 2012 10:16:55 +0000</pubDate>
		<dc:creator>shawson</dc:creator>
				<category><![CDATA[C#.net]]></category>

		<guid isPermaLink="false">http://codeblog.shawson.co.uk/?p=1304</guid>
		<description><![CDATA[Embarrasingly simple, but something I always seem to forget, and then never blog! I needed to show a tick in a repeater when a row value was -1: Simple! In MVC, with the razor syntax and strongly typed views I&#8217;ve grown to love, this is a pinch o&#8217; the proverbial piss- In WebForms rreviously I [...]


Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/how-to-display-hierarchical-data-by-using-nested-repeater-controls-and-visual-c-net/' rel='bookmark' title='How To Display Hierarchical Data Using Nested Repeater Controls and Visual C# .NET'>How To Display Hierarchical Data Using Nested Repeater Controls and Visual C# .NET</a></li>
<li><a href='http://codeblog.shawson.co.uk/aspnet-nested-listview-controls-with-all-edit-functionality-working/' rel='bookmark' title='Asp.net nested ListView control&#8217;s, with edit functionality- example'>Asp.net nested ListView control&#8217;s, with edit functionality- example</a></li>
<li><a href='http://codeblog.shawson.co.uk/c-dynamic-keyword-and-how-you-can-use-it-to-help-tdd/' rel='bookmark' title='C# Dynamic keyword, and how you can use it to help TDD!'>C# Dynamic keyword, and how you can use it to help TDD!</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>Embarrasingly simple, but something I always seem to forget, and then never blog!  I needed to show a tick in a repeater when a row value was -1: Simple!  In MVC, with the razor syntax and strongly typed views I&#8217;ve grown to love, this is a pinch o&#8217; the proverbial piss- In WebForms rreviously I often resort to setting up an ItemDataBound event handler which hides or shows an image, but to be honest I could not be bothered- this seems such overkill for something as simple as this.  Anyway, after some faffing I reminded myself the easiest method is to use an &#8216;in-line if&#8217; in the ItemTemplate, like so;</p>
<pre class="brush: html">
&lt;ItemTemplate&gt;
        &lt;tr&gt;
            &lt;td&gt;&lt;%# Eval(&quot;CarReg&quot;) %&gt;&lt;/td&gt;
            ...
            &lt;td&gt;
                &lt;%# (DataBinder.Eval(Container.DataItem, &quot;NewRepeat&quot;) != null &amp;&amp; DataBinder.Eval(Container.DataItem, &quot;NewRepeat&quot;).Equals(-1) ? &quot;&lt;img src=\&quot;../images/tick.png\&quot; alt=\&quot;tick\&quot; /&gt;&quot; : &quot;&lt;img src=\&quot;../images/cross.png\&quot; alt=\&quot;cross\&quot; /&quot;)%&gt;
            &lt;/td&gt;
</pre>


<p>Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/how-to-display-hierarchical-data-by-using-nested-repeater-controls-and-visual-c-net/' rel='bookmark' title='How To Display Hierarchical Data Using Nested Repeater Controls and Visual C# .NET'>How To Display Hierarchical Data Using Nested Repeater Controls and Visual C# .NET</a></li>
<li><a href='http://codeblog.shawson.co.uk/aspnet-nested-listview-controls-with-all-edit-functionality-working/' rel='bookmark' title='Asp.net nested ListView control&#8217;s, with edit functionality- example'>Asp.net nested ListView control&#8217;s, with edit functionality- example</a></li>
<li><a href='http://codeblog.shawson.co.uk/c-dynamic-keyword-and-how-you-can-use-it-to-help-tdd/' rel='bookmark' title='C# Dynamic keyword, and how you can use it to help TDD!'>C# Dynamic keyword, and how you can use it to help TDD!</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://codeblog.shawson.co.uk/conditional-logic-in-listview-itemtemplate-with-databinder-eval/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Grabbing data from the registry on a remote machine using dot net and WMI</title>
		<link>http://codeblog.shawson.co.uk/grabbing-data-from-the-registry-on-a-remote-machine-using-dot-net-and-wmi/</link>
		<comments>http://codeblog.shawson.co.uk/grabbing-data-from-the-registry-on-a-remote-machine-using-dot-net-and-wmi/#comments</comments>
		<pubDate>Tue, 22 Nov 2011 13:24:57 +0000</pubDate>
		<dc:creator>shawson</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[C#.net]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://codeblog.shawson.co.uk/?p=1281</guid>
		<description><![CDATA[I recently had to write an app which, given a computer name, would grab their telephone extension from a registry key (For the purpose of the code example below, I just grab the CommonFilesDir key from the windows node. There&#8217;s a couple of ways you can achieve this- either using RegistryKey.OpenRemoteBaseKey which gave me a [...]


Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/using-urlencode-urldecode-and-other-http-functions-from-a-non-web-file/' rel='bookmark' title='Using URLEncode, URLDecode and other Http functions from a non Web file'>Using URLEncode, URLDecode and other Http functions from a non Web file</a></li>
<li><a href='http://codeblog.shawson.co.uk/wcf-404-3-errors/' rel='bookmark' title='WCF 404.3 Errors'>WCF 404.3 Errors</a></li>
<li><a href='http://codeblog.shawson.co.uk/making-your-wcf-service-compatible-with-legacy-net-1-1-applications/' rel='bookmark' title='Making your WCF Service compatible with legacy .net 1.1 applications'>Making your WCF Service compatible with legacy .net 1.1 applications</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>I recently had to write an app which, given a computer name, would grab their telephone extension from a registry key (For the purpose of the code example below, I just grab the CommonFilesDir key from the windows node.  There&#8217;s a couple of ways you can achieve this- either using <a href="http://msdn.microsoft.com/en-us/library/8zha3xws.aspx">RegistryKey.OpenRemoteBaseKey</a> which gave me a whole bunch of permissions issues, plus you need the remote registry and remote administration services active on the server/client OR you can use the Windows Management Instrumentation (WMI) service.  I took this route, as it&#8217;s a service which is active by default on all of our machines on the domain, and it was easier to get the permissions right.  </p>
<p>Before I paste the code, a GOTCHA to beware of, straight from the MSDN <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa392722(v=vs.85).aspx">here</a>;</p>
<blockquote><p>The registry provider is hosted in LocalService—not the LocalSystem. Therefore, obtaining information remotely from the subtree HKEY_CURRENT_USER is not possible</p></blockquote>
<pre class="brush: csharp">
ConnectionOptions options = new ConnectionOptions();
options.Impersonation = ImpersonationLevel.Impersonate;
options.EnablePrivileges = true;
options.Username = &quot;&lt;domain_admin_username&gt;&quot;;
options.Password = &quot;&lt;domain_admin_password&gt;&quot;;

// http://msdn.microsoft.com/en-us/library/system.management.managementscope.aspx
ManagementScope ms = new ManagementScope(&quot;\\\\&lt;computer name&gt;\\root\\default&quot;, options);          

ms.Connect();

// http://msdn.microsoft.com/en-us/library/windows/desktop/aa390788(v=vs.85).aspx
ManagementClass mc = new ManagementClass(&quot;stdRegProv&quot;);
mc.Scope = ms;

ManagementBaseObject inParams = mc.GetMethodParameters(&quot;GetStringValue&quot;);
// there are other methods for grabbing other reg types- see
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa393664(v=VS.85).aspx

inParams[&quot;hDefKey&quot;] = RegHive.HKEY_LOCAL_MACHINE;
inParams[&quot;sSubKeyName&quot;] = &quot;SOFTWARE\\Microsoft\\Windows\\CurrentVersion&quot;;
inParams[&quot;sValueName&quot;] = &quot;CommonFilesDir&quot;;

ManagementBaseObject outParams =
        mc.InvokeMethod(&quot;GetStringValue&quot;, inParams, null);

if (outParams[&quot;ReturnValue&quot;].ToString() == &quot;0&quot;)
{
    Console.WriteLine(outParams[&quot;sValue&quot;]);
}
else
{
    Console.WriteLine(&quot;Error &quot; + outParams[&quot;ReturnValue&quot;] + &quot; please refer to http://msdn.microsoft.com/en-us/library/ms681382%28v=3Dvs.85%29.aspx&quot;);
}

Console.ReadLine();
</pre>
<p>This code requires this enum..</p>
<pre class="brush: csharp">
public enum RegHive : uint
{
  HKEY_CLASSES_ROOT = 0x80000000,
  HKEY_CURRENT_USER = 0x80000001,
  HKEY_LOCAL_MACHINE = 0x80000002,
  HKEY_USERS = 0x80000003,
  HKEY_CURRENT_CONFIG = 0x80000005
}
</pre>
<p>If you receive a COM error back &#8220;The RPC server is unavailable&#8221;, make sure the target machine&#8217;s firewall isn&#8217;t blocking the call- this will open the port;<br />
<code>netsh firewall set service RemoteAdmin</code></p>


<p>Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/using-urlencode-urldecode-and-other-http-functions-from-a-non-web-file/' rel='bookmark' title='Using URLEncode, URLDecode and other Http functions from a non Web file'>Using URLEncode, URLDecode and other Http functions from a non Web file</a></li>
<li><a href='http://codeblog.shawson.co.uk/wcf-404-3-errors/' rel='bookmark' title='WCF 404.3 Errors'>WCF 404.3 Errors</a></li>
<li><a href='http://codeblog.shawson.co.uk/making-your-wcf-service-compatible-with-legacy-net-1-1-applications/' rel='bookmark' title='Making your WCF Service compatible with legacy .net 1.1 applications'>Making your WCF Service compatible with legacy .net 1.1 applications</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://codeblog.shawson.co.uk/grabbing-data-from-the-registry-on-a-remote-machine-using-dot-net-and-wmi/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ninject + WCF Docs</title>
		<link>http://codeblog.shawson.co.uk/ninject-wcf-docs/</link>
		<comments>http://codeblog.shawson.co.uk/ninject-wcf-docs/#comments</comments>
		<pubDate>Wed, 05 Oct 2011 13:22:08 +0000</pubDate>
		<dc:creator>shawson</dc:creator>
				<category><![CDATA[C#.net]]></category>
		<category><![CDATA[OO Design]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://codeblog.shawson.co.uk/?p=1262</guid>
		<description><![CDATA[I&#8217;ve recently started using Ninject, having previously only used Unity as my IoC container, but it seems the internet is scarce of any documentation. I&#8217;ve employed the WCF extension, and found this handy guide on how to get up and going with it. www.aaronstannard.com/post/2011/08/16/dependency-injection-ninject-wcf-service.aspx ps- This is my 200th blog post! Woohoo! Related posts:C# Dynamic [...]


Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/c-dynamic-keyword-and-how-you-can-use-it-to-help-tdd/' rel='bookmark' title='C# Dynamic keyword, and how you can use it to help TDD!'>C# Dynamic keyword, and how you can use it to help TDD!</a></li>
<li><a href='http://codeblog.shawson.co.uk/getting-started-with-wcf-and-rest-web-services/' rel='bookmark' title='Getting started with WCF and REST web services'>Getting started with WCF and REST web services</a></li>
<li><a href='http://codeblog.shawson.co.uk/making-your-wcf-service-compatible-with-legacy-net-1-1-applications/' rel='bookmark' title='Making your WCF Service compatible with legacy .net 1.1 applications'>Making your WCF Service compatible with legacy .net 1.1 applications</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve recently started using Ninject, having previously only used Unity as my IoC container, but it seems the internet is scarce of any documentation.  I&#8217;ve employed the WCF extension, and found this handy guide on how to get up and going with it.  <a href="http://www.aaronstannard.com/post/2011/08/16/dependency-injection-ninject-wcf-service.aspx" target="_blank">www.aaronstannard.com/post/2011/08/16/dependency-injection-ninject-wcf-service.aspx</a></p>
<p>ps- This is my 200th blog post! Woohoo!</p>


<p>Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/c-dynamic-keyword-and-how-you-can-use-it-to-help-tdd/' rel='bookmark' title='C# Dynamic keyword, and how you can use it to help TDD!'>C# Dynamic keyword, and how you can use it to help TDD!</a></li>
<li><a href='http://codeblog.shawson.co.uk/getting-started-with-wcf-and-rest-web-services/' rel='bookmark' title='Getting started with WCF and REST web services'>Getting started with WCF and REST web services</a></li>
<li><a href='http://codeblog.shawson.co.uk/making-your-wcf-service-compatible-with-legacy-net-1-1-applications/' rel='bookmark' title='Making your WCF Service compatible with legacy .net 1.1 applications'>Making your WCF Service compatible with legacy .net 1.1 applications</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://codeblog.shawson.co.uk/ninject-wcf-docs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Conditional DataAnnotations in c#</title>
		<link>http://codeblog.shawson.co.uk/conditional-dataannotations-in-c/</link>
		<comments>http://codeblog.shawson.co.uk/conditional-dataannotations-in-c/#comments</comments>
		<pubDate>Thu, 15 Sep 2011 10:49:55 +0000</pubDate>
		<dc:creator>shawson</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[C#.net]]></category>

		<guid isPermaLink="false">http://codeblog.shawson.co.uk/?p=1250</guid>
		<description><![CDATA[This is something a bit weird, which maybe even, dare I say, a bug in the .net DataAnnotationsExtensions pack (Installable via NuGet). I decorated one of my class properties with an Email data annotation, because If the class had an email set, I wanted to ensure it was valid. I didn&#8217;t, however, decorate it with [...]


Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/mvc-strongly-typed-view-returns-a-null-model-on-post-back/' rel='bookmark' title='MVC strongly typed view returns a null model on post back'>MVC strongly typed view returns a null model on post back</a></li>
<li><a href='http://codeblog.shawson.co.uk/creating-an-order-order-details-style-form-using-asp-net-mvc2-entity-framework/' rel='bookmark' title='Creating an Order/ Order Details style view using ASP.net MVC2 &amp; Entity Framework 4'>Creating an Order/ Order Details style view using ASP.net MVC2 &#038; Entity Framework 4</a></li>
<li><a href='http://codeblog.shawson.co.uk/premailer-%e2%80%94-preflight-for-html-e-mail/' rel='bookmark' title='Premailer — preflight for HTML e-mail'>Premailer — preflight for HTML e-mail</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>This is something a bit weird, which maybe even, dare I say, a bug in the .net <a href="http://dataannotationsextensions.org/" target="_blank">DataAnnotationsExtensions pack</a> (Installable via NuGet).  I decorated one of my class properties with an Email data annotation, because If the class had an email set, I wanted to ensure it was valid.  I didn&#8217;t, however, decorate it with a Required attribute.  However it seems the Email attribute will return false if no value is passed, ensuring that it is infact required?  (Please leave a comment if there is some really obvious built in way around this!)  </p>
<p>To get around this I created a simple &#8220;IfPresent&#8221; data annotation which you can chain another validation onto;  This basically returns a true if the value is null, otherwise it will pass it on to the real ValidationAttribute to work it&#8221;s magic.  It can be implemented like this;</p>
<pre class="brush: csharp">
[DataMember]
[IfPresent(typeof(EmailAttribute), ErrorMessage = &quot;Must be a valid email address&quot;)]
public string EmailAddress { get; set; }
</pre>
<p>The code is;</p>
<pre class="brush: csharp">
namespace Chinook.Model.ValidationAttributes
{
    public class IfPresent : ValidationAttribute
    {
        private ValidationAttribute attr;

        public IfPresent(Type attr)
        {
            this.attr = (ValidationAttribute)Activator.CreateInstance(attr);
        }

        public override bool IsValid(object value)
        {
            if (value == null)
                return true;

            return attr.IsValid(value);
        }
    }
}
</pre>


<p>Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/mvc-strongly-typed-view-returns-a-null-model-on-post-back/' rel='bookmark' title='MVC strongly typed view returns a null model on post back'>MVC strongly typed view returns a null model on post back</a></li>
<li><a href='http://codeblog.shawson.co.uk/creating-an-order-order-details-style-form-using-asp-net-mvc2-entity-framework/' rel='bookmark' title='Creating an Order/ Order Details style view using ASP.net MVC2 &amp; Entity Framework 4'>Creating an Order/ Order Details style view using ASP.net MVC2 &#038; Entity Framework 4</a></li>
<li><a href='http://codeblog.shawson.co.uk/premailer-%e2%80%94-preflight-for-html-e-mail/' rel='bookmark' title='Premailer — preflight for HTML e-mail'>Premailer — preflight for HTML e-mail</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://codeblog.shawson.co.uk/conditional-dataannotations-in-c/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Refactoring a web project so you can share user controls across others</title>
		<link>http://codeblog.shawson.co.uk/sharing-user-controls-between-web-projects/</link>
		<comments>http://codeblog.shawson.co.uk/sharing-user-controls-between-web-projects/#comments</comments>
		<pubDate>Thu, 11 Aug 2011 07:57:06 +0000</pubDate>
		<dc:creator>shawson</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[C#.net]]></category>

		<guid isPermaLink="false">http://codeblog.shawson.co.uk/?p=1135</guid>
		<description><![CDATA[I recently built a brand new site, which launched last week and have now been tasked with adding an additional B2B component to it. The B2B site will have all the same styling as the B2C site, and will share a lot of functionality that I&#8217;ve already written into User Controls for the main web [...]


Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/asp-net-build-step-to-minify-and-obfuscate-your-sites-javascript-and-css/' rel='bookmark' title='Adding minification and obfuscation of your Javascript and CSS to your ASP.net build process using Yahoo YUI Compressor'>Adding minification and obfuscation of your Javascript and CSS to your ASP.net build process using Yahoo YUI Compressor</a></li>
<li><a href='http://codeblog.shawson.co.uk/how-to-display-hierarchical-data-by-using-nested-repeater-controls-and-visual-c-net/' rel='bookmark' title='How To Display Hierarchical Data Using Nested Repeater Controls and Visual C# .NET'>How To Display Hierarchical Data Using Nested Repeater Controls and Visual C# .NET</a></li>
<li><a href='http://codeblog.shawson.co.uk/quickly-find-open-a-file-in-visual-studio/' rel='bookmark' title='Quickly Find/ Open a file in Visual Studio'>Quickly Find/ Open a file in Visual Studio</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>I recently built a brand new site, which launched last week and have now been tasked with adding an additional B2B component to it.  The B2B site will have all the same styling as the B2C site, and will share a lot of functionality that I&#8217;ve already written into User Controls for the main web site.  So I was faced with a problem- How can I share these controls across both projects?  I don&#8217;t want to simply copy and paste, because then I have two controls to maintain, so I took to Google where I found <a href="http://weblogs.asp.net/scottgu/archive/2005/08/28/423888.aspx">this old article by Scott Guthrie</a>.</p>
<p>I figured I would document the re-factoring exercise I went through.</p>
<p>So I started with my main web project which looked like this;</p>
<p><a href="http://codeblog.shawson.co.uk/wp-content/uploads/2011/08/before.png"><img src="http://codeblog.shawson.co.uk/wp-content/uploads/2011/08/before.png" alt="" title="before" width="351" height="433" class="aligncenter size-full wp-image-1137" /></a></p>
<p>I shall break down the refactor into some simple steps;</p>
<ol>
<li>
I created a new class library project which could be shared between the two web projects, in this instance I called mine Chinook.Web.Helpers</li>
<li>
Create a &#8220;Controls&#8221; folder and drag all the controls from the original web project, into the new shared projects control folder (Make sure both the ASPX and the code behind parts came across!).  Build the new shared project- you will probably find some build errors and will need to add references to some web specific .net dll&#8217;s- I needed
<ul>
<li>System.Configuration</li>
<li>System.Web</li>
<li>System.Web.Extensions</li>
<li>System.Web.Extensions.Design</li>
<li>System.Web.Services</li>
</ul>
<p>As well as these I also had to add references to my .Model and .Interfaces projects, but this will be different depending on how you&#8217;ve setup your project.  At this stage I had a projects which built and looked like this;</p>
<p><a href="http://codeblog.shawson.co.uk/wp-content/uploads/2011/08/helper.png"><img src="http://codeblog.shawson.co.uk/wp-content/uploads/2011/08/helper.png" alt="" title="helper" width="346" height="476" class="aligncenter size-full wp-image-1141" /></a>
</li>
<li>
  I updated the namespace for each controls code behind and the first line of each ascx to reflect the namespace of the new project;</p>
<pre class="brush: csharp">
//namespace Chinook.Web.Controls
namespace Chinook.Web.Helpers.Controls
{
    public partial class QuickContact : System.Web.UI.UserControl
</pre>
<p>..and the new inherits parameters in the ascx;</p>
<pre class="brush: html">
&lt;%@ Control Language=&quot;C#&quot; AutoEventWireup=&quot;true&quot; CodeBehind=&quot;QuickContact.ascx.cs&quot;
    Inherits=&quot;Chinook.Web.Helpers.Controls.QuickContact&quot; %&gt;
</pre>
</li>
<li>Next I added a reference in my web project to the new shared project, then deleted the controls from my controls folder, leaving an empty controls folder.  All the references to the controls in your pages remain the same; for example
<pre class="brush: html">
&lt;%@ Master Language=&quot;C#&quot; AutoEventWireup=&quot;True&quot; CodeBehind=&quot;Site.master.cs&quot; Inherits=&quot;Chinook.Web.SiteMaster&quot; %&gt;
&lt;%@ Register Src=&quot;Controls/RSSLister.ascx&quot; TagName=&quot;RSSLister&quot; TagPrefix=&quot;uc1&quot; %&gt;
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head runat=&quot;server&quot;&gt;
...
&lt;ul id=&quot;rss&quot; class=&quot;orange-bullets&quot;&gt;
  &lt;uc1:RSSLister ID=&quot;BlogRSSFeed&quot; runat=&quot;server&quot; /&gt;
&lt;/ul&gt;
</pre>
</li>
<li>
So the project is now happy- we just need to add the pre-build step which will copy the ascx files (but not the code behind) over to each projects control folder on pre-build.  So in the original web project, right click the project and go to properties -> Build Events and set the pre-build event so that it copies;</p>
<pre>
copy $(SolutionDir)\Chinook.Web.Helpers\Controls\*.ascx $(ProjectDir)\Controls\
</pre>
</li>
<li>Build and run your web project!</li>
</ol>
<p>I also moved over a few other bits.  I had an ashx file which handles file uploads- so I moved the code behind to the shared projects and just updated the ashx file to inherit from the same class, but in it&#8217;s new namespace.  I also had a resx file which contained user friendly error messages which I moved to be central.  My final helper looked like this;<br />
<a href="http://codeblog.shawson.co.uk/wp-content/uploads/2011/08/finished-helper.png"><img src="http://codeblog.shawson.co.uk/wp-content/uploads/2011/08/finished-helper.png" alt="" title="finished-helper" width="346" height="605" class="aligncenter size-full wp-image-1146" /></a></p>
<p>Make sure that you don&#8217;t edit the ascx files that now exist within your web project, as there will be overwritten by the versions in the shared project everytime you re-build.  </p>
<p>If you use the publish option (you probably do!), make sure you &#8220;show all files&#8221; on your web project after a build include the ascx files into your web project, so it gets copied up.</p>


<p>Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/asp-net-build-step-to-minify-and-obfuscate-your-sites-javascript-and-css/' rel='bookmark' title='Adding minification and obfuscation of your Javascript and CSS to your ASP.net build process using Yahoo YUI Compressor'>Adding minification and obfuscation of your Javascript and CSS to your ASP.net build process using Yahoo YUI Compressor</a></li>
<li><a href='http://codeblog.shawson.co.uk/how-to-display-hierarchical-data-by-using-nested-repeater-controls-and-visual-c-net/' rel='bookmark' title='How To Display Hierarchical Data Using Nested Repeater Controls and Visual C# .NET'>How To Display Hierarchical Data Using Nested Repeater Controls and Visual C# .NET</a></li>
<li><a href='http://codeblog.shawson.co.uk/quickly-find-open-a-file-in-visual-studio/' rel='bookmark' title='Quickly Find/ Open a file in Visual Studio'>Quickly Find/ Open a file in Visual Studio</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://codeblog.shawson.co.uk/sharing-user-controls-between-web-projects/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Adding minification and obfuscation of your Javascript and CSS to your ASP.net build process using Yahoo YUI Compressor</title>
		<link>http://codeblog.shawson.co.uk/asp-net-build-step-to-minify-and-obfuscate-your-sites-javascript-and-css/</link>
		<comments>http://codeblog.shawson.co.uk/asp-net-build-step-to-minify-and-obfuscate-your-sites-javascript-and-css/#comments</comments>
		<pubDate>Fri, 22 Jul 2011 08:00:29 +0000</pubDate>
		<dc:creator>shawson</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[C#.net]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://codeblog.shawson.co.uk/?p=1104</guid>
		<description><![CDATA[I&#8217;ve just finished integrating Yahoo&#8217;s YUI Compressor into the MSBuild process for a new web probject I&#8217;m working on, and I thought I would document the process as there doesn;t seem to be a start to finish guide about anywhere. To start with, let me just explain the structure I use for new Solutions; C:\_Dev\MyNewWebsite\ [...]


Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/entity-framework-the-data-reader-is-incompatible-with-the-specified-complex-type/' rel='bookmark' title='Entity Framework &#8220;The data reader is incompatible with the specified complex type.&#8221;'>Entity Framework &#8220;The data reader is incompatible with the specified complex type.&#8221;</a></li>
<li><a href='http://codeblog.shawson.co.uk/javascript-css-minification/' rel='bookmark' title='Javascript &amp; CSS Minification'>Javascript &#038; CSS Minification</a></li>
<li><a href='http://codeblog.shawson.co.uk/asp-net-update-panels-and-jquery/' rel='bookmark' title='ASP.net update panel&#8217;s and jQuery'>ASP.net update panel&#8217;s and jQuery</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve just finished integrating Yahoo&#8217;s YUI Compressor into the MSBuild process for a new web probject I&#8217;m working on, and I thought I would document the process as there doesn;t seem to be a start to finish guide about anywhere.</p>
<p>To start with, let me just explain the structure I use for new Solutions;</p>
<pre>
C:\_Dev\MyNewWebsite\
C:\_Dev\MyNewWebsite\Artwork\
C:\_Dev\MyNewWebsite\BuildTools\
C:\_Dev\MyNewWebsite\Docs\
C:\_Dev\MyNewWebsite\Source\
C:\_Dev\MyNewWebsite\Source\MyNewWebsite.sln
C:\_Dev\MyNewWebsite\Source\MyNewWebsite.Web\
C:\_Dev\MyNewWebsite\Source\MyNewWebsite.Web\Controls\
C:\_Dev\MyNewWebsite\Source\MyNewWebsite.Web\Images\
C:\_Dev\MyNewWebsite\Source\MyNewWebsite.Web\Scripts\
C:\_Dev\MyNewWebsite\Source\MyNewWebsite.Web\Services\
C:\_Dev\MyNewWebsite\Source\MyNewWebsite.Web\Styles\
C:\_Dev\MyNewWebsite\Source\MyNewWebsite.Web\MyNewWebsiteWeb.csproj
C:\_Dev\MyNewWebsite\Source\MyNewWebsite.Entities\
C:\_Dev\MyNewWebsite\Source\MyNewWebsite.Entities\MyNewWebsiteEntities.csproj
C:\_Dev\MyNewWebsite\Source\MyNewWebsite.Interfaces\
C:\_Dev\MyNewWebsite\Source\MyNewWebsite.Interfaces\MyNewWebsiteInterfaces.csproj
C:\_Dev\MyNewWebsite\ThirdParty\
</pre>
<p>Firstly, download the <a href="http://yuicompressor.codeplex.com/">dot net port of the YUI compressor from codeplex</a>.  I then extracted this into a new folder in the BuildTools folder. (there should be 2 dll files and one txt licence file.)</p>
<p>I then created a new MSBuild file called build-minify.xml, in the MyNewWebsite.Web project folder.  That file looks like this;</p>
<pre class="brush: xml">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;!-- http://yuicompressor.codeplex.com/wikipage?title=Sample%20MSBuild.xml%20File&amp;amp;amp;amp;amp;amp;ProjectName=yuicompressor --&gt;
&lt;Project DefaultTargets=&quot;Build&quot; xmlns=&quot;http://schemas.microsoft.com/developer/msbuild/2003&quot;&gt;
  &lt;UsingTask
         TaskName=&quot;CompressorTask&quot;
         AssemblyFile=&quot;..\..\BuildTools\Yahoo.Yui.Compressor-v1.5.0.0\Yahoo.Yui.Compressor.dll&quot; /&gt;

  &lt;ItemGroup&gt;
    &lt;CssFiles Include=&quot;$(SourceLocation)Styles\Fonts.css&quot;/&gt;
    &lt;CssFiles Include=&quot;$(SourceLocation)Styles\Site.css&quot;/&gt;

    &lt;CssIE Include=&quot;$(SourceLocation)Styles\IE.css&quot;/&gt;
    &lt;CssIE6 Include=&quot;$(SourceLocation)Styles\IE6.css&quot;/&gt;

    &lt;JsAll Include=&quot;$(SourceLocation)Scripts\jquery-1.6.1.min.js&quot; /&gt;
    &lt;JsAll Include=&quot;$(SourceLocation)Scripts\jquery-ui-1.8.14.custom.min.js&quot; /&gt;
    &lt;JsAll Include=&quot;$(SourceLocation)Scripts\json2.js&quot; /&gt;
    &lt;JsAll Include=&quot;$(SourceLocation)Scripts\jqModal-r14.js&quot; /&gt;
    &lt;JsAll Include=&quot;$(SourceLocation)Scripts\jquery.tipsy.js&quot; /&gt;
    &lt;JsAll Include=&quot;$(SourceLocation)Scripts\jquery.scrollTo-1.4.2.min.js&quot; /&gt;
    &lt;JsAll Include=&quot;$(SourceLocation)Scripts\jquery.localscroll-1.2.7.min.js&quot; /&gt;
    &lt;JsAll Include=&quot;$(SourceLocation)Scripts\chinook-alert.js&quot; /&gt;
    &lt;JsAll Include=&quot;$(SourceLocation)Scripts\chinook-validation.js&quot; /&gt;
    &lt;JsAll Include=&quot;$(SourceLocation)Scripts\chinook-rollovers.js&quot; /&gt;
    &lt;JsAll Include=&quot;$(SourceLocation)Scripts\chinook-custom-accordion.js&quot; /&gt;
    &lt;JsAll Include=&quot;$(SourceLocation)Scripts\chinook-vehicle-lookup.js&quot; /&gt;
    &lt;JsAll Include=&quot;$(SourceLocation)Scripts\chinook-sandbox.js&quot; /&gt;
    &lt;JsAll Include=&quot;$(SourceLocation)Scripts\chinook-finance-calculator.js&quot; /&gt;
    &lt;JsAll Include=&quot;$(SourceLocation)Scripts\chinook-apply-now.js&quot; /&gt;

  &lt;/ItemGroup&gt;

  &lt;Target Name=&quot;Minimize&quot;&gt;
    &lt;CompressorTask
              CssFiles=&quot;@(CssFiles)&quot;
              DeleteCssFiles=&quot;false&quot;
              CssOutputFile=&quot;Styles/Site.rel.css&quot;
              CssCompressionType=&quot;YuiStockCompression&quot;
              DisableOptimizations=&quot;Nope&quot;
              EncodingType=&quot;Default&quot;
              LineBreakPosition=&quot;-1&quot;
              LoggingType=&quot;ALittleBit&quot;
              ThreadCulture=&quot;en-gb&quot;
              IsEvalIgnored=&quot;false&quot;
            /&gt;

    &lt;CompressorTask
              CssFiles=&quot;@(CssIE)&quot;
              DeleteCssFiles=&quot;false&quot;
              CssOutputFile=&quot;Styles/IE.rel.css&quot;
              CssCompressionType=&quot;YuiStockCompression&quot;
              DisableOptimizations=&quot;Nope&quot;
              EncodingType=&quot;Default&quot;
              LineBreakPosition=&quot;-1&quot;
              LoggingType=&quot;ALittleBit&quot;
              ThreadCulture=&quot;en-gb&quot;
              IsEvalIgnored=&quot;false&quot;
            /&gt;

    &lt;CompressorTask
              CssFiles=&quot;@(CssIE6)&quot;
              DeleteCssFiles=&quot;false&quot;
              CssOutputFile=&quot;Styles/IE6.rel.css&quot;
              CssCompressionType=&quot;YuiStockCompression&quot;
              DisableOptimizations=&quot;Nope&quot;
              EncodingType=&quot;Default&quot;
              LineBreakPosition=&quot;-1&quot;
              LoggingType=&quot;ALittleBit&quot;
              ThreadCulture=&quot;en-gb&quot;
              IsEvalIgnored=&quot;false&quot;
            /&gt;

    &lt;CompressorTask
      JavaScriptFiles=&quot;@(JsAll)&quot;
      ObfuscateJavaScript=&quot;true&quot;
      PreserveAllSemicolons=&quot;true&quot;
      DisableOptimizations=&quot;false&quot;
      EncodingType=&quot;Default&quot;
      DeleteJavaScriptFiles=&quot;false&quot;
      LineBreakPosition=&quot;-1&quot;
      JavaScriptOutputFile=&quot;Scripts/chinook.rel.js&quot;
      LoggingType=&quot;ALittleBit&quot;
      ThreadCulture=&quot;en-gb&quot;
      IsEvalIgnored=&quot;false&quot;
		/&gt;
  &lt;/Target&gt;
&lt;/Project&gt;
</pre>
<p>You can create whatever ItemGroups you&#8217;d like- then just create a compressor task for each.  For a rundown of the settings, check out the link in the comment at the top of the XML there.  In the above file I had decided to compress all of my Javascript into a single file called chinook.rel.js, and my fonts and site css file rolled into one file, keeping the ie6 css separate, but still minifying it down.</p>
<p>The next step is to add it to the normal build.  I opened the solution in Visual Studio, right clicked my web project and selected properties.  Go to &#8220;Build Events&#8221; and add the following post-build event;</p>
<pre>
$(MSBuildBinPath)\msbuild.exe  $(ProjectDir)build-minify.xml /target:Minimize
</pre>
<p>Now you can test it out by building your project.  The new minified files are dumped out, in my case to the Scripts folder.  Now that the files are there, I need a way of telling my release version of the website to use these instead of the raw, human-readable versions; but I still want to continue using the human-readable versions for development.</p>
<p>To achieve this I use pre-processor directives.  These are most commonly seen in the c# code behind files, but can also be used in the aspx files.  I added the following lines at the bottom of my master page;</p>
<pre class="brush: html">
    &lt;% #if (!DEBUG) %&gt;
    &lt;script src=&quot;Scripts/chinook.rel.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;% #else %&gt;
    &lt;script src=&quot;Scripts/jquery-1.6.1.min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;Scripts/jqModal-r14.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;Scripts/chinook-alert.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;Scripts/jquery-ui-1.8.14.custom.min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;Scripts/chinook-vehicle-lookup.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;Scripts/chinook-sandbox.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;Scripts/chinook-finance-calculator.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;Scripts/jquery.scrollTo-1.4.2.min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;Scripts/jquery.localscroll-1.2.7.min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;Scripts/jquery.tipsy.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;Scripts/json2.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;Scripts/chinook-validation.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;Scripts/chinook-apply-now.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;Scripts/chinook-rollovers.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;Scripts/chinook-custom-accordion.js&quot;&gt;&lt;/script&gt;
    &lt;% #endif %&gt;
</pre>
<p>So if the project is NOT running in debug mode, I import my full chinook.rel.js include which has everything already included, otherwise I manually include all the human readable, separate files.</p>
<p>And that&#8217;s pretty much it.  Make sure you thoroughly retest your site with your combined java script file, as sometimes minification can cause issues with some code.  </p>


<p>Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/entity-framework-the-data-reader-is-incompatible-with-the-specified-complex-type/' rel='bookmark' title='Entity Framework &#8220;The data reader is incompatible with the specified complex type.&#8221;'>Entity Framework &#8220;The data reader is incompatible with the specified complex type.&#8221;</a></li>
<li><a href='http://codeblog.shawson.co.uk/javascript-css-minification/' rel='bookmark' title='Javascript &amp; CSS Minification'>Javascript &#038; CSS Minification</a></li>
<li><a href='http://codeblog.shawson.co.uk/asp-net-update-panels-and-jquery/' rel='bookmark' title='ASP.net update panel&#8217;s and jQuery'>ASP.net update panel&#8217;s and jQuery</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://codeblog.shawson.co.uk/asp-net-build-step-to-minify-and-obfuscate-your-sites-javascript-and-css/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Entity Framework 4.1 Code First (With One to Many relationship) Code Example</title>
		<link>http://codeblog.shawson.co.uk/entity-framework-4-1-code-first-with-one-to-many-relationship-code-example/</link>
		<comments>http://codeblog.shawson.co.uk/entity-framework-4-1-code-first-with-one-to-many-relationship-code-example/#comments</comments>
		<pubDate>Sun, 10 Jul 2011 20:43:50 +0000</pubDate>
		<dc:creator>shawson</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[C#.net]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://codeblog.shawson.co.uk/?p=1091</guid>
		<description><![CDATA[A quick piece of code demo&#8217;ing a very common/ simple usage scenario- basic one to many with some demo data being seeded into the database; I thought this might be needed as I&#8217;ve waded through a LOT of exmaples for various beta versions and different releases of EF, but had little luck actually finding something [...]


Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/linq-distinct/' rel='bookmark' title='Linq Distinct!'>Linq Distinct!</a></li>
<li><a href='http://codeblog.shawson.co.uk/syndicating-to-rss-using-the-build-in-net-syndicationfeed-classes/' rel='bookmark' title='Syndicating to RSS using the built in .net SyndicationFeed classes'>Syndicating to RSS using the built in .net SyndicationFeed classes</a></li>
<li><a href='http://codeblog.shawson.co.uk/creating-an-order-order-details-style-form-using-asp-net-mvc2-entity-framework/' rel='bookmark' title='Creating an Order/ Order Details style view using ASP.net MVC2 &amp; Entity Framework 4'>Creating an Order/ Order Details style view using ASP.net MVC2 &#038; Entity Framework 4</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>A quick piece of code demo&#8217;ing a very common/ simple usage scenario- basic one to many with some demo data being seeded into the database; I thought this might be needed as I&#8217;ve waded through a LOT of exmaples for various beta versions and different releases of EF, but had little luck actually finding something relevant.  The best site I came across was tucked away on the ADO.net team&#8217;s blog- <a href="http://blogs.msdn.com/b/adonet/archive/2011/01/27/using-dbcontext-in-ef-feature-ctp5-part-1-introduction-and-model.aspx">Using DbContext in EF 4.1</a>.  First&#8211; the entities and the database context</p>
<pre class="brush: csharp">
    public class Category
    {
        [Key]
        public Guid ID { get; set; }

        public string Title { get; set; }
        public virtual ICollection&lt;Product&gt; Products { get; set; }
                   //virtual makes this lazily loaded

        public Category()
        {
            this.ID = Guid.NewGuid();
        }
    }

    public class Product
    {
        [Key]
        public Guid ID { get; set; }

        public string Title { get; set; }
        public string Details { get; set; }
        public double Price { get; set; }
        public string ImageFileName { get; set; }

        public DateTime DateAdded { get; set; }

        public virtual Category Category { get; set; }
                   //virtual makes this lazily loaded

        public Product()
        {
            this.ID = Guid.NewGuid();
        }
    }

    public class MyDBContext: DbContext
    {
        public DbSet&lt;Product&gt; Products { get; set; }
        public DbSet&lt;Category&gt; Categories { get; set; }
    }
</pre>
<p>Note the use of ICollection on Products in Category, and the use of DbSet in the context.  I used a DbSet in lieu of ICollection on the Products entity and found it went mental if I had a Product with no category (something which I wanted to be valid) &#8211; swapping it to ICollection fixed this issue (I don&#8217;t know enough of the inner workings to explain why) </p>
<p>BAMM!  Next for the seeding- add a class like so;</p>
<pre class="brush: csharp">
    public class MyDBInitializer : DropCreateDatabaseAlways&lt;MyDBContext&gt;
    {
        protected override void Seed(Entities.ComicolleDB context)
        {
            Category marvel = new Category()
            {
                Title = &quot;Category 1&quot;
            };
            Category dc = new Category()
            {
                Title = &quot;Category 2&quot;
            };

            context.Categories.Add(marvel);
            context.Categories.Add(dc);

            context.Products.Add(new Product()
            {
                Title = &quot;Test1&quot;,
                ImageFileName = &quot;image-1.gif&quot;,
                Details = &quot;This is a test&quot;,
                Price = 4.99,
                DateAdded = DateTime.Now,
                Category = marvel
            });

            context.Products.Add(new Product()
            {
                Title = &quot;Test2&quot;,
                ImageFileName = &quot;image-1.gif&quot;,
                Details = &quot;This is a test&quot;,
                Price = 4.99,
                DateAdded = DateTime.Now,
                Category = dc
            });

            context.Products.Add(new Product()  // no category
            {
                Title = &quot;Test3&quot;,
                ImageFileName = &quot;image-1.gif&quot;,
                Details = &quot;This is a test&quot;,
                Price = 4.99,
                DateAdded = DateTime.Now
            });

            context.SaveChanges();
        }
    }
</pre>
<p>Then add the following line to the end of your Application_Start() method in global.asax;</p>
<pre class="brush: csharp">
Database.SetInitializer&lt;MyDBContext&gt;(new MyDBInitializer());
</pre>
<p>Voila- you can then go ahead and use your model in whatever applications you see fit- here are some example;</p>
<pre class="brush: csharp">
MyDBContext db = new MyDBContext();

// get a category, and make sure the products are loaded
Category the_category = db.Categories.Include(&quot;Products&quot;)
                           .Where(x =&gt; x.Title == &quot;Category 1&quot;).SingleOrDefault();

// get all the products for that category
List&lt;Product&gt; some_products = the_category.Products;

// get all the categories (without loading the products)
List&lt;Category&gt; some_categories = db.Categories.ToList();
</pre>


<p>Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/linq-distinct/' rel='bookmark' title='Linq Distinct!'>Linq Distinct!</a></li>
<li><a href='http://codeblog.shawson.co.uk/syndicating-to-rss-using-the-build-in-net-syndicationfeed-classes/' rel='bookmark' title='Syndicating to RSS using the built in .net SyndicationFeed classes'>Syndicating to RSS using the built in .net SyndicationFeed classes</a></li>
<li><a href='http://codeblog.shawson.co.uk/creating-an-order-order-details-style-form-using-asp-net-mvc2-entity-framework/' rel='bookmark' title='Creating an Order/ Order Details style view using ASP.net MVC2 &amp; Entity Framework 4'>Creating an Order/ Order Details style view using ASP.net MVC2 &#038; Entity Framework 4</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://codeblog.shawson.co.uk/entity-framework-4-1-code-first-with-one-to-many-relationship-code-example/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Netgear ReadyNAS Duo command line shut down utility</title>
		<link>http://codeblog.shawson.co.uk/netgear-readynas-duo-command-line-shut-down-utility/</link>
		<comments>http://codeblog.shawson.co.uk/netgear-readynas-duo-command-line-shut-down-utility/#comments</comments>
		<pubDate>Mon, 04 Jul 2011 21:20:45 +0000</pubDate>
		<dc:creator>shawson</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[C#.net]]></category>
		<category><![CDATA[Networking]]></category>

		<guid isPermaLink="false">http://codeblog.shawson.co.uk/?p=1082</guid>
		<description><![CDATA[So I finished the backup app and compiled it for anyone who wants it- it&#8217;s used from the command prompt like so; ShutdownNASBox -h &#60;hostname&#62; -u &#60;username&#62; -p &#60;password&#62; eg. ShutdownNASBox -h backup -u admin -p abc123 If you run the tool with administrator privileges, it will log to the Windows Event Log on the System [...]


Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/asp-net-roles-and-membership-installed-to-local-sql-express-2008-mdf-file/' rel='bookmark' title='ASP.net Roles and Membership installed to local SQL Express 2008 MDF file'>ASP.net Roles and Membership installed to local SQL Express 2008 MDF file</a></li>
<li><a href='http://codeblog.shawson.co.uk/automatic-shutdown-of-my-netgear-readynas-duo-network-storage-server/' rel='bookmark' title='Automatic NAS Box shutdown &#8211; How to POST the shutdown command over SSL with HTTP authentication from a dot net Console app (Part 1/2)'>Automatic NAS Box shutdown &#8211; How to POST the shutdown command over SSL with HTTP authentication from a dot net Console app (Part 1/2)</a></li>
<li><a href='http://codeblog.shawson.co.uk/my-shiny-new-blog/' rel='bookmark' title='My shiny new blog'>My shiny new blog</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>So I finished the backup app and compiled it for anyone who wants it- it&#8217;s used from the command prompt like so;<br />
ShutdownNASBox -h &lt;hostname&gt; -u &lt;username&gt; -p &lt;password&gt;</p>
<p>eg.</p>
<p>ShutdownNASBox -h backup -u admin -p abc123</p>
<p>If you run the tool with administrator privileges, it will log to the Windows Event Log on the System tab.</p>
<p><a href="http://codeblog.shawson.co.uk/storage/ShutdownNASBox.zip">You can download it here</a> (note you will need <a href="http://www.microsoft.com/download/en/details.aspx?id=17851">dot net framework 4 installed</a>)</p>


<p>Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/asp-net-roles-and-membership-installed-to-local-sql-express-2008-mdf-file/' rel='bookmark' title='ASP.net Roles and Membership installed to local SQL Express 2008 MDF file'>ASP.net Roles and Membership installed to local SQL Express 2008 MDF file</a></li>
<li><a href='http://codeblog.shawson.co.uk/automatic-shutdown-of-my-netgear-readynas-duo-network-storage-server/' rel='bookmark' title='Automatic NAS Box shutdown &#8211; How to POST the shutdown command over SSL with HTTP authentication from a dot net Console app (Part 1/2)'>Automatic NAS Box shutdown &#8211; How to POST the shutdown command over SSL with HTTP authentication from a dot net Console app (Part 1/2)</a></li>
<li><a href='http://codeblog.shawson.co.uk/my-shiny-new-blog/' rel='bookmark' title='My shiny new blog'>My shiny new blog</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://codeblog.shawson.co.uk/netgear-readynas-duo-command-line-shut-down-utility/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Automatic NAS Box shutdown &#8211; How to POST the shutdown command over SSL with HTTP authentication from a dot net Console app (Part 1/2)</title>
		<link>http://codeblog.shawson.co.uk/automatic-shutdown-of-my-netgear-readynas-duo-network-storage-server/</link>
		<comments>http://codeblog.shawson.co.uk/automatic-shutdown-of-my-netgear-readynas-duo-network-storage-server/#comments</comments>
		<pubDate>Sun, 03 Jul 2011 11:38:56 +0000</pubDate>
		<dc:creator>shawson</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[C#.net]]></category>
		<category><![CDATA[Networking]]></category>
		<category><![CDATA[Authentication]]></category>
		<category><![CDATA[HTTP]]></category>
		<category><![CDATA[Post]]></category>
		<category><![CDATA[SSL]]></category>
		<category><![CDATA[WebClient]]></category>

		<guid isPermaLink="false">http://codeblog.shawson.co.uk/?p=1036</guid>
		<description><![CDATA[I recently purchased a Netgear ReadyNAS Duo RAIDed network storage box for general backup of my &#8216;stuff and things&#8217;, which sit&#8217;s on my desk and runs off the same power as my PC.  A couple of times now I&#8217;ve booted the box up to run a backup, then forgot to shut it down, then shut [...]


Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/netgear-readynas-duo-command-line-shut-down-utility/' rel='bookmark' title='Netgear ReadyNAS Duo command line shut down utility'>Netgear ReadyNAS Duo command line shut down utility</a></li>
<li><a href='http://codeblog.shawson.co.uk/pages-jump-to-the-top-on-post-back-in-aspnet/' rel='bookmark' title='Pages jump to the top on post back in asp.net'>Pages jump to the top on post back in asp.net</a></li>
<li><a href='http://codeblog.shawson.co.uk/mvc-strongly-typed-view-returns-a-null-model-on-post-back/' rel='bookmark' title='MVC strongly typed view returns a null model on post back'>MVC strongly typed view returns a null model on post back</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>I recently purchased a <a href="http://www.readynas.com/?cat=3" target="_blank">Netgear ReadyNAS Duo</a> RAIDed network storage box for general backup of my &#8216;stuff and things&#8217;, which sit&#8217;s on my desk and runs off the same power as my PC.  A couple of times now I&#8217;ve booted the box up to run a backup, then forgot to shut it down, then shut down my PC, flick the switch at the wall and then realise.  When I boot everything back up in a day or so, the NAS box has to do a full system check and maybe rebuild the RAID array if theres a problem etc etc &#8211; it&#8217;s a pain.</p>
<p>So I thought I would set about automating the NAS box shut down with my PC shut down which turned out to be pretty easy.  The NAS box is controller via a web UI- my box has the host name &#8220;BACKUP&#8221; so I can get to it over the browser on http://BACKUP/.  This uses basic HTTP authentication asking me to login, and also use&#8217;s https (which my browser always warns me about because it&#8217;s not from a trusts CA or whatever- so I just ignore the warnings and continue).  From the web UI you can go to the system tab and select shut down and the box goes down.  I figured as this is going to be a simple web call, it should be easy enough to write a simple console app which makes the same call which can be fired on Windows shutdown- so I fired up <a href="http://getfirebug.com/" target="_blank">Firebug</a>, opened the &#8220;Net&#8221; tab, which allows you to inspect all http calls made, and triggered a shut down.  It&#8217;s probably worth noting at this point that the techniques used here could probably be applied to pretty much any other networked device with a web based UI (most routers, firewalls, switches, printers, media boxes etc) so this should hopefully be quite useful.</p>
<p style="text-align: center;"><a href="http://codeblog.shawson.co.uk/wp-content/uploads/2011/07/netgear-frontview.jpg"><img class="aligncenter size-large wp-image-1039" title="netgear-frontview" src="http://codeblog.shawson.co.uk/wp-content/uploads/2011/07/netgear-frontview-981x1024.jpg" alt="" width="550" height="574" /></a></p>
<p style="text-align: left;">Sure enough the HTTPS POST made to a file called get_handler on the root could be seen, with the POST data string;</p>
<p style="text-align: center;"><a href="http://codeblog.shawson.co.uk/wp-content/uploads/2011/07/firebug_post.jpg"><img class="aligncenter size-large wp-image-1043" title="firebug_post" src="http://codeblog.shawson.co.uk/wp-content/uploads/2011/07/firebug_post-1024x565.jpg" alt="" width="574" height="317" /></a></p>
<p style="text-align: left;">As we can see from firebug, the data sent is;</p>
<p style="text-align: left;"><code>PAGE=System&amp;OUTER_TAB=tab_shutdown&amp;INNER_TAB=NONE&amp;shutdown_option1=1&amp;command=poweroff&amp;OPERATION=set</code></p>
<p style="text-align: left;">So six key value pairs separated by ampersands.  The code itself is pretty simple using WebClient class (System.Net namespace)- however there are a couple of complications, which as it happens are fairly common things to run into, so a good opportunity to give some example code for future reference;</p>
<ul>
<li>
<h2>We need to perform our Form Post over SSL</h2>
</li>
<li>
<h2>The SSL certificate of the server we are posting to will never be valid!</h2>
</li>
<li>
<h2>We must carry out our form post while supplying basic HTTP authentication credentials</h2>
</li>
</ul>
<p>I created a new Console application and added the following code;</p>
<pre class="brush: c-sharp">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Collections.Specialized;

namespace ShutdownNASBox
{
    class Program
    {
        static void Main(string[] args)
        {
            using (WebClient client = new WebClient())
            {
                // add the basic http authentication username &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp; password
                client.Credentials = new NetworkCredential(&quot;admin&quot;, &quot;abc123&quot;);

                // register the face that the connection uses SSL
                // (otherwise it defaults to TLS and you get an exception)
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

                // set it to effectivly ignore the SSL certificate
                ServicePointManager.ServerCertificateValidationCallback =
                                                        delegate { return true; };

                // build a NameValueCollection which holds those 6 values we saw
                // being posted when we used firebug
                NameValueCollection c = new NameValueCollection();
                c.Add(&quot;PAGE&quot;, &quot;System&quot;);
                c.Add(&quot;OUTER_TAB&quot;, &quot;tab_shutdown&quot;);
                c.Add(&quot;INNER_TAB&quot;, &quot;NONE&quot;);
                c.Add(&quot;shutdown_option1&quot;, &quot;1&quot;);
                c.Add(&quot;command&quot;, &quot;poweroff&quot;);
                c.Add(&quot;OPERATION&quot;, &quot;set&quot;);

                try
                {
                    // Post the data!  This will return as a byte array
                    byte[] bytes =
                    client.UploadValues(&quot;https://backup/get_handler&quot;, c);

                    // convert the byte array into text we can read!
                    string result = Encoding.ASCII.GetString(bytes);

                    Console.Write(&quot;Shutdown Message Sent&quot;);
                    Console.Write(result);

                }
                catch (Exception e)
                {
                    Console.Write(&quot;Shutdown Message Send Failure!&quot;);
                    Console.Write(e.ToString());
                }
            }
        }
    }
}
</pre>
<p>And that&#8217;s all there is to it!  An obvious and easy upgrade would be to make this parametrized and maybe get it to write to the windows log on failure.</p>
<p>In <a href="http://codeblog.shawson.co.uk/automatic-nas-box-shutdown-how-to-execute-applications-on-windows-shutdown-part-22/">part two</a> I shall do a quick post on how to schedule tasks to run on shut down in Windows 7.</p>
<p><a href="http://codeblog.shawson.co.uk/netgear-readynas-duo-command-line-shut-down-utility/">You can see the finished app, with the above recommended improvements already implemented,  here</a></p>


<p>Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/netgear-readynas-duo-command-line-shut-down-utility/' rel='bookmark' title='Netgear ReadyNAS Duo command line shut down utility'>Netgear ReadyNAS Duo command line shut down utility</a></li>
<li><a href='http://codeblog.shawson.co.uk/pages-jump-to-the-top-on-post-back-in-aspnet/' rel='bookmark' title='Pages jump to the top on post back in asp.net'>Pages jump to the top on post back in asp.net</a></li>
<li><a href='http://codeblog.shawson.co.uk/mvc-strongly-typed-view-returns-a-null-model-on-post-back/' rel='bookmark' title='MVC strongly typed view returns a null model on post back'>MVC strongly typed view returns a null model on post back</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://codeblog.shawson.co.uk/automatic-shutdown-of-my-netgear-readynas-duo-network-storage-server/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Framework &#8220;The data reader is incompatible with the specified complex type.&#8221;</title>
		<link>http://codeblog.shawson.co.uk/entity-framework-the-data-reader-is-incompatible-with-the-specified-complex-type/</link>
		<comments>http://codeblog.shawson.co.uk/entity-framework-the-data-reader-is-incompatible-with-the-specified-complex-type/#comments</comments>
		<pubDate>Tue, 07 Jun 2011 16:07:21 +0000</pubDate>
		<dc:creator>shawson</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[C#.net]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://codeblog.shawson.co.uk/?p=1024</guid>
		<description><![CDATA[I recently had this problem with a site I&#8217;m working on. I&#8217;m using Entity framework to access a bunch of legacy stored procedures, originally in MySQL but ported over to MSSQL. Having added the sprocs to EF and let it auto-generate it&#8217;s magic, I was shocked to find one of my calls throwing the following [...]


Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/cross-apply-in-sql/' rel='bookmark' title='Cross Apply in SQL'>Cross Apply in SQL</a></li>
<li><a href='http://codeblog.shawson.co.uk/entity-framework-4-1-code-first-with-one-to-many-relationship-code-example/' rel='bookmark' title='Entity Framework 4.1 Code First (With One to Many relationship) Code Example'>Entity Framework 4.1 Code First (With One to Many relationship) Code Example</a></li>
<li><a href='http://codeblog.shawson.co.uk/asp-net-build-step-to-minify-and-obfuscate-your-sites-javascript-and-css/' rel='bookmark' title='Adding minification and obfuscation of your Javascript and CSS to your ASP.net build process using Yahoo YUI Compressor'>Adding minification and obfuscation of your Javascript and CSS to your ASP.net build process using Yahoo YUI Compressor</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>I recently had this problem with a site I&#8217;m working on.  I&#8217;m using Entity framework to access a bunch of legacy stored procedures, originally in MySQL but ported over to MSSQL.  Having added the sprocs to EF and let it auto-generate it&#8217;s magic, I was shocked to find one of my calls throwing the following exception;</p>
<pre>
System.Data.EntityCommandExecutionException: The data reader is incompatible with the specified &amp;#39;ChinookModel.GetVehicleDescFromModelId_Result1&amp;#39;. A member of the type, &amp;#39;ivaluationid1&amp;#39;, does not have a corresponding column in the data reader with the same name.
   at System.Data.Query.InternalTrees.ColumnMapFactory.GetMemberOrdinalFromReader(DbDataReader storeDataReader, EdmMember member, EdmType currentType, Dictionary`2 renameList)
   at System.Data.Query.InternalTrees.ColumnMapFactory.GetColumnMapsForType(DbDataReader storeDataReader, EdmType edmType, Dictionary`2 renameList)
   at System.Data.Query.InternalTrees.ColumnMapFactory.CreateColumnMapFromReaderAndType(DbDataReader storeDataReader, EdmType edmType, EntitySet entitySet, Dictionary`2 renameList)
   at System.Data.Query.InternalTrees.ColumnMapFactory.CreateFunctionImportStructuralTypeColumnMap(DbDataReader storeDataReader, FunctionImportMapping mapping, EntitySet entitySet, StructuralType baseStructuralType)
   at System.Data.EntityClient.EntityCommandDefinition.FunctionColumnMapGenerator.System.Data.EntityClient.EntityCommandDefinition.IColumnMapGenerator.CreateColumnMap(DbDataReader reader)
   at System.Data.Objects.ObjectContext.CreateFunctionObjectResult[TElement](EntityCommand entityCommand, EntitySet entitySet, EdmType edmType, MergeOption mergeOption)
   at System.Data.Objects.ObjectContext.ExecuteFunction[TElement](String functionName, MergeOption mergeOption, ObjectParameter[] parameters)
   at System.Data.Objects.ObjectContext.ExecuteFunction[TElement](String functionName, ObjectParameter[] parameters)
   at Chinook.Model.ChinookEntities.GetVehicleDescFromModelId(Nullable`1 modelid) in C:\_Dev\Chinook\Source\Chinook.Model\Chinook.Designer.cs:line 160
   at Chinook.Model.GlassGuideDataProvider.GetVehicleFromModelId(Int32 ModelId) in C:\_Dev\Chinook\Source\Chinook.Model\GlassGuideDataProvider.cs:line 104
   at Chinook.Services.VehicleDataLookup.GetVehicleForRegistration(String reg) in C:\_Dev\Chinook\Source\Chinook\Services\VehicleDataLookup.asmx.cs:line 81
</pre>
<p>It seemed to be moaning that one of the columns in the complex type I set for it to use as the return type, doesn&#8217;t match to a column actually being returned, despite entity framework having auto generated that type itself!  The cause was, as is generally the case,  user error.  Inspecting the sproc a bit closer I noticed one of the columns was being returned twice, using the same name.  EF generated me a call with an iValuation and iValuation1 column, but failed to match iValuation1 because in reality both columns were simply called iValuation!  So a simple, and kind of obvious fix, but worth noting to stop someone else loose a little more hair when they&#8217;re confonted with this error!</p>


<p>Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/cross-apply-in-sql/' rel='bookmark' title='Cross Apply in SQL'>Cross Apply in SQL</a></li>
<li><a href='http://codeblog.shawson.co.uk/entity-framework-4-1-code-first-with-one-to-many-relationship-code-example/' rel='bookmark' title='Entity Framework 4.1 Code First (With One to Many relationship) Code Example'>Entity Framework 4.1 Code First (With One to Many relationship) Code Example</a></li>
<li><a href='http://codeblog.shawson.co.uk/asp-net-build-step-to-minify-and-obfuscate-your-sites-javascript-and-css/' rel='bookmark' title='Adding minification and obfuscation of your Javascript and CSS to your ASP.net build process using Yahoo YUI Compressor'>Adding minification and obfuscation of your Javascript and CSS to your ASP.net build process using Yahoo YUI Compressor</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://codeblog.shawson.co.uk/entity-framework-the-data-reader-is-incompatible-with-the-specified-complex-type/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

