<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Christophe Geers&#039; Blog &#187; Programming</title>
	<atom:link href="http://cgeers.wordpress.com/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://cgeers.wordpress.com</link>
	<description>Christophe Geers&#039; Blog about .NET programming</description>
	<lastBuildDate>Sun, 25 Oct 2009 08:26:26 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='cgeers.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/f73a5731818603b97bd2dc9f3a92a96d?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>Christophe Geers&#039; Blog &#187; Programming</title>
		<link>http://cgeers.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://cgeers.wordpress.com/osd.xml" title="Christophe Geers&#039; Blog" />
		<item>
		<title>ASP.NET: Supporting Dynamic Applications</title>
		<link>http://cgeers.wordpress.com/2009/10/24/asp-net-supporting-dynamic-applications/</link>
		<comments>http://cgeers.wordpress.com/2009/10/24/asp-net-supporting-dynamic-applications/#comments</comments>
		<pubDate>Sat, 24 Oct 2009 17:10:09 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Custom Membership Provider]]></category>
		<category><![CDATA[Dynamic Applications]]></category>
		<category><![CDATA[Membership]]></category>
		<category><![CDATA[SqlMembershipProvider]]></category>

		<guid isPermaLink="false">http://cgeers.wordpress.com/?p=960</guid>
		<description><![CDATA[Introduction
The ASP.NET membership feature reduces the amount of code you have to write to authenticate users and store their credentials. To quote MSDN:
&#8220;The ASP.NET membership gives you a built-in way to validate and store user credentials. You use the ASP.NET membership with Forms authentication and / or with the ASP.NET login controls for authenticating users.&#8221;
The [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.wordpress.com&blog=2504479&post=960&subd=cgeers&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a title="introduction" name="introduction"></a><strong>Introduction</strong><img src="http://cgeers.files.wordpress.com/2008/12/web-development.gif?w=80&#038;h=80" alt="Web Development" title="Web Development" width="80" height="80" class="alignright size-full wp-image-293" /></p>
<p>The ASP.NET membership feature reduces the amount of code you have to write to authenticate users and store their credentials. To quote MSDN:</p>
<p><em>&#8220;The <a href="http://msdn.microsoft.com/en-us/library/yh26yfzy.aspx" target="_blank">ASP.NET membership</a> gives you a built-in way to validate and store user credentials. You use the ASP.NET membership with Forms authentication and / or with the ASP.NET login controls for authenticating users.&#8221;</em></p>
<p>The membership provider needs to be specified in the Web.config configuration file. You can use your own custom provider or one of the default providers that ships with the .NET Framework, such as the <a href="http://msdn.microsoft.com/en-us/library/system.web.security.sqlmembershipprovider.aspx" target="_blank">SqlMembershipProvider</a> provider. </p>
<p>All of the user related data is stored in a set of tables used by the ASP.NET membership system. In most cases you&#8217;ll use one set of tables per web application. However you can also reuse the same set to store the user credentials of multiple web applications. This effectively enables you to create one web application that acts as a portal allowing you to log in to one of these &#8220;virtual&#8221; applications.</p>
<p>However this isn&#8217;t possible out of the box. You have some work ahead of you, before you can support such dynamic applications. </p>
<p>Let&#8217;s get started&#8230;</p>
<p><span id="more-960"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#applicationcontext">Application Context</a></li>
<li><a href="#provider">Dynamic Applications SqlMembershipProvider</a></li>
<li><a href="#login">Login Control</a></li>
<li><a href="#formsauthenticationhelper">FormsAuthenticationHelper</a></li>
<li><a href="#dynamicapplicationsmodule">DynamicApplicationsModule</a></li>
<li><a href="#formsauthenticationticketextensions">FormsAuthenticationTicketExtensions</a></li>
<li><a href="#controls">PasswordRecovery &amp; ChangePassword Controls</a></li>
<li><a href="#webapplication">Web Application Demo</a></li>
<li><a href="#summary">Summary</a></li>
<li><a href="#download">Download</a></li>
</ul>
<p><a title="applicationcontext" name="applicationcontext"></a><strong>Application Context</strong></p>
<p>Let&#8217;s start by examining the following Web.config entry:</p>
<p><strong>Listing 1</strong> &#8211; Web.Config ASP.NET Membership Configuration</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
&lt;membership defaultProvider=<span class="str">"SqlProvider"</span>&gt;
  &lt;providers&gt;
    &lt;clear /&gt;
    &lt;add name=<span class="str">"SqlProvider"</span>
        type=<span class="str">"System.Web.Security.SqlMembershipProvider"</span>
        connectionStringName=<span class="str">"YourConnectionStringName"</span>
        applicationName=<span class="str">"MyApplication"</span>
      ... /&gt;
  &lt;/providers&gt;
&lt;/membership&gt;</pre>
</div>
<p>These settings setup your web application to use the SqlMembershipProvider to manage your user credentials. All of the data related to your users is stored in the default ASP.NET membership tables.</p>
<p><strong>Remark</strong>: This article is not a primer on ASP.NET membership, you should be familiar with it. Use the <a href="http://msdn.microsoft.com/en-us/library/ms229862%28VS.80%29.aspx" target="_blank">ASP.NET SQL Server Registration Tool</a> (aspnet_regsql.exe) for setting up your database.</p>
<p>As mentioned before you can store the user credentials of multiple web applications in the same set of tables. Each web application separates their user data by partitioning them, in what I call,  an application context. This application context is defined by the applicationName property of the membership provider. As you can see in Listing 1 the application name is &#8220;MyApplication&#8221;.</p>
<p>The SqlMembershipProvider uses this setting to determine in which context it should operate, all of the user data tied to this application name will be accessible by the ASP.NET membership library and login controls. </p>
<p>Unfortunately this setting is statically defined in the Web.config. You cannot easily change it during runtime. If you want to support dynamic applications, you need a way to control the value of the provider&#8217;s ApplicationName property. The solution lies in creating your very own ASP.NET Membership provider.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="provider" name="provider"></a><strong>Dynamic Applications SqlMembershipProvider</strong></p>
<p>The SqlMembershipProvider retrieves the value for its ApplicationName property from the configuration settings contained in the Web.config file. We want to change the value which the getter of this property returns. </p>
<p>When logging in the user should make his intentions clear, in other words he has to specify which of the virtual applications he wants to access. For this purpose I require that the user not only specifies his username and password but also the virtual application he wants to access. From the user&#8217;s point of view I call this virtual application, the domain.</p>
<p>For example, suppose you have established a Sql Server database called AspNetMembership which contains the ASP.NET membership tables. This database contains the following virtual applications defined in the aspnet_Applications table:</p>
<ul>
<li>Northwind</li>
<li>AdventureWorks</li>
</ul>
<p>Each virtual application contains a user with the username &#8220;cgeers&#8221;. Now if I want to log in to the Northwind application I have to enter my username as &#8220;Northwind\cgeers&#8221;. For the AdventureWorks application this would be &#8220;AdventureWorks\cgeers&#8221;. </p>
<p>The part preceding the username is the application name or as far as the user is concerned this is the domain he has to enter in order to specify which virtual application he wants to access. The domain and the username are separated by a backslash.</p>
<p>When the user logs in using the ASP.NET Login control we have to extract the domain he entered and store this in a location which our custom membership provider can access. However we have to take into account that ASP.NET operates in a multithreaded environment. Each request received by ASP.NET is handled by a separate thread. We can&#8217;t store the domain in just any location, otherwhise other incoming requests might overwrite it. It must be tied to a single request. </p>
<p>The ideal place to store contextual information that is tied to an individual request is the current Http context. This contextual information is encapsulated by the <a href="http://msdn.microsoft.com/en-us/library/system.web.httpcontext.aspx" target="_blank">HttpContext</a> class. </p>
<p>Start up Visual Studio and create a new blank solution called &#8220;AspNetDynamicApplications&#8221;. Next add a new Class Library project to the solution named &#8220;CGeers.Web.Security&#8221;. Add references to the System.Configuration and System.Web assemblies. Our custom provider will descend from the default SqlMembershipProvider so these references are required.</p>
<p><strong>Figure 1</strong> &#8211; Visual Studio Solution<br />
<a href="http://cgeers.files.wordpress.com/2009/10/dynamic-applications-1.jpg"><img src="http://cgeers.files.wordpress.com/2009/10/dynamic-applications-1.jpg?w=300&#038;h=97" alt="Dynamic Applications Figure 1" title="Dynamic Applications Figure 1" width="300" height="97" class="aligncenter size-medium wp-image-993" /></a></p>
<p>Rename the automatically generated Class1.cs file to DynamicApplicationsSqlMembershipProvider.cs and add the code shown in Listing 2.</p>
<p><strong>Listing 2</strong> &#8211; DynamicApplicationsSqlMembershipProvider</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> DynamicApplicationsSqlMembershipProvider : SqlMembershipProvider
{
    <span class="preproc">#region</span> Fields

    <span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">string</span> ApplicationNameSetting = <span class="str">"ApplicationName"</span>;

    <span class="preproc">#endregion</span>

    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">string</span> ApplicationName
    {
        get
        {
            HttpContext context = HttpContext.Current;
            <span class="kwrd">if</span> (context == <span class="kwrd">null</span>)
            {
                <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(<span class="str">"Http context cannot be null."</span>);
            }

            <span class="kwrd">string</span> applicationName = String.Empty;
            <span class="kwrd">if</span> (context.Items.Contains(ApplicationNameSetting))
            {
                <span class="kwrd">if</span> (!String.IsNullOrEmpty((<span class="kwrd">string</span>)context.Items[ApplicationNameSetting]))
                {
                    applicationName = (<span class="kwrd">string</span>)context.Items[ApplicationNameSetting];
                }
            }
            <span class="kwrd">return</span> applicationName;
        }
        set
        {
            <span class="kwrd">base</span>.ApplicationName = <span class="kwrd">value</span>;
        }
    }
}</pre>
</div>
<p>As you can see our custom membership provider descends from the default SqlMembershipProvider and overrides the ApplicationName property. We aren&#8217;t concerned with the setter, only with the getter. When the provider reads the ApplicationName property we get a handle to the current Http context by calling the static Current property of the HttpContext class. The obtained HttpContext object has a  key/value collection property called Items. This collection stores the application name in an entry identified by the key &#8220;ApplicationName&#8221;. The name of this key is something you have to determine at design time.</p>
<p>Now each time our custom membership provider needs to determine the application name it calls the ApplicationName property which retrieves the value from the current Http context. This works in ASP.NET&#8217;s multithreaded environment as each request is tied to its own Http context.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="login" name="login"></a><strong>Login Control</strong></p>
<p>Now that we a custom membership provider that retrieves the value for its ApplicationName property from the currect Http context, we still have to figure out a way to actually store the application name in the Http context.</p>
<p>The first time that a user specifies the virtual application or domain he wants to access is when he logs in. As mentioned earlier the user has to enter his username in the format <em>&lt;domain&gt;\&lt;username&gt;</em>. We have to create our own Login control which descends from the ASP.NET Login control. Upon user authentication we need to extract the entered domain and save it in the current Http context.</p>
<p>Add a new project using the Class Library template to your solution called &#8220;CGeers.Web.UI.WebControls&#8221;.  Add the following references to the project:</p>
<ul>
<li>System.Configuration</li>
<li>System.Web</li>
<li>CGeers.Web.Security</li>
</ul>
<p>Next delete the automatically generated Class1.cs file and add a new class called DynamicApplicationsLogin. Since the code for this class is quite lengthy I&#8217;ve chosen to break it up into several listings. After each listing a brief explanation of the code is added.</p>
<p><strong>Listing 3</strong> &#8211; DynamicApplicationsLogin Control Private Properties</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> DynamicApplicationsLogin : Login
{
    <span class="preproc">#region</span> Fields

    <span class="kwrd">private</span> <span class="kwrd">string</span> _fullUserName;

    <span class="preproc">#endregion</span>

    <span class="preproc">#region</span> Properties

    <span class="kwrd">private</span> <span class="kwrd">string</span> ApplicationName
    {
        get
        {
            <span class="kwrd">string</span>[] data = <span class="kwrd">base</span>.UserName.Split(<span class="str">@"\"</span>.ToCharArray(), 2);
            <span class="kwrd">string</span> applicationName = (data.Length == 2) ? data[0] : String.Empty;
            <span class="kwrd">return</span> applicationName;
        }
    }

    <span class="kwrd">private</span> <span class="kwrd">string</span> BaseUserName
    {
        get
        {
            <span class="kwrd">string</span>[] data = <span class="kwrd">base</span>.UserName.Split(<span class="str">@"\"</span>.ToCharArray(), 2);
            <span class="kwrd">string</span> userName = (data.Length == 2) ? data[1] : <span class="kwrd">base</span>.UserName;
            <span class="kwrd">return</span> userName;
        }
    }

    <span class="preproc">#endregion</span>

   <span class="rem">// ...</span>
}</pre>
</div>
<p>As you can see the DynamicApplicationsLogin control descends from the standard ASP.NET Login control and a field called _fullUserName and two private properties ApplicationName and BaseUserName are added. </p>
<p>Since the user enters the domain and username into the same TextBox control we need to split up these parts. As you might guess the ApplicationName property extracts the domain and the BaseUserName returns the username. For example if the user enters Northwind\cgeers, the ApplicationName property would return &#8220;Northwind&#8221; and the BaseUserName property would return &#8220;cgeers&#8221;.</p>
<p><strong>Listing 4</strong> &#8211; DynamicApplicationsLogin Control OnAuthenticate Method</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> OnAuthenticate(AuthenticateEventArgs e)
{
    HttpContext context = HttpContext.Current;
    <span class="kwrd">if</span> (context == <span class="kwrd">null</span>)
    {
        <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(<span class="str">"Http context cannot be null."</span>);
    }
    MembershipProvider provider = Membership.Provider;
    <span class="kwrd">if</span> (provider == <span class="kwrd">null</span>)
    {
        <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(<span class="str">"MembershipProvider cannot be null."</span>);
    }
    provider = provider <span class="kwrd">as</span> DynamicApplicationsSqlMembershipProvider;
    <span class="kwrd">if</span> (provider == <span class="kwrd">null</span>)
    {
        <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(<span class="str">"The specified MembershipProvider must be of type DynamicApplicationsSqlMembershipProvider."</span>);
    }

    <span class="rem">// Store the application name in the current Http context's items collections</span>
    context.Items[<span class="str">"ApplicationName"</span>] = ApplicationName;

    <span class="rem">// Validate the user</span>
    _fullUserName = UserName;
    UserName = BaseUserName;
    <span class="kwrd">base</span>.OnAuthenticate(e);
}
</pre>
</div>
<p>Next you need to override the Login control&#8217;s OnAuthenticate method to make sure that the user is validated inside the correct application context (virtual application). </p>
<p>First this method retrieves a reference to the current Http context, then it checks if the loaded membership provider is indeed our custom DynamicApplicationsSqlMembershipProvider. Then the entered domain or application name is stored in the current Http context&#8217;s Items collection so that our membership provider can retrieve the correct value for its ApplicationName property. </p>
<p>Last but not least the UserName property&#8217;s value is set to only contain the UserName by assigning the BaseUserName property to it. The private _fullUserName field temporarily stores the value the user entered (domain\username). You&#8217;ll see how this field is used later on. </p>
<p>After the application name has been stored in the Http context and the UserName property only contains the username the base implementation is called, this causes the username to be validated inside of the correct application context.</p>
<p><strong>Listing 5</strong> -DynamicApplicationsLogin Control OnLoginError Method</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> OnLoginError(EventArgs e)
{
    UserName = _fullUserName;
    <span class="kwrd">base</span>.OnLoginError(e);
}</pre>
</div>
<p>Override the OnLoginError method and before calling the base implementation assign the _fullUserName field to the UserName property. When authenticating the user (OnAuthenticate method) the UserName property must only contain the username and not the domain, but when the authentication fails you need to make sure that the text the user entered in the TextBox control representing the UserName is reset to the value the user initially entered. Otherwhise it might be confusing for the user if the domain he entered disappears. </p>
<p><strong>Listing 6</strong> &#8211; DynamicApplicationsLogin Control  OnLoggedIn Method</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> OnLoggedIn(EventArgs e)
{
    UserName = _fullUserName;
    HttpContext context = HttpContext.Current;
    <span class="kwrd">if</span> (context == <span class="kwrd">null</span>)
    {
        <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(<span class="str">"Http context cannot be null."</span>);
    }

    <span class="kwrd">string</span> userName = BaseUserName;
    MembershipUser user = Membership.GetUser(userName);
    <span class="kwrd">if</span> (user != <span class="kwrd">null</span>)
    {
        <span class="kwrd">string</span> userData = String.Format(<span class="str">"AN={0};"</span>, ApplicationName);
        HttpCookie cookie = FormsAuthenticationHelper.StoreUserDataInAuthenticationCookie(userName, userData, RememberMeSet);

        <span class="rem">// Manually add the cookie to the Cookies collection</span>
        context.Response.Cookies.Add(cookie);
    }
}</pre>
</div>
<p>To finish the DynamicApplicationsLogin Control you need to override the OnLoggedIn method. The application name is stored in the UserData property of a <a href="http://msdn.microsoft.com/en-us/library/system.web.security.formsauthenticationticket.aspx" target="_blank">FormsAuthenticationTicket</a>. This authentication ticket is used by forms authentication to identify an authenticated user. Here we store it in a cookie and add it to the current Http context&#8217;s response. Later on, you&#8217;ll see why this is required.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="formsauthenticationhelper" name="formsauthenticationhelper"></a><strong>FormsAuthenticationHelper</strong></p>
<p>It you take a look at Listing 6, you&#8217;ll see that the cookie containing the Forms Authentication ticket is created by a helper class called FormsAuthenticationHelper. This is a static helper class which only contains one method, namely StoreUserDataInAuthenticationCookie.</p>
<p>Add a new class called FormsAuthenticationHelper to the CGeers.Web.Security project and add the code shown in Listing 7.</p>
<p><strong>Listing 7</strong> &#8211; FormsAuthenticationHelper</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> FormsAuthenticationHelper
{
    <span class="kwrd">public</span> <span class="kwrd">static</span> HttpCookie StoreUserDataInAuthenticationCookie(<span class="kwrd">string</span> userName, <span class="kwrd">string</span> userData, <span class="kwrd">bool</span> persistent)
    {
        <span class="kwrd">if</span> (String.IsNullOrEmpty(userName))
        {
            <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(<span class="str">"UserName cannot be null or empty."</span>);
        }
        <span class="kwrd">if</span> (String.IsNullOrEmpty(userData))
        {
            <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(<span class="str">"User data cannot be null or empty."</span>);
        }

        <span class="rem">// Create the cookie that contains the forms authentication ticket</span>
        HttpCookie cookie = FormsAuthentication.GetAuthCookie(userName, persistent);

        <span class="rem">// Get the FormsAuthenticationTicket out of the encrypted cookie</span>
        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);

        <span class="rem">// Create a new FormsAuthenticationTicket that includes our custom user data</span>
        FormsAuthenticationTicket newTicket = <span class="kwrd">new</span> FormsAuthenticationTicket(ticket.Version,
                                                                            ticket.Name,
                                                                            ticket.IssueDate,
                                                                            ticket.Expiration,
                                                                            persistent,
                                                                            userData);

        <span class="rem">// Update the cookie's value to use the encrypted version of our new ticket</span>
        cookie.Value = FormsAuthentication.Encrypt(newTicket);

        <span class="rem">// Return the cookie</span>
        <span class="kwrd">return</span> cookie;
    }
}</pre>
</div>
<p>The StoreUserDataInAuthenticationCookie(&#8230;) method retrieves the cookie for the specified user (userName parameter) that contains the forms authentication ticket. Next the cookie is decrypted in order to access the FormsAuthenticationTicket object. Then a new FormsAuthenticationTicket is created based on the old ticket and the value contained in the userData parameter is stored within this ticket. As a last step, the new FormsAuthenticationTicket object is stored within an encrypted cookie.</p>
<p><strong>Remark</strong>: The DynamicApplicationsLogin control stores sends this cookie back to the user, so the client needs to support cookies!</p>
<p><a href="#top">Top of page</a></p>
<p><a title="dynamicapplicationsmodule" name="dynamicapplicationsmodule"></a><strong>DynamicApplicationsModule</strong></p>
<p>Let&#8217;s recapitulate what we have so far.</p>
<ul>
<li><strong>DynamicApplicationsSqlMembershipProvider</strong>: A custom membership provider that dynamically determines in which application context (application name) to operate.</li>
<li><strong>DynamicApplicationsLogin Control</strong>: A custom Login control that stores the domain (or application name) in the Http context of the ASP.NET request. This value is read by our custom membership provider.</li>
</ul>
<p>So we have our custom membership provider that is able, per request, to determine the application context in which to operate and we have a custom Login control that identifies this context by requiring that users precede their username with a domain (= application name). </p>
<p>This works quite well if your web application only consists out of a login page. Remember that the custom membership provider determines the application context by reading the application name stored in the current Http context. With each request you make, a new Http context is created. When logging in the application name is explicitly stored within the Http context. However for any subsequent requests this is not the case. Somehow we have to make sure that the Http context is correctly initialized with the application name with each request after the user has logged in.</p>
<p>As mentioned earlier, the DynamicApplicationLogin control sends an encrypted cookie to the user after having successfully logged in. This cookie contains the application name and is sent along with each subsequent request. Voila, now all we need is a way to insert some logic into the ASP.NET request pipeline, in order to read the contents of this cookie and store the retrieved application name in the Http context.</p>
<p>A <a href="http://msdn.microsoft.com/en-us/library/ms227673.aspx" target="_blank">Http module</a> is perfect for this situation. An Http module is called on every request and runs before and after a request is processed.</p>
<p>Add a new class called DynamicApplicationsModule to the CGeers.Web.Security project. This class needs to implement the <a href="http://msdn.microsoft.com/en-us/library/system.web.ihttpmodule.aspx" target="_blank">IHttpModule interface</a>. The code for this Http module is displayed in Listing 8.</p>
<p><strong>Listing 8</strong> -DynamicApplicationsModule</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> DynamicApplicationsModule : IHttpModule
{
    <span class="preproc">#region</span> Fields

    <span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">string</span> ApplicationNameSetting = <span class="str">"ApplicationName"</span>;

    <span class="preproc">#endregion</span>

    <span class="preproc">#region</span> IHttpModule Members

    <span class="kwrd">public</span> <span class="kwrd">void</span> Dispose()
    { }

    <span class="kwrd">public</span> <span class="kwrd">void</span> Init(HttpApplication context)
    {
        context.AuthenticateRequest += DetermineApplicationName;
    }

    <span class="preproc">#endregion</span>

    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> DetermineApplicationName(<span class="kwrd">object</span> sender, EventArgs e)
    {
        <span class="rem">// Access the current Http application.</span>
        HttpApplication application = sender <span class="kwrd">as</span> HttpApplication;
        <span class="kwrd">if</span> (application == <span class="kwrd">null</span>)
        {
            <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(<span class="str">"Http application cannot be null."</span>);
        }

        <span class="rem">// Get the HttpContext for the current request.</span>
        HttpContext context = application.Context;
        <span class="kwrd">if</span> (context == <span class="kwrd">null</span>)
        {
            <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(<span class="str">"Http context cannot be null."</span>);
        }

        <span class="rem">// Read the application name stored in the FormsAuthenticationTicket</span>
        <span class="kwrd">string</span> applicationName = String.Empty;
        <span class="kwrd">if</span> (context.Request.IsAuthenticated)
        {
            FormsIdentity identity = context.User.Identity <span class="kwrd">as</span> FormsIdentity;
            <span class="kwrd">if</span> (identity != <span class="kwrd">null</span>)
            {
                FormsAuthenticationTicket ticket = identity.Ticket;
                <span class="kwrd">if</span> (ticket != <span class="kwrd">null</span>)
                {
                    applicationName = ticket.GetApplicationName();
                }
            }
        }

        <span class="rem">// Store the application name in the Items collection of the per-request http context.</span>
        <span class="rem">// Storing it in the session state is not an option as the session is not available at this</span>
        <span class="rem">// time. It is only available when the Http application triggers the AcquireRequestState event.</span>
        context.Items[ApplicationNameSetting] = applicationName;
    }
}</pre>
</div>
<p>The Init(&#8230;) method initializes a Http module and prepares it to handle requests. Here the HttpApplication&#8217;s AuthenticateRequest event is hooked to the DetermineApplicationName event handler.</p>
<p>The DetermineApplicationName(&#8230;) event handler checks if its dealing with an authenticated request and if so retrieves the FormsAuthentication ticket that was sent along by the client. </p>
<p>This ticket identifies the application context in which to operate. The application name is extracted from the ticket using the FormsAuthenticationTicket&#8217;s GetApplicationName() method. This is an extension method, I&#8217;ll address it in the following section. </p>
<p>Finally after extracting the application name from the ticket it is stored within the Http context so that our custom membership provider can read it.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="formsauthenticationticketextensions" name="formsauthenticationticketextensions"></a><strong> FormsAuthenticationTicketExtensions </strong></p>
<p>Add a new class called FormsAuthenticationTicketExtensions to the CGeers.Web.Security project and add the code shown in Listing 9.</p>
<p><strong>Listing 9</strong> &#8211; FormsAuthenticationTicketExtensions</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">internal</span> <span class="kwrd">static</span> <span class="kwrd">class</span> FormsAuthenticationTicketExtensions
{
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">string</span> GetApplicationName(<span class="kwrd">this</span> FormsAuthenticationTicket ticket)
    {
        <span class="rem">// Check if the application name (AN=) is stored in the ticket's userdata.</span>
        <span class="kwrd">string</span> applicationName = String.Empty;
        List&lt;<span class="kwrd">string</span>&gt; settings = <span class="kwrd">new</span> List&lt;<span class="kwrd">string</span>&gt;(ticket.UserData.Split(<span class="str">';'</span>));
        <span class="kwrd">foreach</span> (<span class="kwrd">string</span> s <span class="kwrd">in</span> settings)
        {
            <span class="kwrd">string</span> setting = s.Trim();
            <span class="kwrd">if</span> (setting.StartsWith(<span class="str">"AN="</span>))
            {
                <span class="kwrd">int</span> startIndex = setting.IndexOf(<span class="str">"AN="</span>) + 3;
                applicationName = setting.Substring(startIndex);
                <span class="kwrd">break</span>;
            }
        }
        <span class="kwrd">return</span> applicationName;
    }
}  </pre>
</div>
<p>As you can see in Listing 6 the DynamicApplicationLogin Control saves the application name in the UserData property of the FormsAuthenticationTicket by preceding it with the prefix &#8220;AN=&#8221;. Thus this extension method needs to take this into account when retrieving the application name from a FormsAuthenticationTicket. </p>
<p><strong>Remark</strong>: Feel free to improve on the way the application name is stored within the ticket, but remember to implement the same system for the DynamicApplicationsLogin Control and this extension method.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="controls" name="controls"></a><strong>PasswordRecovery &amp; ChangePassword Controls</strong></p>
<p>Similar to the DynamicApplicationsLogin Control I&#8217;ve created controls that descend from the ASP.NET PasswordRecovery and Changepassword controls. If you want a user to be able to retrieve his password and/or change it, then you need to use these controls. They make sure that everything is executed within the correct application context. </p>
<p>The implementation is very similar to that of the DynamicApplicationsLogin control so I will not list the code of these controls here. If you want to check out the source code of these controls, then download the source code accompanying this article. You can find these controls in the CGeers.Web.UI.WebControls project.</p>
<ul>
<li><strong>DynamicApplicationsPasswordRecovery</strong>: When a user wants to retrieve his password he has to enter his username. Just as with the Login control he needs to precede his username with the domain (= application name). The DynamicApplicationsPasswordRecovery control takes care of the rest and makes sure the username is verified within the correct application context.</li>
<li><strong>DynamicApplicationsChangePassword</strong>: Use this control on a page that requires that the user is logged in. In other words make sure that the user is already operating within the correct application context. Changing ones password happens to delete the cookie that stores the FormsAuthenticationTicket that contains the application name. This control solves this by generating a new cookie after the password has been changed.</li>
</ul>
<p><a href="#top">Top of page</a></p>
<p><a title="webapplication" name="webapplication"></a><strong>Web Application Demo</strong></p>
<p>The source code accompanying this article also contains a demo web application project that demonstrates the DynamicApplicationsSqlMembershipProvider, the new Login controls, our custom Http module&#8230;and so on.</p>
<p><strong>Figure 2</strong> &#8211; Visual Studio Solution<br />
<a href="http://cgeers.files.wordpress.com/2009/10/dynamic-applications-2.jpg"><img src="http://cgeers.files.wordpress.com/2009/10/dynamic-applications-2.jpg?w=298&#038;h=221" alt="Dynamic Applications 2" title="Dynamic Applications 2" width="298" height="221" class="aligncenter size-full wp-image-1063" /></a></p>
<p>In order to run this demo application please follow these steps:</p>
<ol>
<li>Create an Sql Server database called PortalDatabase.</li>
<li>Register the ASP.NET Membership tables in this database using the <a href="http://msdn.microsoft.com/en-us/library/ms229862(VS.80).aspx" target="_blank">ASP.NET SQL Server Registration Tool</a>.</li>
<li>Add a connection string to the Web.config in the connectionStrings section pointing to the newly created database.</li>
<li>Add the necessary configuration settings to register the DynamicApplicationsMembershipProvider as the default ASP.NET membership provider. You still need to define a default value for its applicationName setting.</li>
<li>Start the ASP.NET Configuration website and create a new user. This user will be created for the application you specified in step 4.</li>
<li>Change the default application name for the ASP.NET membership provider. Relaunch the ASP.NET Configuration website and create another user account.</li>
<li>Add the DynamicApplicationModule to the httpModules section.</li>
<li>Make sure the authentication method is set to Forms and that cookies are enabled.</li>
</ol>
<p>After following these steps you should be ready to run the demo web application. You created a database which contains two applications and a user for each application. </p>
<p>When you start the web application you are able to log in to each application by specyfing the application name (domain) followed by a backslash and the username. Ofcourse the user&#8217;s password is required too. </p>
<p>The Login controls we created take care of the rest and make sure that you are operating within the correct application context. Any subsequent calls with the ASP.NET membership library will trigger the custom membership provider to return the correct application name thus making sure these calls operate within the correct application context.</p>
<p><strong>Remark</strong>: The demo web application&#8217;s Web.config file contains comments that specify everything that you need to do in order to properly setup the application. Be sure to check it out.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="summary" name="summary"></a><strong>Summary</strong></p>
<p>This article showed you how can take use of the ASP.NET membership system to create a portal application that allows users to log in to one of many virtual applications. </p>
<p>The first key to realizing this is to create a custom membership provider that makes sure you operate within the correct application context by retrieving the value for the ApplicationName property from a storage location that is tied to an individual request. </p>
<p>By creating a custom Login control that descends from the standard ASP.NET Login control we are able to determine which application the user wants to access. </p>
<p>By encapsulating this information in an encrypted cookie we are able to automatically identify the application the user wants to access for each of his requests.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="download" name="download"></a><strong>Download</strong></p>
<p>You can find the source code for this article on the <a href="http://cgeers.wordpress.com/download/" target="_blank">Download page</a> of this blog.</p>
<p><a href="#top">Top of page</a></p>
Posted in ASP.NET, C#, Programming  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/960/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/960/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cgeers.wordpress.com/960/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cgeers.wordpress.com/960/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cgeers.wordpress.com/960/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cgeers.wordpress.com/960/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cgeers.wordpress.com/960/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cgeers.wordpress.com/960/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cgeers.wordpress.com/960/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cgeers.wordpress.com/960/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.wordpress.com&blog=2504479&post=960&subd=cgeers&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://cgeers.wordpress.com/2009/10/24/asp-net-supporting-dynamic-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1deb97b690d087dea7942250d7b03310?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2008/12/web-development.gif" medium="image">
			<media:title type="html">Web Development</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/10/dynamic-applications-1.jpg?w=300" medium="image">
			<media:title type="html">Dynamic Applications Figure 1</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/10/dynamic-applications-2.jpg" medium="image">
			<media:title type="html">Dynamic Applications 2</media:title>
		</media:content>
	</item>
		<item>
		<title>Using WCF Services With PHP 5</title>
		<link>http://cgeers.wordpress.com/2009/08/20/using-wcf-services-with-php-5/</link>
		<comments>http://cgeers.wordpress.com/2009/08/20/using-wcf-services-with-php-5/#comments</comments>
		<pubDate>Thu, 20 Aug 2009 06:20:27 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[basicHttpBinding]]></category>

		<guid isPermaLink="false">http://cgeers.wordpress.com/?p=894</guid>
		<description><![CDATA[Introduction
Most of the time when I need to consume a web service I do so using a .NET client built upon the Windows Communication Foundation (WCF). In most cases the web service in question has also been developed using .NET&#8217;s WCF.
About 8 years ago I used PHP as my primary tool for building web sites. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.wordpress.com&blog=2504479&post=894&subd=cgeers&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a title="introduction" name="introduction"></a><strong>Introduction</strong><img class="alignnone size-medium wp-image-24 alignright" style="float:right;" src="http://cgeers.files.wordpress.com/2008/04/dotnetwcf.gif?w=80&#038;h=80" alt="" width="80" height="80" /></p>
<p>Most of the time when I need to consume a web service I do so using a .NET client built upon the Windows Communication Foundation (WCF). In most cases the web service in question has also been developed using .NET&#8217;s WCF.</p>
<p>About 8 years ago I used <a href="http://www.php.net" target="_blank">PHP</a> as my primary tool for building web sites. At the time I used versions 3 &amp; 4. Recently I had the opportunity to brush up my PHP skills by building a couple of small sites using PHP 5. Besides lending itself more towards object orientend programming I noticed that they added support for SOAP by adding the <a href="http://be.php.net/manual/en/class.soapclient.php" target="_blank">SoapClient class</a>.</p>
<p><img class="alignnone size-medium wp-image-24 alignright" style="float:right;" src="http://cgeers.files.wordpress.com/2009/08/php1.gif?w=80&#038;h=45" alt="" width="80" height="45" /></p>
<p>As PHP is still widely used it is not unimaginable, but likely very probably that PHP developers out there need to consume a web service that has been developed with WCF. This article explains how to create WCF services that offer support for PHP clients and how such clients can consume these services.</p>
<p>Let&#8217;s start coding&#8230;</p>
<p><span id="more-894"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#service">WCF Service</a></li>
<li><a href="#host">Hosting The Service</a></li>
<li><a href="#client">PHP Client</a></li>
<li><a href="#messagecontract">MessageContract</a></li>
<li><a href="#revisedclient">Revised PHP Client</a></li>
<li><a href="#summary">Summary</a></li>
<li><a href="#download">Download</a></li>
</ul>
<p><a title="service" name="service"></a><strong>WCF Service</strong></p>
<p>Before we can start consuming a WCF service we obviously need to create one. Let&#8217;s build a web service that offers exactly one method, namely for uploading a file to the server which hosts it.</p>
<p>Start an instance of Visual Studio and create a new blank solution called &#8220;WcfWithPhp&#8221;. Next add a WCF Service Library project and call it CGeers.Wcf.Services. A bunch of automatically generated files will be added to this project. Rename the IService1.cs file to IFileUploadService.cs and replace the generated code with the code shown in the following listing.</p>
<p><strong>Listing 1</strong> &#8211; IFileUploadService</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[ServiceContract]
<span class="kwrd">public</span> <span class="kwrd">interface</span> IFileUploadService
{
    [OperationContract]
    <span class="kwrd">bool</span> Upload(Stream stream);
}</pre>
</div>
<p>This is by far one of the simplest possible setups for a service that enables you to upload a file. The only parameter which you have to supply is the file itself (Stream parameter). Afterwards you&#8217;ll receive a boolean indicating if the upload succeeded or failed.</p>
<p>Now let&#8217;s quickly provide an implementation for this service contract. Rename the Service1.cs file to FileUploadService.cs and delete all of the boilerplate code. Your code should end up resembling the following structure:</p>
<p><strong>Listing 2</strong> &#8211; FileUploadService</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> FileUploadService : IFileUploadService
{
    <span class="kwrd">public</span> <span class="kwrd">bool</span> Upload(Stream stream)
    {
        <span class="kwrd">try</span>
        {
            <span class="rem">// Generate a random filename</span>
            <span class="rem">// ...</span>

            <span class="rem">// Read the incoming stream and save it to file</span>
            <span class="rem">// ...</span>
            <span class="kwrd">return</span> <span class="kwrd">true</span>;
        }
        <span class="kwrd">catch</span> (Exception)
        {
            <span class="rem">// Gulp</span>
            <span class="kwrd">return</span> <span class="kwrd">false</span>;
        }
    }
}</pre>
</div>
<p>The listing above doesn&#8217;t show you the code for the actual implementation. Don&#8217;t fret about it, you can consult it in the source code accompanying this article. The code isn&#8217;t optimal, but this &#8220;Hello, World&#8221;-ish example it is sufficient. </p>
<p>The service generates a random filename based on a Guid and then reads the incoming stream and saves it to file. Afterwards it return true. If any exceptions should occur they are swallowed and the service will return false indicating that the upload failed. It&#8217;s not good practice to just swallow every possible exception, but once again this is just &#8220;illustrative code&#8221;.</p>
<p>As a final step delete the App.config file from the WCF Service Library project. In the next step we&#8217;ll setup a console application that acts as a host for our service.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="host" name="host"></a><strong>Hosting The Service</strong></p>
<p>Add a new Console Application project to your solution named ConsoleHost. Add a reference to the System.ServiceModel assembly (WCF) and to the CGeers.Wcf.Services project. Then add the following code to the Main(&#8230;) method.</p>
<p><strong>Listing 3</strong> &#8211; Hosting The Service</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">static</span> <span class="kwrd">void</span> Main()
{
    ServiceHost host = <span class="kwrd">new</span> ServiceHost(<span class="kwrd">typeof</span>(FileUploadService));
    host.Open();
    Console.WriteLine(<span class="str">"FileUpload Service Host"</span>);
    Console.WriteLine(<span class="str">"Service Started!"</span>);
    <span class="kwrd">foreach</span> (Uri address <span class="kwrd">in</span> host.BaseAddresses)
    {
        Console.WriteLine(<span class="str">"Listening on "</span> + address);
    }
    Console.WriteLine(<span class="str">"Press any key to close the host..."</span>);
    Console.ReadLine();
    host.Close();
}</pre>
</div>
<p>A service host for the FileUpload service type is created and opened. The service&#8217;s configuration is included in the application&#8217;s configuration file. So add an App.config file to the project and configure the service as shown below.</p>
<p><strong>Listing 4</strong> &#8211; Configuring The Service (App.config)</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
&lt;system.serviceModel&gt;
  &lt;services&gt;
    &lt;service behaviorConfiguration=<span class="str">"MyServiceBehavior"</span>
             name=<span class="str">"CGeers.Wcf.Services.FileUploadService"</span>&gt;
      &lt;endpoint address=<span class="str">""</span>
                binding=<span class="str">"basicHttpBinding"</span>
                contract=<span class="str">"CGeers.Wcf.Services.IFileUploadService"</span>&gt;
        &lt;identity&gt;
          &lt;dns <span class="kwrd">value</span>=<span class="str">"localhost"</span> /&gt;
        &lt;/identity&gt;
      &lt;/endpoint&gt;
      &lt;endpoint address=<span class="str">"mex"</span> binding=<span class="str">"mexHttpBinding"</span>
                contract=<span class="str">"IMetadataExchange"</span> /&gt;
      &lt;host&gt;
        &lt;baseAddresses&gt;
          &lt;add baseAddress=<span class="str">"http://localhost:8731/FileUploadService"</span> /&gt;
        &lt;/baseAddresses&gt;
      &lt;/host&gt;
    &lt;/service&gt;
  &lt;/services&gt;
  &lt;behaviors&gt;
    &lt;serviceBehaviors&gt;
      &lt;behavior name=<span class="str">"MyServiceBehavior"</span>&gt;
        &lt;serviceMetadata httpGetEnabled=<span class="str">"True"</span>/&gt;
        &lt;serviceDebug includeExceptionDetailInFaults=<span class="str">"False"</span> /&gt;
      &lt;/behavior&gt;
    &lt;/serviceBehaviors&gt;
  &lt;/behaviors&gt;
&lt;/system.serviceModel&gt;</pre>
</div>
<p>As you can see there is nothing special about this particular configuration. Two endpoints are made available, one for the service itself and another one for exposing it&#8217;s metadata (mex). The transport medium is the HTTP protocol so we can choose one of the interoperable http-enabled bindings. </p>
<p>However since the client application will be build using PHP built-in SoapClient class we have to opt for the <a href="http://msdn.microsoft.com/en-us/library/ms731361.aspx" target="_blank">basicHttpBinding</a> as it conform to the WS-I Basic Profile 1.1 and PHP offers no additional support for any other standards.</p>
<p>Run the console application to make sure it builds and executes correctly. When the application is running you should be able to enter the service&#8217;s address in your favorite browser. The result should be the familiar web service test page.</p>
<p><strong>Figure 1</strong> &#8211; FileUploadService Test Page<br />
<a href="http://cgeers.files.wordpress.com/2009/08/fileuploadservice1.jpg"><img src="http://cgeers.files.wordpress.com/2009/08/fileuploadservice1.jpg?w=300&#038;h=233" alt="File Upload Service Test Page" title="File Upload Service Test Page" width="300" height="233" class="aligncenter size-medium wp-image-924" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="client" name="client"></a><strong>PHP Client</strong></p>
<p>The PHP script which consumes the service is built using PHP 5.2.0, served by Apache 2.2.3 and running on Windows XP. Your setup might differ, but make sure that your PHP 5.x version supports the SoapClient class.</p>
<p>Make sure that the ConsoleHost application is running while you execute your script. The actual script is surprisingly simple.</p>
<p><strong>Listing 5</strong> &#8211; PHP Client Script</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
&lt;?php

<span class="rem">// Function to read the contents of a file</span>
function GetFileContents( $filename ) {
  $handle = fopen($filename, <span class="str">"r"</span>);
  $contents = fread($handle, filesize($filename));
  fclose($handle);
  <span class="kwrd">return</span> $contents;
}

<span class="rem">// Create a new soap client based on the service's metadata (WSDL)</span>
$client = <span class="kwrd">new</span> SoapClient(<span class="str">"http://localhost:8731/FileUploadService?wsdl"</span>);

<span class="rem">// Specify the file to upload</span>
$filename = <span class="str">"test.txt"</span>;

<span class="rem">// Specify the parameters for the Upload(...) method as an associative array</span>
$parameters = array(<span class="str">"stream"</span> =&gt; GetFileContents($filename));

<span class="rem">// Upload the file</span>
$result = $client-&gt;Upload($parameters);

<span class="rem">// Check if the upload succeeded</span>
<span class="kwrd">if</span> ($result) {
    echo $filename . <span class="str">" uploaded"</span>;
}
<span class="kwrd">else</span> {
    echo $filename . <span class="str">" upload failed"</span>;
}

?&gt;</pre>
</div>
<p>The comments in the code adequately explains what it performs. To recap, a soap client is created using the service&#8217;s metadata (WSDL), the contents of the file you want to upload are read and put in an associative array. Then the client calls the Upload method and passes in this array to actually upload the file. Finally the return value is checked to determine whether the upload succeeded.</p>
<p>If you execute the PHP script a couple of times you will see a number of GUID-named .dat files appearing in the same folder that hosts your ConsoleHost.exe application. </p>
<p><strong>Figure 2</strong> &#8211; Uploaded files<br />
<a href="http://cgeers.files.wordpress.com/2009/08/uploaded-files.jpg"><img src="http://cgeers.files.wordpress.com/2009/08/uploaded-files.jpg?w=250&#038;h=293" alt="Uploaded Files" title="Uploaded Files" width="250" height="293" class="aligncenter size-full wp-image-935" /></a></p>
<p>While testing my script I choose to upload a simple text file (test.txt), but any file will do. Just make sure to adjust your PHP script accordingly. When uploading large files your WCF service might time out and throw an exception. You need to adjust your service&#8217;s <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.binding.receivetimeout(VS.85).aspx" target="_blank">timeout settings</a> in this case.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="messagecontract" name="messagecontract"></a><strong>MessageContract</strong></p>
<p>The &#8220;Hello, World&#8221; example I choose for this article enables you to upload a file. I particularly choose this functionality as it lends itself quite easily to implement the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.messagecontractattribute.aspx" target="_blank">MessageContract attribute</a>. As you can see in Listing 1 the Upload(&#8230;) method only takes only one parameter, namely a stream of the file itself. When using a stream to upload a file (or any arbitrary data) it can be the only parameter passed in the body of the request. </p>
<p>Since we are using the HTTP transport and SOAP it can be the only parameter in the body of the soap message / envelope. If we want to send extra parameters along, then we have to insert these in the header of the request / SOAP message. This is where the MessageContract attribute comes to the rescue. It helps us shape the SOAP envelope and determine what is placed in the header and what is placed in the body of the SOAP message. </p>
<p>Suppose we want to send the original filename and filesize (expressed in bytes) along with the actual file itself (Stream parameter). To do this add a new class FileUploadInputParameter to the CGeers.Wcf.Services project and add the following code to it:</p>
<p><strong>Listing 6</strong> &#8211; FileUploadInputParameter </p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[MessageContract]
<span class="kwrd">public</span> <span class="kwrd">class</span> FileUploadInputParameter
{
    [MessageHeader(MustUnderstand = <span class="kwrd">true</span>)]
    <span class="kwrd">public</span> <span class="kwrd">string</span> FileName { get; set; }

    [MessageHeader(MustUnderstand = <span class="kwrd">true</span>)]
    <span class="kwrd">public</span> <span class="kwrd">int</span> FileSize { get; set; }

    [MessageBodyMember(Order = 1)]
    <span class="kwrd">public</span> Stream Stream { get; set; }
}</pre>
</div>
<p>By decorating the FileUploadInputParameter class with the MessageContract attribute you define a strongly-typed class that corresponds to a SOAP message. Using the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.messageheaderattribute.aspx" target="_blank">MessageHeader</a> and <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.messagebodymemberattribute.aspx" target="_blank">MessageBodyMember</a> attribute you can specify which properties of the class are respectively placed in the header and which are to be inserted in the body.</p>
<p><strong>Remark</strong>: WCF states that when using the MessageContract attribute in your service operation that you cannot mix it with regular serializable parameters. Either only use custom message types (= class types decorated with the MessageContract attribute) or only use regular serializable parameters for the input parameters and return value of your service operation.</p>
<p>This means we have to use a custom message type for the return value of our service operation as well. Since this is only a boolean let&#8217;s quickly wrap it in a new class type and decorate it with the necessary attributes. Add a new class FileUploadReturnValue to the CGeers.Wcf.Services project and add the code shown in Listing 7 to it.</p>
<p><strong>Listing 7</strong> &#8211; FileUploadReturnValue</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[MessageContract]
<span class="kwrd">public</span> <span class="kwrd">class</span> FileUploadReturnValue
{
    [MessageBodyMember(Order = 1)]
    <span class="kwrd">public</span> <span class="kwrd">bool</span> UploadSucceeded { get; set; }
}</pre>
</div>
<p>This message type does not include any headers and places one single boolean named UploadSucceeded in the body of the envelope.</p>
<p>Voila, the message contracts are in place. Let&#8217;s add a new service operation to our service (IFileUploadService.cs). Very originally I&#8217;ve named it UploadWithMessageContract(&#8230;).</p>
<p><strong>Listing 8</strong> &#8211; UploadWithMessageContract(&#8230;) Service Operation</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[OperationContract]
FileUploadReturnValue UploadWithMessageContract(FileUploadInputParameter file);</pre>
</div>
<p>The implementation of this new service operation in the FileUploadService class is very simular to that of our regular Upload(&#8230;) method. The only difference is that instead of generating a random filename based on a Guid we use the filename provided to us. Also note that the return value (true / false) is being wrapped in our custom message type (FileUploadReturnValue).</p>
<p><strong>Listing 9</strong> &#8211; UploadWithMessageContract Implementation</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> FileUploadReturnValue UploadWithMessageContract(FileUploadInputParameter file)
{
    <span class="kwrd">try</span>
    {
        <span class="rem">// Read the incoming stream and save it to file</span>
        SaveFile(file.FileName, file.Stream);
        <span class="kwrd">return</span> <span class="kwrd">new</span> FileUploadReturnValue {UploadSucceeded = <span class="kwrd">true</span>};
    }
    <span class="kwrd">catch</span> (Exception)
    {
        <span class="rem">// Gulp</span>
        <span class="kwrd">return</span> <span class="kwrd">new</span> FileUploadReturnValue {UploadSucceeded = <span class="kwrd">false</span>};
    }
}</pre>
</div>
<p>Since the Upload(&#8230;) and UploadWithMessageContract(&#8230;) methods both use the same code for saving the incoming file I&#8217;ve moved this code to a separate helper method named SaveFile(string filename, Stream stream). Check the accompanying source code to see the code for this method.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="revisedclient" name="revisedclient"></a><strong>Revised PHP Client</strong></p>
<p>We have to revise our PHP client a bit before we can call the new UploadWithMessageContract(&#8230;) method. Here&#8217;s the adjusted code:</p>
<p><strong>Listing 10</strong> &#8211; Revised PHP Client</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
&lt;?php

<span class="rem">// Function to read the contents of a file</span>
function GetFileContents( $filename ) {
  $handle = fopen($filename, <span class="str">"r"</span>);
  $contents = fread($handle, filesize($filename));
  fclose($handle);
  <span class="kwrd">return</span> $contents;
}

<span class="rem">// Create a new soap client based on the service's metadata (WSDL)</span>
$client = <span class="kwrd">new</span> SoapClient(<span class="str">"http://localhost:8731/FileUploadService?wsdl"</span>);

<span class="rem">// Specify the file to upload</span>
$filename = <span class="str">"test.txt"</span>;

<span class="rem">// Twee headers (FileName &amp; Length) wordt in de SOAP envelope geplaatst</span>
$headers[] = <span class="kwrd">new</span> SoapHeader(<span class="str">'http://tempuri.org/'</span>,
                            <span class="str">'FileName'</span>,
                            <span class="str">"test.txt"</span>);

$headers[] = <span class="kwrd">new</span> SoapHeader(<span class="str">'http://tempuri.org/'</span>,
                            <span class="str">'FileSize'</span>,
                            filesize($filename));

$client-&gt;__setSoapHeaders($headers);

<span class="rem">// Specify the parameters for the Upload(...) method as an associative array</span>
$parameters = array(<span class="str">"Stream"</span> =&gt; GetFileContents($filename));

<span class="rem">// Upload the file</span>
$result = $client-&gt;UploadWithMessageContract($parameters);

<span class="rem">// Check if the upload succeeded</span>
<span class="kwrd">if</span> ($result-&gt;UploadSucceeded) {
    echo $filename . <span class="str">" uploaded"</span>;
}
<span class="kwrd">else</span> {
    echo $filename . <span class="str">" upload failed"</span>;
}

?&gt;</pre>
</div>
<p>The only adjustments made here all the creation of the soap headers and their injection into the SOAP message. The rest is simular to that of the example shown in Listing 5. Because the response message has also been wrapped inside a custom message type the check to read the response is also slightly different.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="summary" name="summary"></a><strong>Summary</strong></p>
<p>I hope you enjoyed this article which demonstrated the interoperability between .NET and PHP 5 using web services. Exchanging data over the HTTP transport using SOAP (v1.1) messages is a breeze between these two technologies. </p>
<p>Setting up your WCF service and exposing it through an endpoint which uses the httpBasicBinding enables PHP clients to consume these services through the SoapClient class. Service operations which require data to be included through the use of SOAP headers (MessageContract attribute) can also be called using PHP 5 built-in SOAP supported provided ofcourse that you include this information in the headers.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="download" name="download"></a><strong>Download</strong></p>
<p>You can find the source code for this article on the <a href="http://cgeers.wordpress.com/download/" target="_blank">Download page</a> of this blog.</p>
<p>The source code only contains the C# code for the WCF service. The entire PHP code for creating the clients can be found in Listing 5 &amp; 10.</p>
<p><a href="#top">Top of page</a></p>
Posted in C#, PHP, Programming, WCF  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/894/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/894/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cgeers.wordpress.com/894/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cgeers.wordpress.com/894/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cgeers.wordpress.com/894/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cgeers.wordpress.com/894/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cgeers.wordpress.com/894/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cgeers.wordpress.com/894/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cgeers.wordpress.com/894/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cgeers.wordpress.com/894/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.wordpress.com&blog=2504479&post=894&subd=cgeers&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://cgeers.wordpress.com/2009/08/20/using-wcf-services-with-php-5/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1deb97b690d087dea7942250d7b03310?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2008/04/dotnetwcf.gif" medium="image" />

		<media:content url="http://cgeers.files.wordpress.com/2009/08/php1.gif" medium="image" />

		<media:content url="http://cgeers.files.wordpress.com/2009/08/fileuploadservice1.jpg?w=300" medium="image">
			<media:title type="html">File Upload Service Test Page</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/08/uploaded-files.jpg" medium="image">
			<media:title type="html">Uploaded Files</media:title>
		</media:content>
	</item>
		<item>
		<title>Monitoring A Directory</title>
		<link>http://cgeers.wordpress.com/2009/08/14/monitoring-a-directory/</link>
		<comments>http://cgeers.wordpress.com/2009/08/14/monitoring-a-directory/#comments</comments>
		<pubDate>Fri, 14 Aug 2009 08:16:25 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Directory]]></category>
		<category><![CDATA[FileSystemWatcher]]></category>
		<category><![CDATA[MEF]]></category>
		<category><![CDATA[Monitor]]></category>

		<guid isPermaLink="false">http://cgeers.wordpress.com/?p=840</guid>
		<description><![CDATA[Introduction
The subject of this article is a tad less modern than the previous two articles: WCF over HTTPS &#38; MEF. Instead of focusing on a modern technology such as WCF or the upcoming Managed Extensibility Framework, I have a craving to write an article about the good ol&#8217; FileSystemWatcher Class. 
It&#8217;s been around since .NET [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.wordpress.com&blog=2504479&post=840&subd=cgeers&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a title="introduction" name="introduction"></a><strong>Introduction</strong></p>
<p>The subject of this article is a tad less modern than the previous two articles: <a href="http://cgeers.wordpress.com/2009/08/07/wcf-over-https/" target="_blank">WCF over HTTPS</a> &amp; <a href="http://cgeers.wordpress.com/2009/08/10/net-4-0-managed-extensibiliy-framework-mef/" target="_blank">MEF</a>. Instead of focusing on a modern technology such as WCF or the upcoming Managed Extensibility Framework, I have a craving to write an article about the good ol&#8217; <a href="http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx" target="_blank">FileSystemWatcher Class</a>. </p>
<p>It&#8217;s been around since .NET 1.0 but the other day when I was composing the article about <a href="http://cgeers.wordpress.com/2009/08/10/net-4-0-managed-extensibiliy-framework-mef/" target="_blank">MEF</a> it was brought back to my attention. MEF contains a <a href="http://mef.codeplex.com/Wiki/View.aspx?title=Using%20Catalogs&amp;referringTitle=Home" target="_blank">DirectoryCatalog</a> type, which allows you to specify a directory that contains assemblies that in turn contain extensions (exports) for your application. </p>
<p>In an earlier preview of MEF the DirectoryCatalog type automatically detected new assemblies placed inside of this directory and refreshed the loaded extensions. However this functionality has been dropped in favor of a Refresh() method which you have to call yourself. In other words you are now responsible for detecting new additions to said directory.</p>
<p>The main focus of this article is on how to use the FileSystemWatcher class type effectively for monitoring a directory for new, incoming files. Enough introductionary chit-chat, let&#8217;s get to the meat of it&#8230;</p>
<p><span id="more-840"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#hello">Hello, World!</a></li>
<li><a href="#basics">The Basics</a></li>
<li><a href="#handling">Handling The Created Event</a></li>
<li><a href="#volumes">Large Volumes</a></li>
<li><a href="#processing">Asynchronous Processing</a></li>
<li><a href="#mef">Applied to MEF</a></li>
<li><a href="#summary">Summary</a></li>
<li><a href="#download">Download</a></li>
</ul>
<p><a title="hello" name="hello"></a><strong>Hello, World!</strong></p>
<p>I usually build demo applications in order to get my point accross and this article is no different. Let us not ponder about MEF&#8217;s DirectoryCatalog type but instead focus on a more &#8220;Hello, World!&#8221;-ish example. </p>
<p>Imagine an application which needs to monitor a directory for newly added text files. These text files needs to be processed and deleted afterwards . </p>
<p>In the real-world you would probably use a Windows service for this type of application as no real GUI is needed, but since this is a demo and some kind of output is preferable the .NET&#8217;s universe black gold comes in handy. You guessed it, let&#8217;s create another fancy console application. </p>
<p>For starters fire up Visual Studio and create a new blank solution called &#8220;FileSystemWatcher&#8221;. Next add a new console application project named &#8220;ConsoleMonitor&#8221;. We&#8217;re now ready to lay the groundwork&#8230;</p>
<p><a href="#top">Top of page</a></p>
<p><a title="basics" name="basics"></a><strong>The Basics</strong></p>
<p>In order to setup a FileSystemWatcher for the purpose of monitoring a directory you need hook it up properly. The following properties and events relate to our demo:</p>
<p><strong>Properties</strong>:</p>
<ul>
<li><strong>Path</strong>: Identifies the path of the directory to watch</li>
<li><strong>Filter</strong>: Filter used to determine which files are monitored (e.g.: *.txt, *.xml&#8230;etc.)</li>
<li><strong>EnableRaisingEvents</strong>: The most important one of all. By default it is false, but you need to set it to true to enable the FileSystemWatcher instance. If you don&#8217;t do this then it will not raise any events when files are created, deleted, changed&#8230;etc. In a Windows service you would set this property to true upon starting the service and to false when stopping it.</li>
</ul>
<p>Another useful property is IncludeSubDirectories. By default it is set to false, but by setting it to true the FileSystemWatcher will also monitor the subdirectories found within the specified path.</p>
<p><strong>Events</strong>:</p>
<ul>
<li><strong>Created</strong>: This event is triggered whenever a file or directory in the specified path is created. By specifying a filter you opt to only receive notifications for the type of files you specified.</li>
</ul>
<p>Similarly the events Changed, Deleted and Renamed are also available. Their name implies when they are triggered. Since the focus of our demo only deals with newly created files we don&#8217;t need these. Feel free to explore <a href="http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher_members.aspx" target="_blank">these events</a> on your own.</p>
<p>Let&#8217;s setup the basics for our console application. Your code should resemble that of Listing 1:</p>
<p><strong>Listing 1</strong> &#8211; Monitoring A Directory</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">class</span> Program
{
    <span class="kwrd">private</span> <span class="kwrd">static</span> FileSystemWatcher watcher;

    <span class="kwrd">static</span> <span class="kwrd">void</span> Main()
    {
        <span class="rem">// Make the directory being monitored exists</span>
        Assembly assembly = Assembly.GetCallingAssembly();
        <span class="kwrd">string</span> path = Path.Combine(Path.GetDirectoryName(assembly.Location), <span class="str">"input"</span>);
        <span class="kwrd">if</span> (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }

        watcher = <span class="kwrd">new</span> FileSystemWatcher {Path = path, Filter = <span class="str">"*.txt"</span>};

        watcher.Created += file_Created;
        watcher.EnableRaisingEvents = <span class="kwrd">true</span>;

        Console.WriteLine(<span class="str">"Press any key to close this application..."</span>);
        Console.ReadLine();
    }

    <span class="kwrd">static</span> <span class="kwrd">void</span> file_Created(<span class="kwrd">object</span> sender, FileSystemEventArgs e)
    {
        <span class="rem">// Process the file</span>
    }
}</pre>
</div>
<p>The code checks for a directory &#8220;Input&#8221; in the location of the executing assembly and creates if not available. Then a FileSystemWatcher instance is being setup to monitor this directory for any new text files. If a new text file is created within this directory then the file_Created(&#8230;) event handler will be triggered.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="handling" name="handling"></a><strong>Handling The Created Event</strong></p>
<p>Being an event handler the file_Created(&#8230;) method receives two parameters, namely the Sender and an EventArgs descendant. The Sender is the FileSystemWatcher instance itself and for the EventArgs you receive a <a href="http://msdn.microsoft.com/en-us/library/system.io.filesystemeventargs.aspx" target="_blank">FileSystemEventArgs</a> instance. It contains a few useful properties describing the newly created file.</p>
<ul>
<li><strong>ChangeType</strong>: The type of directory event that occured (e.g.: Changed, Created, Deleted, Renamed). Is an enumeration of type <a href="http://msdn.microsoft.com/en-us/library/t6xf43e0.aspx" target="_blank">WatcherChangeTypes</a>.</li>
<li><strong>FullPath</strong>: The fully qualified path of the file.</li>
</ul>
<p>We only need to concern ourselves with the FullPath property. At first sight you might process the files in the following manner:</p>
<p><strong>Listing 2</strong> &#8211; Processing A File</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">static</span> <span class="kwrd">void</span> file_Created(<span class="kwrd">object</span> sender, FileSystemEventArgs e)
{
    <span class="rem">// Process the file</span>
    <span class="rem">// ...</span>

    <span class="rem">// Delete the file after it has been processed</span>
    File.Delete(e.FullPath);
}</pre>
</div>
<p>This might sometimes work and on other occasions an IOException will be thrown indicating that the file is currently being used by another process. </p>
<p>This is caused by the fact that the FileSystemWatcher triggers the Created event immediately after the first byte of the new file has been written. It does not wait to trigger this event until the file has been completely created or uploaded. </p>
<p>Processing the files directly from within this event handler will eventually result in one or more IOExceptions being thrown because the creation process might still be busy creating the file and thus disallow another process from accessing it.</p>
<p>I have not found a proper solution to this problem and upon searching the net I found out that the following approach is usually implemented:</p>
<p><strong>Listing 3</strong> &#8211; IsFileUploadComplete</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">bool</span> IsFileUploadComplete(<span class="kwrd">string</span> path)
{
    <span class="kwrd">try</span>
    {
        <span class="kwrd">using</span> (File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None))
        {
            <span class="kwrd">return</span> <span class="kwrd">true</span>;
        }
    }
    <span class="kwrd">catch</span> (IOException)
    {
        <span class="kwrd">return</span> <span class="kwrd">false</span>;
    }
}</pre>
</div>
<p>The above piece of code tries to open the file exclusively for reading. If it fails an IOException is thrown indicating that the file is still being used by another process. If you have a better approach please suggest it by posting a comment or <a href="mailto:geersch@gmail.com">e-mailing me</a> directly.</p>
<p>The event handler for the Created event is then implemented as follows:</p>
<p><strong>Listing 4</strong> &#8211; Revised file_Created(&#8230;) Event Handler</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
{
    <span class="rem">// Check if the file has been completely created / uploaded</span>
    <span class="kwrd">int</span> maximumProcessRetries = 5;
    <span class="kwrd">int</span> delayBeforeRetry = 5000;

    <span class="kwrd">int</span> attempts = 0;

    <span class="kwrd">while</span> (<span class="kwrd">true</span>)
    {
        <span class="kwrd">if</span> (IsFileUploadComplete(e.FullPath))
        {
            <span class="rem">// Process the file</span>
            <span class="rem">// ...</span>

            <span class="kwrd">break</span>;
        }
        attempts += 1;
        <span class="kwrd">if</span> (attempts &gt;= maximumProcessRetries)
        {
            <span class="rem">// Log the error and send out notifications</span>
            <span class="rem">/// ...etc.</span>
            <span class="kwrd">break</span>;
        }
        Thread.Sleep(delayBeforeRetry);
    }

    <span class="rem">// Delete the file after it has been processed</span>
    File.Delete(e.FullPath);
}</pre>
</div>
<p>When a new file is created an attempt to exclusively access the file is made. If it fails the thread waits for a certain amount of time before trying again. This is repeated for a maximum number of X times. Feel free to adjust the code and perhaps make the number of retries or the delay configurable.</p>
<p>Not the nicest solution, but effective for most times the FileSystemWatcher is put to use&#8230;</p>
<p><a href="#top">Top of page</a></p>
<p><a title="volumes" name="volumes"></a><strong>Large Volumes</strong></p>
<p>Until now processing the files has been handled directly within the event handler attached to the FileSystemWatcher&#8217;s Created event. This poses no problem if you only need to handle the occasional file, but can be problematic if you need to process large batches of files.</p>
<p>Each FileSystemWatcher allocates a buffer of 8 Kb that contains all the information about the files that cause events to be raised. When a large number of files are created in the directory being monitored and the processing of each file takes up a considerable amount of time then this buffer may fill up. Any events that arrive after the buffer has been filled up will be lost. No exceptions or notifications will be thrown for these missing events.</p>
<p>The most obvious to circumvent this issue (or at least postpone it) is to increase the size of the buffer. This can be done by setting the <a href="http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.internalbuffersize.aspx" target="_blank">InternalBufferSize property</a> of the FileSystemWatcher.</p>
<p>To quote MSDN: &#8220;<em>The file system changes stored in this buffer can use up to 16 bytes of memory, not including the file name. If there are many changes in a short time, the buffer can overflow. This caused the component to lose trackof changes in the directory.</em>&#8220;. </p>
<p>So simply increasing the buffer size might do, but it also has a ramification, namely that it is quite expensive as the memory is non paged and cannot be swapped out to disk. It is better to use a small buffer and filter out any notifications you do not require.</p>
<p>There is another possible solution to postpone a buffer overflow from occuring. By handling the events you monitor, the Created event in this case, as quickly as possibly you remove the information tied to the event from the buffer so that it can reclaim this space. Credit where credit is due as this is proposed by Rohan Warang, read <a href="http://csharp-codesamples.com/2009/02/file-system-watcher-and-large-file-volumes/" target="_blank">his article</a> on <a href="http://csharp-codesamples.com/" target="_blank">csharp-codesamples.com</a>.</p>
<p>To implement this we need to asynchronously process the files. As soon as the event is triggered we queue the full path to the file in a Queue which in turn will be processed by a worker thread. The duty of the event handler tied to the Created event is reduced to adding a string (the file path) to a queue.</p>
<p>Let&#8217;s realize this. Add a new class to the console application project named FileProcessor. Add the following code:</p>
<p><strong>Listing 5</strong> &#8211; FileProcessor Class</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> FileProcessor
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> Queue&lt;<span class="kwrd">string</span>&gt; files = <span class="kwrd">new</span> Queue&lt;<span class="kwrd">string</span>&gt;();

    <span class="kwrd">public</span> <span class="kwrd">void</span> EnqueueFile(<span class="kwrd">string</span> path)
    {
        files.Enqueue(path);
    }
}</pre>
</div>
<p>The code for the event handler attached to the created event can then be minimized to this:</p>
<p><strong>Listing 6</strong> &#8211; Queuing The File</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="rem">//...</span>
<span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> FileProcessor fileProcessor = <span class="kwrd">new</span> FileProcessor();
<span class="rem">//...</span>
<span class="kwrd">static</span> <span class="kwrd">void</span> file_Created(<span class="kwrd">object</span> sender, FileSystemEventArgs e)
{
    fileProcessor.EnqueueFile(e.FullPath);
}</pre>
</div>
<p><a href="#top">Top of page</a></p>
<p><a title="processing" name="processing"></a><strong>Asynchronous Processing</strong></p>
<p>How the files are actually asynchronously processed by a FileProcessor instance has little to do with the FileSystemWatcher but let&#8217;s quickly cover it to get it out of the way. </p>
<p>Start by adding the following fields to the FileProcessor class.</p>
<p><strong>Listing 7</strong> &#8211; FileProcessor Fields</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="preproc">#region</span> Fields

<span class="kwrd">private</span> <span class="kwrd">readonly</span> Queue&lt;<span class="kwrd">string</span>&gt; files = <span class="kwrd">new</span> Queue&lt;<span class="kwrd">string</span>&gt;();
<span class="kwrd">private</span> Thread thread;
<span class="kwrd">private</span> <span class="kwrd">readonly</span> EventWaitHandle waitHandle = <span class="kwrd">new</span> AutoResetEvent(<span class="kwrd">true</span>);
<span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> <span class="kwrd">object</span> lockObject = <span class="kwrd">new</span> <span class="kwrd">object</span>();

<span class="rem">// Volatile is used as hint to the compiler that this data</span>
<span class="rem">// member will be accessed by multiple threads.</span>
<span class="rem">// http://msdn.microsoft.com/en-us/library/7a2f3ay4(VS.80).aspx</span>
<span class="kwrd">private</span> <span class="kwrd">volatile</span> <span class="kwrd">bool</span> shouldStop = <span class="kwrd">false</span>;

<span class="preproc">#endregion</span></pre>
</div>
<p>Obviously we need to declare a new queue which contains a list of String types (the paths to the files) and a new separate thread. Since this queue is accessed by multiple threads we need a lock object for synchronization purposes. The other fields waitHandle and shouldStop are used to determine if the second thread should continue with executing its worker method.</p>
<p>With these fields in place the EnqueueFile(&#8230;) method can be revised. </p>
<p><strong>Listing 8</strong> &#8211; Enqueuing The File Revised</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">void</span> EnqueueFile(<span class="kwrd">string</span> path)
{
    <span class="rem">// Queue the file</span>
    <span class="kwrd">lock</span> (lockObject)
    {
        files.Enqueue(path);
    }

    <span class="rem">// Initialize and start the worker thread when the first file is queued</span>
    <span class="rem">// or when it has been stopped and thus terminated.</span>
    <span class="kwrd">if</span> (thread == <span class="kwrd">null</span> || shouldStop)
    {
        thread = <span class="kwrd">new</span> Thread(<span class="kwrd">new</span> ThreadStart(Work));
        thread.Start();
    }
    <span class="rem">// If the thread is waiting then start it</span>
    <span class="kwrd">else</span> <span class="kwrd">if</span> (thread.ThreadState == ThreadState.WaitSleepJoin)
    {
        waitHandle.Set();
    }
}
</pre>
</div>
<p>The file is added to the queue. If it is the first file than the worker thread is created and started, if not then a check is performed to see if the waithandle should be signaled. The worker method is coupled to a worker method by using the ThreadStart delegate. This worker method aptly named Work() contains no parameters or return type and is implemented as follows:</p>
<p><strong>Listing 8</strong> &#8211; The Method That Executes On The Worker Thread</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">private</span> <span class="kwrd">void</span> Work()
{
    <span class="kwrd">while</span> (!shouldStop)
    {
        <span class="kwrd">string</span> path = String.Empty;
        <span class="kwrd">lock</span> (lockObject)
        {
            <span class="kwrd">if</span> (files.Count &gt; 0)
            {
                path = files.Dequeue();
            }
        }

        <span class="kwrd">if</span> (!String.IsNullOrEmpty(path))
        {
            <span class="rem">// Process the file</span>
            ProcessFile(path);
        }
        <span class="kwrd">else</span>
        {
            <span class="rem">// If no files are left to process then wait</span>
            waitHandle.WaitOne();
        }
    }
}</pre>
</div>
<p>This method dequeues an item of the queue and hands it off to the ProcessFile(&#8230;) method for further processing. The ProcessFile(&#8230;) method basically contains the code shown in Listing 4. The IsFileUploadComplete(&#8230;) method (Listing 3) is also moved to the FileProcessor method as a private helper method. The volatile shouldStop boolean is checked wether or not the FileProcessor should continue to process the queue. This enables you to add a method called StopProcessing() which you can call to stop the processing. Enqueuing another file afterwards would restart it.</p>
<p>This basically sums up the internal workings of the FileProcessor type. Please consult the accompanying source code for a working example.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="mef" name="mef"></a><strong>Applied To MEF</strong></p>
<p>Let&#8217;s briefly bring up MEF again. When using a DirectoryCatalog to import all the exports available in the assemblies listed in the directory to which the catalog is tied, it is possible to use the FileSystemWatcher to monitor it. You only need to call the DirectoryCatalog&#8217;s Refresh() method when new assemblies are added.</p>
<p><strong>Listing 10</strong> &#8211; Refreshing A DirectoryCatalog</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">static</span> <span class="kwrd">void</span> file_Created(<span class="kwrd">object</span> sender, FileSystemEventArgs e)
{
    directoryCatalog.Refresh();
}</pre>
</div>
<p><a href="#top">Top of page</a></p>
<p><a title="summary" name="summary"></a><strong>Summary</strong></p>
<p>Voila, that wraps up my article about the FileSystemWatcher. Though not the hottest or most modern topic I think it is still usefull today for various situations.</p>
<p>When using it you should be careful to make sure that the Created event is triggered as soon as the first byte of the file is written, <u>not</u> when the file has been completely created / uploaded. The internal buffer of the FileSystemWatcher can also overflow if your processing of the files takes up too much time while incoming notifications are still being generated. </p>
<p>I&#8217;ve tested this approach using 10.000 files and the default buffer size without any problems, which should be adequate enough for most the situations.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="download" name="download"></a><strong>Download</strong></p>
<p>You can find the source code for this article on the <a href="http://cgeers.wordpress.com/download/" target="_blank">Download page</a> of this blog.</p>
<p><a href="#top">Top of page</a></p>
Posted in C#, Programming  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/840/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/840/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cgeers.wordpress.com/840/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cgeers.wordpress.com/840/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cgeers.wordpress.com/840/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cgeers.wordpress.com/840/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cgeers.wordpress.com/840/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cgeers.wordpress.com/840/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cgeers.wordpress.com/840/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cgeers.wordpress.com/840/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.wordpress.com&blog=2504479&post=840&subd=cgeers&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://cgeers.wordpress.com/2009/08/14/monitoring-a-directory/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1deb97b690d087dea7942250d7b03310?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>
	</item>
		<item>
		<title>.NET 4.0: Managed Extensibiliy Framework (MEF)</title>
		<link>http://cgeers.wordpress.com/2009/08/10/net-4-0-managed-extensibiliy-framework-mef/</link>
		<comments>http://cgeers.wordpress.com/2009/08/10/net-4-0-managed-extensibiliy-framework-mef/#comments</comments>
		<pubDate>Mon, 10 Aug 2009 13:23:01 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[MEF]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Managed Extensibility Framework]]></category>

		<guid isPermaLink="false">http://cgeers.wordpress.com/?p=781</guid>
		<description><![CDATA[Introduction
Yesterday, on a sunny sunday morning I was catching up on some blog reading. One post in particular caught my eye, namely A Whirlwind Tour Through The Managed Extensibility Framework by Bart De Smet. 
The Managed Extensibility Framework, or MEF, is a new library that will eventually be part of the .NET 4.0 Framework. It [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.wordpress.com&blog=2504479&post=781&subd=cgeers&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a title="introduction" name="introduction"></a><strong>Introduction</strong><a href="http://cgeers.files.wordpress.com/2009/08/mef.jpg"><img src="http://cgeers.files.wordpress.com/2009/08/mef.jpg?w=80&#038;h=80" alt="MEF" title="MEF" width="80" height="80" class="alignright size-full wp-image-786" /></a></p>
<p>Yesterday, on a sunny sunday morning I was catching up on some blog reading. One post in particular caught my eye, namely <a href="http://community.bartdesmet.net/blogs/bart/archive/2009/08/07/a-whirlwind-tour-through-the-managed-extensibility-framework.aspx" target="_blank">A Whirlwind Tour Through The Managed Extensibility Framework</a> by <a href="http://community.bartdesmet.net/blogs/bart/default.aspx" target="_blank">Bart De Smet</a>. </p>
<p>The Managed Extensibility Framework, or MEF, is a new library that will eventually be part of the .NET 4.0 Framework. It enables you to easily create extensible applications that support a plugin model. A lot of modern, popular applications such as FireFox, Winamp, Visual Studio&#8230;etc. already provide a plugin / add-in model that allows you to add your own plugins if you want to extend the functionality of the application. </p>
<p>Making your application extensible in the past was certainly possible but you had to create the infrastructure from scratch. Well, no more! MEF allows you to expose certain parts of your application in which you can import built-in or external extensions.</p>
<p>Let&#8217;s discover the wonderful world of MEF by building a demo application&#8230;</p>
<p><span id="more-781"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#preview">MEF Preview</a></li>
<li><a href="#helloworld">Hello, World!</a></li>
<li><a href="#extensibility">Extensibility</a></li>
<li><a href="#import">Importing ILogger Implementations</a></li>
<li><a href="#export">Export ILogger Implementations</a></li>
<li><a href="#catalogs">Catalogs</a></li>
<li><a href="#summary">Summary</a></li>
<li><a href="#download">Download</a></li>
</ul>
<p><a title="preview" name="preview"></a><strong>MEF Preview</strong></p>
<p>Although the .NET 4.0 Framework has not been released yet, you can download a preview of <a href="http://mef.codeplex.com/" target="_blank">MEF on Codeplex</a>. At the time of writing the latest release is preview 6. Go ahead and download it.</p>
<p>After extracting the contents of the MEF_Preview_6.zip file you&#8217;ll get an entire solution. You only to need to add a reference to the assembly called System.ComponentModel.Composition.dll found in the bin folder to the projects which you want to MEF-enable.</p>
<p>For more information you can consult the <a href="http://mef.codeplex.com/Wiki/View.aspx?title=Guide" target="_blank">MEF Programming Guide</a> on CodePlex.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="helloworld" name="helloworld"></a><strong>Hello, World!</strong></p>
<p>Before entering the world of MEF let&#8217;s first setup an example application which we can rewrite later on. Start up Visual Studio and create a new blank solution called &#8220;Mef&#8221; and add a new ConsoleApplication project aptly named ConsoleApplication. </p>
<p>I prefer Console applications for short demos as I don&#8217;t have to bother with any GUI design. As for the code of this ingenious application please take a look at Listing 1. Prepare to be amazed at the complexity of the code&#8230;</p>
<p><strong>Listing 1</strong> &#8211; Hello, World! Console Application.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">class</span> Program
{
    <span class="kwrd">static</span> <span class="kwrd">void</span> Main()
    {
        ConsoleLogger logger = <span class="kwrd">new</span> ConsoleLogger();
        logger.Log(<span class="str">"Hello, World!"</span>);
        Console.ReadLine();
    }
}

<span class="kwrd">public</span> <span class="kwrd">interface</span> ILogger
{
    <span class="kwrd">void</span> Log(<span class="kwrd">string</span> message);
}

<span class="kwrd">public</span> <span class="kwrd">class</span> ConsoleLogger : ILogger
{
    <span class="kwrd">public</span> <span class="kwrd">void</span> Log(<span class="kwrd">string</span> message)
    {
        Console.WriteLine(message);
    }
}</pre>
</div>
<p>As you can see one interface, ILogger, is declared which contains a method Log(string message) which takes one string parameter called message. The ConsoleLogger class provides an implementation for this interface and writes the message parameter out to the console window. </p>
<p>Finally the Main(&#8230;) method of the console application instantiates a ConsoleLogger object and calls it&#8217;s Log(&#8230;) method in order to print a message to the console window. It can&#8217;t get much simpler than this&#8230;</p>
<p><strong>Remark</strong>: Listing 1 shows all the code as if it were located in the same source file. If you prefer you can place it in seperate code files. I have done so for the source code accompanying this article.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="extensibility" name="extensibility"></a><strong>Extensibility</strong></p>
<p>Suppose I don&#8217;t want to limit my &#8220;logging application&#8221; to only be able to log messages to the Console window. I&#8217;m not going to look at the console window 24/7, so it might come in handy if the application was able to log it&#8217;s messages to more than one target. Instead of printing messages to the console window it could e-mail them, write them to an event log, to a file&#8230;etc.</p>
<p>Let&#8217;s create another implementation for our ILogger and rewrite the application to support multiple loggers.</p>
<p><strong>Listing 2</strong> &#8211; Supporting Multiple Loggers</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">class</span> Program
{
    <span class="kwrd">public</span> <span class="kwrd">static</span> IEnumerable&lt;ILogger&gt; Loggers { get; set; }

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Log(<span class="kwrd">string</span> message)
    {
        <span class="kwrd">foreach</span>(ILogger logger <span class="kwrd">in</span> Loggers)
        {
            logger.Log(message);
        }
    }

    <span class="kwrd">static</span> <span class="kwrd">void</span> Main()
    {
        Loggers = <span class="kwrd">new</span> List&lt;ILogger&gt; {<span class="kwrd">new</span> ConsoleLogger(), <span class="kwrd">new</span> FileLogger()};
        Log(<span class="str">"Hello, World!"</span>);
        Console.ReadLine();
    }
}

<span class="kwrd">public</span> <span class="kwrd">class</span> FileLogger : ILogger
{
    <span class="kwrd">public</span> <span class="kwrd">void</span> Log(<span class="kwrd">string</span> message)
    {
        <span class="rem">// Write the message to a file</span>
    }
}</pre>
</div>
<p>Voila, now our application supports multiple loggers. In the future you can add additional loggers by adding them the Loggers collection in the Main(&#8230;) method. But that means changing the source code of the application and recompiling it. Wouldn&#8217;t it be neat if the application was smart enough to figure out which Logger implementations it would need to use? Enter MEF&#8230;</p>
<p><a href="#top">Top of page</a></p>
<p><a title="import" name="import"></a><strong>Importing ILogger Implementations</strong></p>
<p>In it&#8217;s most simplest form MEF is as simple as 1-2-3. First you need to define the needed parts (Imports &amp; Exports) and then you hand them over to MEF so that the framework can compose the parts.</p>
<p>To MEF-enable our logging application only three simple steps need to be followed. First we need to create, what I like to call, an extensibility point for our application. </p>
<p>From our application&#8217;s point of view it needs to collect all the ILogger implementations it can find and add them to a collection. Let&#8217;s rewrite our logging logic once again.</p>
<p>Add new class Logger to the console project and paste in the following code.</p>
<p><strong>Listing 3</strong> &#8211; Logger class</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> Logger
{
    <span class="kwrd">public</span> Logger()
    {
        Loggers = <span class="kwrd">new</span> List&lt;ILogger&gt;();
    }

    <span class="kwrd">public</span> IEnumerable&lt;ILogger&gt; Loggers { get; set; }

    <span class="kwrd">public</span> <span class="kwrd">void</span> Log(<span class="kwrd">string</span> message)
    {
        <span class="kwrd">foreach</span> (ILogger logger <span class="kwrd">in</span> Loggers)
        {
            logger.Log(message);
        }
    }
}</pre>
</div>
<p>The static Main(&#8230;) method could then simply log it&#8217;s message this way:</p>
<p><strong>Listing 4</strong> &#8211; Instantiating A Logger</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
...
Logger logger = <span class="kwrd">new</span> Logger();
logger.Log(<span class="str">"Hello, World!"</span>);
...</pre>
</div>
<p>But first the different ILogger implementations need to be added to the Loggers property of the Logger object. This collection property of type IEnumerable&lt;ILogger&gt; is going to act as our &#8220;extensibility point&#8221;.</p>
<p><strong>Listing 5</strong> &#8211; ImportMany Attribute</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[ImportMany(<span class="kwrd">typeof</span>(ILogger))]
<span class="kwrd">public</span> IEnumerable&lt;ILogger&gt; Loggers { get; set; }</pre>
</div>
<p>By decorating the Loggers property with the ImportMany attribute we are basically notifying the MEF framework that this property accepts ILogger implementations or exports. </p>
<p><strong>Remark</strong>: MEF also offers an Import attribute if you only want to import one instance instead of an entire collection. You can read more about declaring imports in the <a href="http://mef.codeplex.com/Wiki/View.aspx?title=Declaring%20Imports&amp;referringTitle=Home" target="_blank">MEF Programming Guide</a>.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="export" name="export"></a><strong>Export ILogger Implementations</strong></p>
<p>As it stands now the logging logic is being handled by the Logger class and all the console application does is create a Logger object and call it&#8217;s Log(&#8230;) method. If you were to run the application now nothing would be logged. </p>
<p>We still need to tell MEF were it can find the ILogger implementations. We need to mark the ILogger implementations or export them in MEF parlance. </p>
<p><strong>Listing 6</strong> &#8211; Export Attribute</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[Export(<span class="kwrd">typeof</span>(ILogger))]
<span class="kwrd">public</span> <span class="kwrd">class</span> ConsoleLogger : ILogger
{
    <span class="rem">// ...</span>
}

[Export(<span class="kwrd">typeof</span>(ILogger))]
<span class="kwrd">public</span> <span class="kwrd">class</span> FileLogger : ILogger
{
    <span class="rem">// ...</span>
}</pre>
</div>
<p>By decorating the ConsoleLogger and FileLogger class types with the Export attribute you make them available to the MEF framework. By specifying the type of the ILogger interface the framework will be able to bind these types to our &#8220;extensibility point&#8221; we created earlier.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="catalog" name="catalog"></a><strong>Catalogs</strong></p>
<p>The imports and exports are also called composable parts. Now that all the parts are in place to form our compisition the last thing we need to do is to tell MEF how it should bind the exports to the imports. This is done using catalogs.</p>
<p>Using a catalog you can list all of the ILogger implementations you want to provide to the Logger class. Add the following code to the Main(&#8230;) method of the console application:</p>
<p><strong>Listing 7</strong> &#8211; TypeCatalog</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
TypeCatalog catalog = <span class="kwrd">new</span> TypeCatalog(<span class="kwrd">typeof</span>(ConsoleLogger), <span class="kwrd">typeof</span>(FileLogger));
CompositionContainer container = <span class="kwrd">new</span> CompositionContainer(catalog);
container.ComposeParts(logger);</pre>
</div>
<p>The above example creates a TypeCatalog and adds the ConsoleLogger and FileLogger types to it. Next a CompositionContainer is created passing in the catalog. The container then composes all of the parts using our Logger instance. The magic that happens in the container makes sure that our loggers get instantiated and added to the  IEnumerable&lt;ILogger&gt; collection of the Logger object.</p>
<p>Starting the application now will log the &#8220;Hello, World!&#8221; message to the Console window and to file. However when you want to create a new logger type you still need to adjust the code and add the new type to the TypeCatalog. That&#8217;s not what we want. Luckily MEF provides you with different types of catalogs. Consider the following examples:</p>
<p>Using the AssemblyCatalog type you can discover all of the exports in a given assembly. In this example the currently executing assembly is used but any other will do.</p>
<p><strong>Listing 8</strong> &#8211; AssemblyCatalog</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
AssemblyCatalog catalog = <span class="kwrd">new</span> AssemblyCatalog(Assembly.GetExecutingAssembly());</pre>
</div>
<p><strong>Listing 9</strong> &#8211; DirectoryCatalog</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
DirectoryCatalog catalog = <span class="kwrd">new</span> DirectoryCatalog(<span class="str">@"c:\temp\loggers"</span>);</pre>
</div>
<p>Using a DirectoryCatalog you can scan all of the assemblies in a specified directory. This catalog type will certainly come in handy if you plan on building your own plugin system. Third party providers can then create their own plugins and place them in a certain directory so that the application can detect them.</p>
<p>To enable this for our logging application please follow these steps:</p>
<ol>
<li>Move the ILogger interface to a new class library project called Interface. Add a reference to the Interface library from the console application project.</li>
<li>Add a new class library project called ThirdPartyLogger. Add references to the Interface library and the System.ComponentModel.Composition assembly.</li>
<li>Add a new logger type to the ThirdPartyLogger library. Make sure it implements the ILogger interface and is marked with the Export attribute.</li>
<li>Compile the ThirdPartyLogger project and place the resulting assembly in the directory specified by the DirectoryCatalog.</li>
</ol>
<p>An example third party logger could be a logger that sends every message out via e-mail (not that I&#8217;m advocating e-mail as a logging tool):</p>
<p><strong>Listing 10</strong> &#8211; Third Party Logger</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[Export(<span class="kwrd">typeof</span>(ILogger))]
<span class="kwrd">public</span> <span class="kwrd">class</span> EmailLogger : ILogger
{
    <span class="preproc">#region</span> ILogger Members

    <span class="kwrd">public</span> <span class="kwrd">void</span> Log(<span class="kwrd">string</span> message)
    {
        <span class="rem">// Log the message to e-mail</span>
        <span class="rem">// ...</span>
    }

    <span class="preproc">#endregion</span>
}</pre>
</div>
<p>And luckily you can use multiple catalogs specifying difference sources by setting up an aggregate catalog.</p>
<p><strong>Listing 11</strong> &#8211; AggregateCatalog</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
AssemblyCatalog assemblyCatalog = <span class="kwrd">new</span> AssemblyCatalog(Assembly.GetExecutingAssembly());
DirectoryCatalog directoryCatalog = <span class="kwrd">new</span> DirectoryCatalog(<span class="str">@"c:\temp\loggers"</span>);

AggregateCatalog catalog =
    <span class="kwrd">new</span> AggregateCatalog(<span class="kwrd">new</span> ComposablePartCatalog[] { assemblyCatalog, directoryCatalog });</pre>
</div>
<p>The code abode creates instances the AssemblyCatalog and DirectoryCatalog type and aggregates them in a AggregateCatalog instance. This instance can then be used by a CompositionContainer.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="summary" name="summary"></a><strong>Summary</strong></p>
<p>I hope this article sparked your interest in the Managed Extensibility Framework or MEF, which will be included in the upcoming .NET Framework 4.0. By simply following three steps, namely: Import, Export and Compose you can easily create an extensible application and offer alot of additional functionality to your users even if the application has already been deployed. </p>
<p>By building in the necessary extensibility points you can prepare for the unknown and allow your application to be extended without recompiling it.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="download" name="download"></a><strong>Download</strong></p>
<p>You can find the source code for this article on the <a href="http://cgeers.wordpress.com/download/" target="_blank">Download page</a> of this blog.</p>
<p><a href="#top">Top of page</a></p>
Posted in C#, MEF, Programming  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/781/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/781/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cgeers.wordpress.com/781/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cgeers.wordpress.com/781/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cgeers.wordpress.com/781/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cgeers.wordpress.com/781/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cgeers.wordpress.com/781/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cgeers.wordpress.com/781/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cgeers.wordpress.com/781/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cgeers.wordpress.com/781/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.wordpress.com&blog=2504479&post=781&subd=cgeers&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://cgeers.wordpress.com/2009/08/10/net-4-0-managed-extensibiliy-framework-mef/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1deb97b690d087dea7942250d7b03310?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/08/mef.jpg" medium="image">
			<media:title type="html">MEF</media:title>
		</media:content>
	</item>
		<item>
		<title>WCF over HTTPS</title>
		<link>http://cgeers.wordpress.com/2009/08/07/wcf-over-https/</link>
		<comments>http://cgeers.wordpress.com/2009/08/07/wcf-over-https/#comments</comments>
		<pubDate>Fri, 07 Aug 2009 13:54:53 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[File Upload]]></category>
		<category><![CDATA[HTTPS]]></category>
		<category><![CDATA[SSL]]></category>

		<guid isPermaLink="false">http://cgeers.wordpress.com/?p=691</guid>
		<description><![CDATA[Introduction
A couple of weeks ago I was asked to write a web service that needed to provide a single operation (method) that allowed the user to upload a file using a Secure Sockets Layer (SSL / HTTPS) .
Although they changed their minds and went for a solution using a VPN connection, I still decided to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.wordpress.com&blog=2504479&post=691&subd=cgeers&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a title="introduction" name="introduction"></a><strong>Introduction</strong><img class="alignnone size-medium wp-image-24 alignright" style="float:right;" src="http://cgeers.files.wordpress.com/2008/04/dotnetwcf.gif?w=80&#038;h=80" alt="" width="80" height="80" /></p>
<p>A couple of weeks ago I was asked to write a web service that needed to provide a single operation (method) that allowed the user to upload a file using a Secure Sockets Layer (SSL / HTTPS) .</p>
<p>Although they changed their minds and went for a solution using a VPN connection, I still decided to create the web service in case they went back on their decision again.</p>
<p>This article outlines the steps you need to follow in order to create a service to upload a file over HTTPS using WCF. And it&#8217;s been quite a while since I wrote my last article for this blog. I figured this would make an interesting topic&#8230;</p>
<p><span id="more-691"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#servicecontract">WCF Service Contract</a></li>
<li><a href="#serviceimplementation">Service Implementation</a></li>
<li><a href="#servicehost">Hosting The Service</a></li>
<li><a href="#configuration">Configuring The Host</a></li>
<li><a href="#ssl">SSL Certificate</a></li>
<li><a href="#client">Client Application</a></li>
<li><a href="#authenticateserver">Authenticate The Server</a></li>
<li><a href="#authenticateclient">Authenticate The Client</a></li>
<li><a href="#summary">Summary</a></li>
<li><a href="#download">Download</a></li>
</ul>
<p><a title="servicecontract" name="servicecontract"></a><strong>WCF Service Contract</strong></p>
<p>Let&#8217;s start by laying the groundwork for the WCF Service. As stated the service must enable users to upload a file to the web server which hosts it. Thus the resulting service contract only contains one method, aptly named Upload(&#8230;).</p>
<p>Start by opening up Visual Studio 2008 and create a new blank solution called WcfOverHttps. Next add a new WCF Service Library titled CGeers.Wcf.Services. This class library contains some automatically generated files (IService1.cs, Service.cs, App.config). Rename the IService.cs file to IFileUploadService.cs.</p>
<p><strong>Figure 1</strong> &#8211; Solution Explorer</p>
<p><a href="http://cgeers.files.wordpress.com/2009/08/solutionexplorer1.jpg"><img class="aligncenter size-full wp-image-698" title="Solution Explorer" src="http://cgeers.files.wordpress.com/2009/08/solutionexplorer1.jpg?w=196&#038;h=148" alt="Solution Explorer" width="196" height="148" /></a></p>
<p>The code for the service contract is displayed in Listing 1:</p>
<p><strong>Listing 1</strong> &#8211; Service Contract</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>[ServiceContract(Namespace = <span class="str">"http://cgeers.wordpress.com/wcf/services"</span>)]
<span class="kwrd">public</span> <span class="kwrd">interface</span> IFileUploadService
{
    [OperationContract]
    FileReceivedInfo Upload(FileInfo fileInfo);
}</pre>
</div>
<p>As you can see displayed in Figure 1 and Listing 1 above they mention two other classes, namely:</p>
<ol>
<li>FileInfo</li>
<li>FileReceivedInfo</li>
</ol>
<p>These classes are both decorated with the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.messagecontractattribute.aspx" target="_blank">MessageContract</a> attribute. To upload the file I opted to use streaming. WCF stipulates that the parameter that holds the data to be streamed must be the only parameter in the method.</p>
<p>You could opt to change the type of the fileInfo parameter to Stream, but then you cannot send any additional information about the file along with it. You can circumvent this issue by creating a new class which contains all of the information you want to transmit. By decorating this class with the MessageContract attribute you can use this class (or message) as a parameter or return type in your service operations.</p>
<p>The FileInfo class specifies the structure of a SOAP envelope for a particular message.</p>
<p><strong>Listing 2</strong> &#8211; FileInfo class</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>[MessageContract]
<span class="kwrd">public</span> <span class="kwrd">class</span> FileInfo
{
    [MessageHeader(MustUnderstand = <span class="kwrd">true</span>)]
    <span class="kwrd">public</span> <span class="kwrd">string</span> FileName { get; set; }

    [MessageHeader(MustUnderstand = <span class="kwrd">true</span>)]
    <span class="kwrd">public</span> <span class="kwrd">long</span> Length { get; set; }

    [MessageBodyMember(Order = 1)]
    <span class="kwrd">public</span> Stream Stream { get; set; }
}</pre>
</div>
<p>As you can see in Listing 2 the FileInfo class contains three properties. Apart from the actual file (Stream property) the filename and length of the file are also provided.</p>
<p>By applying the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.messageheaderattribute.aspx" target="_blank">MessageHeader attribute</a> to the FileName and Length propery you place this information in the header of the SOAP message. When streaming a file the body of the SOAP message must only contain the actual file itself. By applying the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.messagebodymemberattribute.aspx" target="_blank">MessageBodyMember attribute</a> to the Stream property you place it in the body of the SOAP message.</p>
<p>If your service operation contains a parameter of a type which has been decorated with the MessageContract attribute then all of the parameters and the return type used in this operation must be of a type to which this attribute has been applied.</p>
<p>You cannot mix parameters of a primitive type with message contracts. For instance if you want the Upload(&#8230;) method to return a boolean indicating if the upload succeeded or failed then you have to wrap this in another message contract.</p>
<p>Listing 3 displays how to setup the return value as a message contract. Apart from the boolean value (body) the header of this SOAP message contains the filename of the uploaded file and an optional message property which contains some information about why the upload failed.</p>
<p><strong>Listing 3</strong> &#8211; FileReceivedInfo class</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>[MessageContract]
<span class="kwrd">public</span> <span class="kwrd">class</span> FileReceivedInfo
{
    [MessageHeader(MustUnderstand = <span class="kwrd">true</span>)]
    <span class="kwrd">public</span> <span class="kwrd">string</span> FileName { get; set; }

    [MessageHeader(MustUnderstand = <span class="kwrd">true</span>)]
    <span class="kwrd">public</span> <span class="kwrd">string</span> Message { get; set; }

    [MessageBodyMember(Order = 1)]
    <span class="kwrd">public</span> <span class="kwrd">bool</span> UploadSucceeded { get; set; }
}</pre>
</div>
<p>If you try to mix message contracts and parameters of a primitive type you&#8217;ll receive the following error message:</p>
<p><em>System.InvalidOperationException: The operation &#8216;Method&#8217; could not be loaded because it has a parameter or return type of type System.ServiceModel.Channels.Message or a type that has MessageContractAttribute and other parameters of different types. When using System.ServiceModel.Channels.Message or types with MessageContractAttribute, the method must not use any other types of parameters.</em></p>
<p><a href="#top">Top of page</a></p>
<p><a title="serviceimplementation" name="serviceimplementation"></a><strong>Service Implementation</strong></p>
<p>Now that the contract for the service has been established it&#8217;s time to provide an actual implementation for it.</p>
<p>Start by renaming the Service1.cs file to FileUploadService.cs and add a reference to the System.Configuration assembly.</p>
<p>Listing 4 displays the code for implementing the service. The code is pretty straightforward. Check out the comments in the code for more explanation. Basically it reads the incoming stream and saves it to a file using familiar .NET code.</p>
<p>The Upload(&#8230;) method&#8217;s return type is of the FileReceivedInfo type. If the upload succeeds the UploadSucceeded property is set to true, if it fails this property is set to false and the message property is populated with the message property of the exception that occured.</p>
<p><strong>Listing 4</strong> &#8211; Service Implementation</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall,
    ConcurrencyMode = ConcurrencyMode.Single)]
<span class="kwrd">public</span> <span class="kwrd">class</span> FileUploadService : IFileUploadService
{
    <span class="preproc">#region</span> IFileUploadService Members

    <span class="kwrd">public</span> FileReceivedInfo Upload(FileInfo fileInfo)
    {
        <span class="kwrd">try</span>
        {
            <span class="rem">// Determine to which directory the file needs to be uploaded</span>
            <span class="kwrd">string</span> uploadDirectory =
                ConfigurationManager.AppSettings[<span class="str">"uploadDirectory"</span>];
            <span class="kwrd">if</span> (String.IsNullOrEmpty(uploadDirectory))
            {
                <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(<span class="str">"..."</span>);
            }

            <span class="rem">// Try to create the upload directory if it does not yet exist</span>
            <span class="kwrd">if</span> (!Directory.Exists(uploadDirectory))
            {
                Directory.CreateDirectory(uploadDirectory);
            }

            <span class="rem">// Check if a file with the same filename is already </span>
            <span class="rem">// present in the upload directory. If this is the case </span>
            <span class="rem">// then delete this file</span>
            <span class="kwrd">string</span> path = Path.Combine(uploadDirectory, fileInfo.FileName);
            <span class="kwrd">if</span> (File.Exists(path))
            {
                <span class="rem">// Check if the file is read-only</span>
                <span class="kwrd">if</span> ((File.GetAttributes(path) &amp; FileAttributes.ReadOnly) ==
                    FileAttributes.ReadOnly)
                {
                    File.SetAttributes(path, FileAttributes.Normal);
                }
                File.Delete(path);
            }

            <span class="rem">// Read the incoming stream and save it to file</span>
            <span class="kwrd">const</span> <span class="kwrd">int</span> bufferSize = 2048;
            <span class="kwrd">byte</span>[] buffer = <span class="kwrd">new</span> <span class="kwrd">byte</span>[bufferSize];
            <span class="kwrd">using</span> (FileStream outputStream = <span class="kwrd">new</span> FileStream(path,
                FileMode.Create, FileAccess.Write))
            {
                <span class="kwrd">int</span> bytesRead = fileInfo.Stream.Read(buffer, 0, bufferSize);
                <span class="kwrd">while</span> (bytesRead &gt; 0)
                {
                    outputStream.Write(buffer, 0, bytesRead);
                    bytesRead = fileInfo.Stream.Read(buffer, 0, bufferSize);
                }
                outputStream.Close();
            }
            <span class="kwrd">return</span> <span class="kwrd">new</span> FileReceivedInfo
                       {
                           FileName = fileInfo.FileName,
                           Message = String.Empty,
                           UploadSucceeded = <span class="kwrd">true</span>
                       };
        }
        <span class="kwrd">catch</span> (Exception ex)
        {
            <span class="kwrd">return</span> <span class="kwrd">new</span> FileReceivedInfo
                       {
                           FileName = fileInfo.FileName,
                           Message = ex.Message,
                           UploadSucceeded = <span class="kwrd">false</span>
                       };
        }
    }

    <span class="preproc">#endregion</span>
}</pre>
</div>
<p><a href="#top">Top of page</a></p>
<p><a title="servicehost" name="servicehost"></a><strong>Hosting The Service</strong></p>
<p>Now that the service has been setup it&#8217;s time to create a host for it. To keep things simple a console application will do. Add a new Console Application project to your solution named ConsoleHost. Next add references to the System.ServiceModel assembly and the CGeers.Wcf.Services project.</p>
<p>The code for the Main(&#8230;) method of the console application is slim and simple. Take a look at Listing 5.</p>
<p><strong>Listing 5</strong> &#8211; Hosting the FileUpload service</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre><span class="kwrd">static</span> <span class="kwrd">void</span> Main(<span class="kwrd">string</span>[] args)
{
    ServiceHost host = <span class="kwrd">new</span> ServiceHost(<span class="kwrd">typeof</span>(FileUploadService));
    host.Open();
    Console.WriteLine(<span class="str">"FileUpload Service Host"</span>);
    Console.WriteLine(<span class="str">"Service Started!"</span>);
    <span class="kwrd">foreach</span> (Uri address <span class="kwrd">in</span> host.BaseAddresses)
    {
        Console.WriteLine(<span class="str">"Listening on "</span> + address);
    }
    Console.WriteLine(<span class="str">"Press any key to close the host..."</span>);
    Console.ReadKey();
    host.Close();
}</pre>
</div>
<p>A new ServiceHost instance is created for the FileUploadService type and the host is then started. But before you launch the console application you still need to configure the service. Instead of doing this through code I opted to do this via an application configuration file. The next section addresses how you can easily configure your service.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="configuration" name="configuration"></a><strong>Configuring The Host</strong></p>
<p>Start by adding an application configuration (App.config) file to the ConsoleHost project. Next specify the directory in which the service should save the incoming files.</p>
<p><strong>Listing 6</strong> &#8211; Upload directory</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>&lt;appSettings&gt;
  &lt;add key=<span class="str">"uploadDirectory"</span> <span class="kwrd">value</span>=<span class="str">"C:\temp\upload"</span> /&gt;
&lt;/appSettings&gt;</pre>
</div>
<p>Now add a node to the configuration file. Within this node three child nodes will be added in order to configure the service. The first such node specifies the service&#8217;s behavior.</p>
<p><strong>Listing 7</strong> &#8211; Service Behavior</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>&lt;behaviors&gt;
  &lt;serviceBehaviors&gt;
    &lt;behavior name=<span class="str">"FileUploadServiceBehavior"</span>&gt;
      &lt;serviceMetadata httpGetEnabled=<span class="str">"False"</span> httpsGetEnabled=<span class="str">"True"</span> /&gt;
      &lt;serviceDebug includeExceptionDetailInFaults=<span class="str">"False"</span> /&gt;
    &lt;/behavior&gt;
  &lt;/serviceBehaviors&gt;
&lt;/behaviors&gt;</pre>
</div>
<p>The behavior specifies that the service should not propagate exception details and that it&#8217;s metadata should be shared over HTTPS (httpsGetEnabled) instead of HTTP (httpGetEnabled).</p>
<p>Next up is the binding for the service. Since the goal is to use HTTPS the built-in BasicHttpBinding fits the bill. A couple of its properties need to be tweaked to fit the needs of the service, namely:</p>
<ol>
<li><strong>transferMode</strong>: Set it to Streamed to enable streaming.</li>
<li><strong>messageEncoding</strong>: The message encoding is set to <a href="http://msdn.microsoft.com/en-us/library/aa395209.aspx" target="_blank">MTOM encoding</a> which is a mechanism for transmitting binary attachements with SOAP messages.</li>
<li><strong>maxReceivedMessageSize</strong>: Set to 64 megabytes to allow large files to be uploaded.</li>
<li><strong>maxBufferSize</strong>: Set to 64 kilobytes.</li>
<li><strong>receiveTimeout</strong>: Set to 10 minutes. If the file fails to upload within this time frame an exception will be thrown.</li>
</ol>
<p><strong>Remark</strong>: Configure these settings according to the needs of your application. For my application a maximum of 64 Mb for the file size and 64 KB for the buffer are sufficient.</p>
<p><strong>Listing 8</strong> &#8211; The Binding</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>&lt;bindings&gt;
  &lt;basicHttpBinding&gt;
    &lt;!-- buffer: 64KB; max size: 64MB --&gt;
    &lt;binding name=<span class="str">"FileUploadServiceBinding"</span>
             transferMode=<span class="str">"Streamed"</span>
             messageEncoding=<span class="str">"Mtom"</span>
             maxReceivedMessageSize=<span class="str">"67108864"</span> maxBufferSize=<span class="str">"65536"</span>
             closeTimeout=<span class="str">"00:01:00"</span> openTimeout=<span class="str">"00:01:00"</span>
             receiveTimeout=<span class="str">"00:10:00"</span> sendTimeout=<span class="str">"00:01:00"</span>&gt;
      &lt;security mode=<span class="str">"Transport"</span>&gt;
        &lt;transport clientCredentialType=<span class="str">"None"</span> /&gt;
      &lt;/security&gt;
    &lt;/binding&gt;
  &lt;/basicHttpBinding&gt;
&lt;/bindings&gt;</pre>
</div>
<p>Last but not least is the configuration for the service itself.</p>
<p><strong>Listing 9</strong>: FileUploadService configuration</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>&lt;services&gt;
  &lt;service behaviorConfiguration=<span class="str">"FileUploadServiceBehavior"</span>
    name=<span class="str">"CGeers.Wcf.Services.FileUploadService"</span>&gt;
    &lt;endpoint address=<span class="str">""</span> binding=<span class="str">"basicHttpBinding"</span> contract=<span class="str">"CGeers.Wcf.Services.IFileUploadService"</span>
              bindingConfiguration=<span class="str">"FileUploadServiceBinding"</span>&gt;
      &lt;identity&gt;
        &lt;dns <span class="kwrd">value</span>=<span class="str">"localhost"</span> /&gt;
      &lt;/identity&gt;
    &lt;/endpoint&gt;
    &lt;endpoint address=<span class="str">"mex"</span> binding=<span class="str">"mexHttpsBinding"</span> contract=<span class="str">"IMetadataExchange"</span> /&gt;
    &lt;host&gt;
      &lt;baseAddresses&gt;
        &lt;add baseAddress=<span class="str">"https://127.0.0.1:8741/FileUploadService/"</span> /&gt;
      &lt;/baseAddresses&gt;
    &lt;/host&gt;
  &lt;/service&gt;
&lt;/services&gt;</pre>
</div>
<p>The service&#8217;s ABC&#8217;s are specified and it&#8217;s hooked up to the behavior and binding we configured earlier. The address https://127.0.0.1:8741/FileUploadService/ is specified as being the location of the service. As you can see in the service&#8217;s binding the security is set to Transport which requires that you provide an HTTPS based address.</p>
<p><strong>Remark</strong>: Note that for the metadata exchange (mex) the mexHttpsBinding is specified and not the default mexHttpBinding.</p>
<p>If you run the ConsoleHost project now you receive the following result:</p>
<p><strong>Figure 2</strong> &#8211; ConsoleHost<br />
<a href="http://cgeers.files.wordpress.com/2009/08/consolehost.jpg"><img class="aligncenter size-full wp-image-732" title="Console Host" src="http://cgeers.files.wordpress.com/2009/08/consolehost.jpg?w=476&#038;h=131" alt="Console Host" width="476" height="131" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="ssl" name="ssl"></a><strong>SSL Certificate</strong></p>
<p>If you run the ConsoleHost project now and enter the address https://127.0.0.1:8741/FileUploadService/ in a browser you&#8217;ll receive an error. Before you can proceed , you need to bind an SSL Certificate to port 8741 for the IP address 127.0.0.1.</p>
<p>First you need to create an SSL certificate. You can do this using the makecert.exe command-line utility. Just start a new Visual Studio command prompt and enter the following command in order to create a X509 certificate which will be used for SSL communication on the localhost (127.0.0.1).</p>
<p>makecert.exe -sr LocalMachine -ss My -n CN=127.0.0.1 -sky exchange -sk -pe</p>
<p>After this command is executed, the new certificate with the private key is created and stored in the LocalMachine Personal store. To see it, use the MMC-certificate snap-in.</p>
<p>After executing this command your new certificate is created and stored in the LocalMachine Personal store. Open the MMC-certificate snap-in to see it.</p>
<ol>
<li>Click Start, Run and enter the command &#8220;mmc&#8221;</li>
<li>Click OK to start the MMC console</li>
<li>Click File | Add/Remove snap-in&#8230;</li>
<li>In the resulting dialog that pops up click the Add option and choose the Certificates snap-in</li>
<li>Confirm your changes by closing the dialog windows</li>
</ol>
<p>Afterwards you can view you new certificate in the MMC console as displayed in Figure 3.</p>
<p><strong>Figure 3</strong> &#8211; MMC Console Certificates snap-in<br />
<a href="http://cgeers.files.wordpress.com/2009/08/mmc.jpg"><img class="aligncenter size-medium wp-image-740" title="MMC Console Certificates Snap-in" src="http://cgeers.files.wordpress.com/2009/08/mmc.jpg?w=300&#038;h=187" alt="MMC Console Certificates Snap-in" width="300" height="187" /></a></p>
<p>Next you need to bind this new certificate to the port 8741. Return to the Visual Studio command prompt and enter the following command to do so:</p>
<p>httpcfg.exe set ssl -i 127.0.0.1:8741 -h cfdf5d1140b94614d047dd77c7bd4d4d4422e1c9 -Personal</p>
<p>Replace the &#8220;cfdf5d1140b94614d047dd77c7bd4d4d4422e1c9&#8243; value with the thumbprint of your own certificate. You can retrieve the thumbprint using the Certificates MMC snap-in as shown in Figure 3. Be sure to remove all the spaces.</p>
<p>If you rerun the ConsoleHost application after creating the certificate and binding it to 127.0.0.1:8741 you should receive the standard WCF service test page after entering the address https://127.0.0.1:8741/FileUploadService/ in a browser.</p>
<p><strong>Figure 4</strong> &#8211; FileUploadService<br />
<a href="http://cgeers.files.wordpress.com/2009/08/fileuploadservice.jpg"><img src="http://cgeers.files.wordpress.com/2009/08/fileuploadservice.jpg?w=300&#038;h=255" alt="FileUploadService" title="FileUploadService" width="300" height="255" class="aligncenter size-medium wp-image-747" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="client" name="client"></a><strong>Client Application</strong></p>
<p>Voila, now that the file upload service is ready we can begin to consume it. Let&#8217;s test this&#8230;</p>
<p>Add a new console application project named ConsoleClient to your solution. Next add a reference to the System.ServiceModel assembly. When done start the ConsoleHost application in non-debug mode. We need to add a reference to this service to the client application. For this the service needs to be up and running.</p>
<p>Right click on the ConsoleClient project within the Solution Explorer and choose &#8220;Add Service Reference&#8230;&#8221;. The Add Service Reference dialog is displayed. Enter the address of the service (https://127.0.0.1:8741/FileUploadService/) in the address field and click Go. The SSL certificate will be presented to the calling application (= Visual Studio). You&#8217;ll be prompted to accept the certificate. Click Yes to proceed.</p>
<p><strong>Figure 5</strong> &#8211; SSL Certificate Security Alert In Visual Studio 2008<br />
<a href="http://cgeers.files.wordpress.com/2009/08/ssl-certificate-security-al.jpg"><img src="http://cgeers.files.wordpress.com/2009/08/ssl-certificate-security-al.jpg?w=300&#038;h=235" alt="SSL Certificate Security Alert" title="SSL Certificate Security Alert" width="300" height="235" class="aligncenter size-medium wp-image-755" /></a></p>
<p>Rename the namespace ServiceReference1 to ServiceReferences and click Advanced. The Service Reference Settings dialog is shown. Make sure that the option &#8220;Always generate message contracts&#8221; is checked. Click OK to close this dialog. Click OK once more to let Visual Studio add the service reference and generate the necessary proxy classes.</p>
<p><strong>Remark</strong>: If you don&#8217;t check the option &#8220;Always generate message contracts&#8221; then the message contract&#8217;s properties will appear as individual parameters in the proxy. And for the result type you&#8217;ll only get the property that is marked as the body of the SOAP message.</p>
<p>Unchecked the Upload(&#8230;) method on the proxy will be generated as such:</p>
<p><strong>Listing 10</strong>: Always Generate Message Contracts</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">bool</span> Upload(<span class="kwrd">string</span> fileName, <span class="kwrd">long</span> length, Stream stream);
</pre>
</div>
<p>instead of</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
FileReceivedInfo Upload(FileInfo fileInfo);</pre>
</div>
<p>Once the necessary proxy classes have been generated consuming the service is an easy task. Consider the following code in the Main(&#8230;) method of the ConsoleClient application.</p>
<p><strong>Listing 11</strong> &#8211; ConsoleClient Application</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">using</span> (FileUploadServiceClient proxy = <span class="kwrd">new</span> FileUploadServiceClient())
{
    FileStream inputStream = File.Open(@"c:\temp\uploadtest.txt", FileMode.Open);

    ServiceReferences.FileInfo fileInfo =
        <span class="kwrd">new</span> ServiceReferences.FileInfo("uploaded.txt", inputStream.Length, inputStream);
    FileReceivedInfo info = proxy.Upload(fileInfo);
    <span class="kwrd">if</span> (info.UploadSucceeded)
    {
        Console.WriteLine(String.Format(<span class="str">"File {0} uploaded"</span>, info.FileName));
    }
    <span class="kwrd">else</span>
    {
        Console.WriteLine(String.Format(<span class="str">"File {0} upload failed"</span>, info.FileName));
        Console.WriteLine(info.Message);
    }
    Console.WriteLine();
    Console.ReadLine();
}</pre>
</div>
<p><a href="#top">Top of page</a></p>
<p><a title="authenticateserver" name="authenticateserver"></a><strong>Authenticate The Server</strong></p>
<p>Make sure the ConsoleHost application is still running and start the ConsoleClient application for the first time. Upon hitting the line of code that calls the Upload(&#8230;) method on the proxy you&#8217;ll receive the following error message:</p>
<p><em>Could not establish trust relationship for the SSL/TLS secure channel with authority &#8216;127.0.0.1:8741&#8242;.</em></p>
<p>This means that the server (ConsoleHost) presented the SSL certificate to the client application during the handshake and the client did not validate it. Thus a trusted relationship for the SSL/TLS secure channel could not be established.</p>
<p>To solve this problem add the following code to the beginning of the Main(&#8230;) method of the ConsoleClient application.</p>
<p><strong>Listing 12</strong> &#8211; Validating The Server</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
ServicePointManager.ServerCertificateValidationCallback += customXertificateValidation;</pre>
</div>
<p>The code for the customXertificateValidation(&#8230;) method is as follows:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">bool</span> customXertificateValidation(<span class="kwrd">object</span> sender, X509Certificate cert,
    X509Chain chain, SslPolicyErrors error)
{
    X509Certificate2 certificate = (X509Certificate2)cert;
    <span class="kwrd">if</span> (certificate.Subject == <span class="str">"CN=127.0.0.1"</span> &amp;&amp; !String.IsNullOrEmpty(certificate.Thumbprint) &amp;&amp;
        certificate.Thumbprint.ToLower() == <span class="str">"cfdf5d1140b94614d047dd77c7bd4d4d4422e1c9"</span>)
    {
        <span class="kwrd">return</span> <span class="kwrd">true</span>;
    }
    <span class="kwrd">return</span> <span class="kwrd">false</span>;
}</pre>
</div>
<p>When the customXertificateValidation(&#8230;) method is called (callback) by WCF to validate the server certificate you have the opportunity to inspect the certificate (= cert parameter). In this example the value of the Subject and Thumbprint are checked in order to validate the identity of the server. If they match then the server is authenticated, if not then the SSL connection cannot be established.</p>
<p><strong>Remark</strong>: Feel free to adjust the validation of the SSL certificate to suit your own needs.</p>
<p>Upon running the client again after applying these changes you&#8217;ll receive the message &#8220;File uploaded.txt uploaded&#8221;.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="authenticateclient" name="authenticateclient"></a><strong>Authenticate The Client</strong></p>
<p>At this point you could consider your file upload service complete, but one crucial item remains. Namely authenticating the client by the server. </p>
<p>I don&#8217;t want anyone who happens to stumble upon my service to be able to upload files to the web server. To block unauthorized users we have to validate the client. Luckily WCF allows you do so  without much hassle.</p>
<p>Let&#8217;s return to the CGeers.Wcf.Service project for a while. Add a reference to the System.IdentityModel assembly and add a new class called CustomUserNameValidator. </p>
<p><strong>Listing 13</strong> &#8211; CustomUserNameValidator</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> CustomUserNameValidator : UserNamePasswordValidator
{
    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Validate(<span class="kwrd">string</span> userName, <span class="kwrd">string</span> password)
    {
        <span class="kwrd">if</span> (userName != <span class="str">"Christophe"</span> || password != <span class="str">"WCFRocks!"</span>)
        {
            <span class="rem">// This throws an informative fault to the client.</span>
            <span class="kwrd">throw</span> <span class="kwrd">new</span> FaultException(<span class="str">"Incorrect username or password"</span>);
        }
    }
}</pre>
</div>
<p>This class derives from the UserNamePasswordValidator which can be found in the System.IdentityModel.Selectors namespace. Only one method needs to be overriden, namely the Validate(&#8230;) method. Here you need to specify your own custom code in order to validate the provided username and password. Just throw a FaultException if you cannot validate the user.</p>
<p>Next you need to configure the ConsoleHost application so that it uses the CustomUserNameValidator class in order to validate the clients. Open the App.config file of the ConsoleHost application and adjust the following settings:</p>
<p>For the basicHttpBinding set the required clientCredentialType of the transport security to Basic. This requires that the client present the necessary credentials (username &amp; password).</p>
<p><strong>Listing 14</strong> &#8211; Adjusting The Binding</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
...
&lt;security mode=<span class="str">"Transport"</span>&gt;
  &lt;transport clientCredentialType=<span class="str">"Basic"</span> /&gt;
&lt;/security&gt;
...</pre>
</div>
<p>Then add the following bit of configuration to the service behavior to tell the service how to validate the client credentials.</p>
<p><strong>Listing 15</strong> &#8211; Adjusting The Service Behavior</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
...
&lt;serviceCredentials&gt;
  &lt;userNameAuthentication
    userNamePasswordValidationMode=<span class="str">"Custom"</span>
    customUserNamePasswordValidatorType=<span class="str">"CGeers.Wcf.Services.CustomUserNameValidator, CGeers.Wcf.Services"</span> /&gt;
&lt;/serviceCredentials&gt;
...  </pre>
</div>
<p>The service is now correctly setup and requires the client to provide the necessary credentials. If you run the ConsoleClient application now you&#8217;ll receive the following error message:</p>
<p><em>The HTTP request is unauthorized with client authentication scheme &#8216;Anonymous&#8217;. The authentication header received from the server was &#8216;Basic realm=&#8221;"&#8216;.</em></p>
<p>The configuration for the client application needs to reflect the changes we made to the service. Right click on the service reference and choose &#8220;Update Service Reference&#8221;.</p>
<p>Running the client application again will now result in the following error message:</p>
<p><em>The HTTP request was forbidden with client authentication scheme &#8216;Basic&#8217;.</em></p>
<p>You still need to adjust the client application so that it passes the correct credentials to the service. Add the following lines of code to the ConsoleClient&#8217;s Main(&#8230;) method.</p>
<p><strong>Listing 16</strong> &#8211; Client Credentials</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
...
proxy.ClientCredentials.UserName.UserName = <span class="str">"Christophe"</span>;
proxy.ClientCredentials.UserName.Password = <span class="str">"WCFRocks!"</span>;
...</pre>
</div>
<p>That&#8217;s it! The client will now present valid credentials to the service and an SSL connection will be established.</p>
<p><strong>Remark</strong>: The username and password validation in this article is kept short for illustrative purposes. Replace this with you&#8217;re own validation logic in real-world applications. A better approach would be to validate the username and password against a database containing the user&#8217;s credentials.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="summary" name="summary"></a><strong>Summary</strong></p>
<p>I hope you enjoyed this tutorial on how to transfer files over HTTPS using WCF. To recap what we&#8217;ve covered from a developer&#8217;s point of view:</p>
<ul>
<li>Streaming a file over WCF</li>
<li>Configuring a WCF service for communication over HTTPS(directories)</li>
<li>Generating and binding a test SSL certificate to a port</li>
<li>Consuming a service over HTTPS</li>
<li>Authenticating the server</li>
<li>Authenticating the client</li>
</ul>
<p>Any comments, questions, tips&#8230;etc. are always appreciated.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="download" name="download"></a><strong>Download</strong></p>
<p>You can find the source code for this article on the <a href="http://cgeers.wordpress.com/download/" target="_blank">Download page</a> of this blog.</p>
<p><a href="#top">Top of page</a></p>
Posted in C#, Programming, WCF  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/691/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/691/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cgeers.wordpress.com/691/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cgeers.wordpress.com/691/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cgeers.wordpress.com/691/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cgeers.wordpress.com/691/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cgeers.wordpress.com/691/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cgeers.wordpress.com/691/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cgeers.wordpress.com/691/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cgeers.wordpress.com/691/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.wordpress.com&blog=2504479&post=691&subd=cgeers&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://cgeers.wordpress.com/2009/08/07/wcf-over-https/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1deb97b690d087dea7942250d7b03310?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2008/04/dotnetwcf.gif" medium="image" />

		<media:content url="http://cgeers.files.wordpress.com/2009/08/solutionexplorer1.jpg" medium="image">
			<media:title type="html">Solution Explorer</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/08/consolehost.jpg" medium="image">
			<media:title type="html">Console Host</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/08/mmc.jpg?w=300" medium="image">
			<media:title type="html">MMC Console Certificates Snap-in</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/08/fileuploadservice.jpg?w=300" medium="image">
			<media:title type="html">FileUploadService</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/08/ssl-certificate-security-al.jpg?w=300" medium="image">
			<media:title type="html">SSL Certificate Security Alert</media:title>
		</media:content>
	</item>
		<item>
		<title>Live Mesh: Programming against the Live Framework</title>
		<link>http://cgeers.wordpress.com/2009/04/19/live-mesh-programming-against-the-live-framework/</link>
		<comments>http://cgeers.wordpress.com/2009/04/19/live-mesh-programming-against-the-live-framework/#comments</comments>
		<pubDate>Sun, 19 Apr 2009 14:25:05 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Live Framework]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Live Services]]></category>
		<category><![CDATA[Mesh]]></category>

		<guid isPermaLink="false">http://cgeers.wordpress.com/?p=590</guid>
		<description><![CDATA[Introduction
In March I went to the Microsoft TechDays in Belgium. The last session I attended was about Microsoft&#8217;s Live Services and the Live Framework used for programming against these services. To showcase all this the Live Mesh service was used.
Live Mesh allows you to easily synchronize files with all of your devices. I tend to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.wordpress.com&blog=2504479&post=590&subd=cgeers&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a title="introduction" name="introduction"></a><strong>Introduction</strong><img class="alignright size-full wp-image-592" title="Live Mesh" src="http://cgeers.files.wordpress.com/2009/04/livemesh.png?w=150&#038;h=134" alt="Live Mesh" width="150" height="134" /></p>
<p>In March I went to the Microsoft TechDays in Belgium. The last session I attended was about Microsoft&#8217;s <a href="http://dev.live.com/" target="_blank">Live Services</a> and the Live Framework used for programming against these services. To showcase all this the <a href="http://www.mesh.com" target="_blank">Live Mesh</a> service was used.</p>
<p>Live Mesh allows you to easily synchronize files with all of your devices. I tend to visualize it as an online hard drive or repository where I can deposit files which I wish to share amongst my devices such as my laptop at work, my PDA&#8230;etc.</p>
<p>You simply have to sign up for a Mesh account and install the Live Mesh client on the devices you want to synchronize. Once the client has been installed all that remains is to add a local folder to Live Mesh. The client will then make sure this folder is synchronized automatically between all of your devices.</p>
<p>Your Live Mesh account allows you to manage the connected devices and Live Mesh folders. For example you can opt to choose between which devices you want to synchronize a certain folder.</p>
<p>When you place a new file into a Live Mesh folder, the client will upload this file to your online Mesh account. The clients on your other devices will be notified as soon as they are up and running and will synchronize with your online Mesh account. So you always have a copy of your data floating around somewhere on the cloud.</p>
<p>There is more to it than this, but this is the gist of it. The goal of this article is to demonstrate just how easy it is to use the Live Framework to program against the Live Mesh service. With a small amount of code you&#8217;ll be able to create folders and store files in your Mesh account.</p>
<p><span id="more-590"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#gettingstarted">Getting Started</a></li>
<li><a href="#resourcemodel">Live Framework Resource Model</a></li>
<li><a href="#liveframework">Connecting To The Live Services</a></li>
<li><a href="#meshobjects">Listing Mesh Objects</a></li>
<li><a href="#resources">Mesh Object Resources</a></li>
<li><a href="#createdirectory">Creating A Directory</a></li>
<li><a href="#addfile">Adding A File</a></li>
<li><a href="#retrievefile">Retrieving A File</a></li>
<li><a href="#summary">Summary</a></li>
<li><a href="#download">Download</a></li>
</ul>
<p><a title="gettingstarted" name="gettingstarted"></a><strong>Getting Started</strong></p>
<p>To get started you need to obtain the Live Framework Client. A separate sandbox environment has been setup for developers who wish to test and evaluate the Live Framework and the Live Services.</p>
<p>Since both are still in beta phase, you need to sign up for the community technology preview (CTP) program waiting list.</p>
<p>To do so just follow these steps:</p>
<ol>
<li>Visit the <a href="https://www.mesh.com/" target="_blank">Live Mesh</a> website</li>
<li>Click on the link <a href="https://www.mesh.com/web/developer.aspx" target="_blank">Developers</a> listed at the bottom of the screen</li>
<li>Sign up for an account. You need to fill in the &#8220;Azure Services Invitations Program&#8221; form.</li>
</ol>
<p>After registering for a <a href="http://www.microsoft.com/azure/windowsazure.mspx" target="_blank">Windows Azure</a> account, you&#8217;ll have to be patient and wait until the good folks at Microsoft mail you an invitation code. In my case it took about 6 hours, but I&#8217;ve heard from other people that they&#8217;d have to wait a couple of days or even weeks.</p>
<p><strong>Note</strong>: How does Windows Azure relate to Mesh? Simple: The Windows Azure platform, which is Microsoft&#8217;s platform for <a href="http://en.wikipedia.org/wiki/Cloud_computing" target="_blank">cloud computing</a>, contains the Live Services which power Mesh. Using the Live Services API allows you to program against Mesh. Take a look at this <a href="http://blogs.msdn.com/livemesh/archive/2008/10/27/how-does-live-mesh-relate-to-azure.aspx" target="_blank">blog post</a> for more information.</p>
<p>After obtaining a Windows Azure account, you&#8217;ll get an invitation code for the Microsoft .NET Services and Microsoft SQL Services. After activating this invitation code you can request another one for the Live Services. You can register for a Live Services account at the <a href="//lx.azure.microsoft.com/" target="_blank">Azure Services Developer Portal</a>.</p>
<p>It&#8217;s quite a hassle and you&#8217;ll have to wait for about a week for all the invitation codes to be sent. Last but not least you&#8217;ll need to get access to the <a href="https://developer.mesh-ctp.com/" target="_blank">developer version of Live Mesh</a>. Be aware, this version is different from the <a href="//www.mesh.com" target="_blank">consumer version</a> of Live Mesh! Both operate in their own sandbox. If you wish to install them side by side, please consult this <a href="http://social.msdn.microsoft.com/Forums/en-US/liveframework/thread/2fa9d3f1-029e-44af-9568-1cea81ca78a9" target="_blank">forum post</a>.</p>
<p>The required software (SDK &amp; Tools) and documentation for programming against the Live Framework Mesh can be downloaded <a href="https://developer.mesh-ctp.com/developers/developers.aspx" target="_blank">here</a>.</p>
<p>You can recognize the Developer Live Mesh client by this icon in the system tray.</p>
<p><strong>Figure 1</strong> &#8211; Live Mesh Developer Client System Tray Icon<br />
<img class="aligncenter size-full wp-image-614" title="Mesh Developer Systemtray Icon" src="http://cgeers.files.wordpress.com/2009/04/mesh-systray-icon.jpg?w=16&#038;h=16" alt="Mesh Developer Systemtray Icon" width="16" height="16" /></p>
<p>After all accounts have been created and the SDK has been setup you&#8217;re finally ready to go&#8230;</p>
<p><strong>Note</strong>: To setup these accounts you&#8217;ll need to use your Windows Live Id.</p>
<p><a href="http://mtaulty.com/communityserver/blogs/mike_taultys_blog/default.aspx" target="_blank">Mike Tautly</a> has put up a nice screencast on how to get started with Live Mesh, <a href="http://channel9.msdn.com/posts/mtaulty/Live-Framework-SDK-Getting-Started/" target="_blank">check it out here</a>.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="resourcemodel" name="resourcemodel"></a><strong>Live Framework Resource Model</strong></p>
<p>Before proceeding further a bit of information on the storage hierarchy of Mesh is advisable. The Live Framework encapsulates more than just Mesh as you can see in the following image.</p>
<p><strong>Figure 2</strong> &#8211; Live Framework Resource Model</p>
<p><a href="http://cgeers.files.wordpress.com/2009/04/resource-model.jpg"><img src="http://cgeers.files.wordpress.com/2009/04/resource-model.jpg?w=300&#038;h=188" alt="Live Framework Resource odel" title="Live Framework Resource odel" width="300" height="188" class="aligncenter size-medium wp-image-636" /></a></p>
<p>Let&#8217;s focus solely on Mesh. Using a bottom-up approach the first item of interest is the data entry object. A data entry is the actual data stored in your Mesh, it can be a picture, a pdf, zip archive&#8230;etc. You are not confined to only storing files. You can, for example, also store objects as data entries.</p>
<p>Moving up one level you can see that a collection of data entries is maintained by a data feed, which in its turn is part of a mesh object. A data feed is usually a collection of data entries of the same type. So a data feed might be a collection of data entries which all represent pictures. I say usually, because it is really up to you to determine what you want to store in the data entries.</p>
<p>A mesh object (MeshObject class) describes the object that you want to share. There is one MeshObject for each object (e.g. folder) that you want to synchronize between your devices. Each MeshObject can have one or more data feeds and each data feed can have one or more data entries. </p>
<p>Just like with the data entries you determine how many data feeds a MeshObject contains and what kind of collections (data entries) these feeds contain. So a MeshObject describes an object that you wish to share and synchronize between your devices. It defines what to share and amongst which devices, a.k.a. the mapping.</p>
<p>To recap, for synchronizing folders and files, Mesh adds a single MeshObject for each Live Mesh folder. Each MeshObject has one data feed which contains a collection of data entries. The data entries are the actual files stored in the folder.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="liveframework" name="liveframework"></a><strong>Connecting To The Live Services</strong></p>
<p>The source code accompagnying this article aims at demonstrating how to establish a connection with the Live Services, querying and creating resources (directories) and uploading / downloading a file.</p>
<p><strong>Note</strong>: The purpose of the source code is to show how to operate with Live Mesh through the Live Framework API, not on how to write robust code. So exception handling and such is skipped. Feel free to add your own.</p>
<p>Well, for starters let&#8217;s begin with the initial task of establishing a connection. Connecting to the Live Services is as easy as following these steps:</p>
<ol>
<li>Start up Visual Studio 2008 (be sure to check if you have <a href="http://msdn.microsoft.com/en-us/vstudio/cc533448.aspx" target="_blank">SP1</a> installed)</li>
<li>Create a new blank solution called &#8220;LiveMesh&#8221; and add a console project aptly named ConsoleApplication</li>
<li>Add references to the following Dll assemblies which are part of the Live Framework SDK:Microsoft.LiveFX.Client.dll, Microsoft.LiveFX.ResourceModel.dll and Microsoft.Web.dll.If you used the default installation location they should be located in the following directory: &#8220;C:\Program Files\Microsoft SDKs\Live Framework\v0.91\API Toolkits\.Net Library&#8221;</li>
<li>Add a new class called LiveMesh to the project. Listing 1 lists the code for this class.</li>
</ol>
<p><strong>Listing 1</strong> &#8211; LiveOperatingEnvironment class (LOE)</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre><span class="kwrd">public</span> <span class="kwrd">class</span> LiveMesh
{
  <span class="preproc">#region</span> Fields

  <span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">string</span> serverUri = <span class="str">"https://user-ctp.windows.net"</span>;
  <span class="kwrd">private</span> <span class="kwrd">readonly</span> LiveOperatingEnvironment environment = <span class="kwrd">new</span> LiveOperatingEnvironment();

  <span class="preproc">#endregion</span>

  <span class="preproc">#region</span> Constructor(s)

  <span class="kwrd">public</span> LiveMesh(<span class="kwrd">string</span> userName, <span class="kwrd">string</span> password)
  {
      UserName = userName;
      Password = password;
  }

  <span class="preproc">#endregion</span>

  <span class="preproc">#region</span> Properties

  <span class="kwrd">public</span> <span class="kwrd">string</span> UserName { get; set; }
  <span class="kwrd">public</span> <span class="kwrd">string</span> Password { get; set; }

  <span class="preproc">#endregion</span>

  <span class="preproc">#region</span> Methods

  <span class="kwrd">public</span> <span class="kwrd">bool</span> Connect()
  {
      <span class="rem">// Using the LiveItemAccessOptions class you can specify if you want to auto-load</span>
      <span class="rem">// relations and if you wish to receive notifications.</span>
      LiveItemAccessOptions options = <span class="kwrd">new</span> LiveItemAccessOptions(<span class="kwrd">true</span>);

      <span class="rem">// Create a user token. You  need to pass a token based on your Windows Live Id</span>
      <span class="rem">// to the LOE object's connect method. The GetWindowsLiveAuthenticationToken() is</span>
      <span class="rem">// an extension method which resides in the Microsoft.LiveFX.ResourceModel namespace.</span>
      <span class="kwrd">string</span> credential = <span class="kwrd">new</span> NetworkCredential(UserName, Password, serverUri).GetWindowsLiveAuthenticationToken();

      <span class="rem">// Connect and retrieve the Mesh object</span>
      environment.Connect(credential, AuthenticationTokenType.UserToken, <span class="kwrd">new</span> Uri(serverUri), options);

      <span class="rem">// When connected the Mesh property of the LOE object will be set.</span>
      <span class="kwrd">return</span> environment.Mesh != <span class="kwrd">null</span>;
  }

  <span class="preproc">#endregion</span>
}</pre>
</div>
<p>This class has a constructor which takes two strings, namely the username and password of your Windows Live Id. The variable serverUri contains the address of the Live Framework server to which you need to connect.</p>
<p>Everything in this class (which will be expanded in the rest of this text) pretty much revolves around the LiveOperatingEnvironment (LOE) class, it is the main entry point into the Live Framework.</p>
<p>The LiveMesh class&#8217;s Connect method in turn calls the LOE class&#8217; Connect method which takes a user token, the server Uri and some options. Read the comments in the code segment above for more information on how these parameters are configured.</p>
<p>Let&#8217;s quickly test the LiveMesh class. The code in Listing 2 doesn&#8217;t need any further explanation.</p>
<p><strong>Listing 2</strong>- Connecting to your Mesh</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre><span class="kwrd">using</span> System;

<span class="kwrd">namespace</span> ConsoleApplication
{
    <span class="kwrd">class</span> Program
    {
        <span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">string</span> userName = <span class="str">"xxxxx@xxxxx.com"</span>;
        <span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">string</span> password = <span class="str">"xxxxx"</span>;

        <span class="kwrd">static</span> <span class="kwrd">void</span> Main(<span class="kwrd">string</span>[] args)
        {
            LiveMesh myMesh = <span class="kwrd">new</span> LiveMesh(userName, password);

            <span class="kwrd">bool</span> connected = myMesh.Connect();
            <span class="kwrd">if</span> (connected)
            {
                Console.WriteLine(<span class="str">"Connected"</span>);
            }
            <span class="kwrd">else</span>
            {
                Console.WriteLine(<span class="str">"Could not establish connection"</span>);
            }

            Console.ReadLine();
        }
    }
}</pre>
</div>
<p><strong>Note</strong>: Don&#8217;t forget to replace the userName and password values with your own.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="meshobjects" name="meshobjects"></a><strong>Listing Mesh Objects</strong></p>
<p>To list the objects present in your Mesh a simple Linq query suffices. Add the following method to your LiveMesh class.</p>
<p><strong>Listing 3</strong> &#8211; GetMeshObjects() method</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> LiveMesh
{
    <span class="rem">// ...</span>

    <span class="preproc">#region</span> Methods

    <span class="kwrd">public</span> IEnumerable&lt;MeshObject&gt; GetMeshObjects()
    {
        <span class="kwrd">return</span> from o <span class="kwrd">in</span> environment.Mesh.CreateQuery&lt;MeshObject&gt;().Execute()
               select o;
    }

    <span class="preproc">#endregion</span>

    <span class="rem">// ...</span>
}</pre>
</div>
<p>As you can see the Linq query follows the pattern shown in figure 2, the Live Framework Resource Model. The Mesh property of the LiveOperatingEnvironment instance is queried and all the Mesh objects are returned (Service Endpoint -&gt; Mesh -&gt; Mesh Objects). Now let&#8217;s foreach this collection and take a look at the results.</p>
<p><strong>Listing 4</strong> &#8211; Foreaching the Mesh objects</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="rem">// List the MeshObjects in your Mesh</span>
IEnumerable&lt;MeshObject&gt; meshObjects = myMesh.GetMeshObjects();
<span class="kwrd">foreach</span>(var meshObject <span class="kwrd">in</span> meshObjects)
{
    Console.WriteLine(meshObject.Resource.Title);
}</pre>
</div>
<p>The output:</p>
<p><strong>Figure 3</strong> &#8211; My Mesh Objects</p>
<p><a href="http://cgeers.files.wordpress.com/2009/04/my-mesh-objects.jpg"><img src="http://cgeers.files.wordpress.com/2009/04/my-mesh-objects.jpg?w=462&#038;h=189" alt="My Mesh Objects" title="My Mesh Objects" width="462" height="189" class="aligncenter size-full wp-image-649" /></a></p>
<p>The folders &#8220;Pictures&#8221; and &#8220;Blog&#8221; were two folders I created using the Live Mesh Developer version website (Live Desktop). Feel free to create your own folders using the site and check if they show up in the query results.</p>
<p>There are two ways to query Mesh. You could also rewrite the query shown in Listing 3 as such:</p>
<p><strong>Listing 5</strong> &#8211; CreateQuery&lt;T&gt; Versus Entries</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">return</span> from o <span class="kwrd">in</span> environment.Mesh.MeshObjects.Entries select o;</pre>
</div>
<p>What&#8217;s the difference? CreateQuery&lt;T&gt; executes server side while using the Entries collection will be executed client-side. The latter case will result in more objects being sent over the wire. For a more in-depth explanation check out this <a href="http://blogs.msdn.com/benwilli/archive/2009/03/09/linqing-to-the-live-framework.aspx" target="_blank">excellent blog post</a>.</p>
<p><strong>Note</strong>: If you only want to return Mesh objects which are folders, then add this where clause: <u>where o.Resource.Type == &#8220;LiveMeshFolder&#8221;</u>.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="resources" name="resources"></a><strong>Mesh Object Resources</strong></p>
<p>Now that you know how to obtain your Mesh objects, let&#8217;s retrieve the resources (data entries) of such a Mesh object. In order words let&#8217;s list the files of a Live Mesh folder.</p>
<p>Add the method shown in Listing 6 to your LiveMesh class.</p>
<p><strong>Listing 6</strong> &#8211; GetFilesOfFolder() method</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> IEnumerable&lt;DataEntry&gt; GetFilesOfFolder(MeshObject meshObject)
{
    <span class="rem">// Obtain the data feed. </span>
    <span class="rem">// A Mesh Object representing a folder only has one data feed.</span>
    <span class="rem">// It's title is LiveMeshFiles.</span>
    DataFeed feed = (from f <span class="kwrd">in</span> meshObject.CreateQuery&lt;DataFeed&gt;().Execute()
                     <span class="kwrd">where</span> f.Resource.Title == <span class="str">"LiveMeshFiles"</span>
                     select f).First();
    <span class="kwrd">if</span> (feed == <span class="kwrd">null</span>)
    {
        <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(<span class="str">"MeshObject does not have any data feeds"</span>);
    }
    <span class="kwrd">return</span> from e <span class="kwrd">in</span> feed.CreateQuery&lt;DataEntry&gt;().Execute() select e;
}</pre>
</div>
<p>Let&#8217;s update the foreach loop in the Main method.</p>
<p><strong>Listing 7</strong> &#8211; Updated Main method</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="rem">// ...</span>

<span class="rem">// List the MeshObjects in your Mesh</span>
IEnumerable&lt;MeshObject&gt; meshObjects = myMesh.GetMeshObjects();
<span class="kwrd">foreach</span>(var meshObject <span class="kwrd">in</span> meshObjects)
{
    Console.WriteLine(meshObject.Resource.Title);
    Console.WriteLine();

    IEnumerable&lt;DataEntry&gt; files = myMesh.GetFilesOfFolder(meshObject);
    <span class="kwrd">foreach</span>(var file <span class="kwrd">in</span> files)
    {
        Console.WriteLine(String.Format(<span class="str">"\t{0}"</span>, file.Resource.Title));
    }
    Console.WriteLine();
}

<span class="rem">// ...</span>
</pre>
</div>
<p><strong>Figure 4</strong> &#8211; Mesh Object Resources (files)</p>
<p><a href="http://cgeers.files.wordpress.com/2009/04/mesh-object-resources1.jpg"><img src="http://cgeers.files.wordpress.com/2009/04/mesh-object-resources1.jpg?w=388&#038;h=285" alt="Mesh Object Resources" title="Mesh Object Resources" width="388" height="285" class="aligncenter size-full wp-image-663" /></a></p>
<p>Just place some files in your Mesh folders using the Live Desktop to test this code.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="createdirectory" name="createdirectory"></a><strong>Creating A Directory</strong></p>
<p>Great, you can now query your Mesh objects and their resources. But how about actually creating a folder without resorting to the Live Desktop?</p>
<p>Again, a short and simple amount of code is all you need. Add the following two methods to your LiveMesh class.</p>
<p><strong>Listing 8</strong> &#8211; DirectoryExists() and CreateDirectory() methods</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">bool</span> DirectoryExists(<span class="kwrd">string</span> directory)
{
    var q = (from o <span class="kwrd">in</span> environment.Mesh.CreateQuery&lt;MeshObject&gt;().Execute()
             <span class="kwrd">where</span> o.Resource.Type == <span class="str">"LiveMeshFolder"</span> &amp;&amp; o.Resource.Title == directory
             select o).FirstOrDefault();
    <span class="kwrd">return</span> q != <span class="kwrd">null</span>;
}

<span class="kwrd">public</span> <span class="kwrd">void</span> CreateDirectory(<span class="kwrd">string</span> directory)
{
    <span class="rem">// Do not create the directory if it already exists</span>
    <span class="kwrd">if</span> (DirectoryExists(directory))
    {
        <span class="kwrd">return</span>;
    }

    <span class="rem">// Create a new Mesh object and set its type</span>
    MeshObject newDirectory = <span class="kwrd">new</span> MeshObject(directory) {Resource = {Type = <span class="str">"LiveMeshFolder"</span>}};

    <span class="rem">// Add the new object to your Mesh</span>
    environment.Mesh.MeshObjects.Add(<span class="kwrd">ref</span> newDirectory);

    <span class="rem">// Create a data feed, set its type and handler</span>
    DataFeed feed =
        <span class="kwrd">new</span> DataFeed(<span class="str">"LiveMeshFiles"</span>)
        { Resource = { Type = <span class="str">"LiveMeshFiles"</span>, HandlerType = <span class="str">"FileSystem"</span> } };

    <span class="rem">// Add the data feed to the new Mesh object</span>
    newDirectory.DataFeeds.Add(<span class="kwrd">ref</span> feed);
}</pre>
</div>
<p>The method DirectoryExists() checks if a folder already exists within Mesh, the second method CreateDirectory() creates a new folder and adds a data feed to it.</p>
<p><strong>Note</strong>: The code contains some hardcoded strings such as LiveMeshFolder, LiveMeshFiles, FileSystem&#8230;etc. Feel free to improve on the design (make them constants for example), but these strings are needed if you want to retrieve / create the correct Mesh objects. Mesh allows you to store more than just folders and files.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="addfile" name="addfile"></a><strong>Adding A File</strong></p>
<p>To enable your LiveMesh class to add files to a folder add the methods shown in Listing 9 to the class.</p>
<ul>
<li><strong>FindDirectory()</strong>: This method checks if a given directory exists in your Mesh and returns the MeshObject if found.</li>
<li><strong>GetMimeType()</strong>: Determines the mime type of a file.</li>
<li><strong>AddFileToDirectory()</strong>: Retrieves the MeshObject for a Live Mesh folder, loads its data feed and adds a new file to the feed&#8217;s data entries.</li>
</ul>
<p><strong>Listing 9</strong> &#8211; Adding A File</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> MeshObject FindDirectory(<span class="kwrd">string</span> directory)
{
    <span class="kwrd">return</span> (from o <span class="kwrd">in</span> environment.Mesh.CreateQuery&lt;MeshObject&gt;().Execute()
            <span class="kwrd">where</span> o.Resource.Type == <span class="str">"LiveMeshFolder"</span> &amp;&amp;
                  o.Resource.Title == directory
            select o).FirstOrDefault();
}

<span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">string</span> GetMimeType(<span class="kwrd">string</span> path)
{
    <span class="kwrd">string</span> mimeType = <span class="str">"application/unknown"</span>;
    <span class="kwrd">string</span> ext = Path.GetExtension(path).ToLower();
    Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
    <span class="kwrd">if</span> (regKey != <span class="kwrd">null</span> &amp;&amp; regKey.GetValue(<span class="str">"Content Type"</span>) != <span class="kwrd">null</span>)
    {
        mimeType = regKey.GetValue(<span class="str">"Content Type"</span>).ToString();
    }
    <span class="kwrd">return</span> mimeType;
}

<span class="kwrd">public</span> <span class="kwrd">void</span> AddFileToDirectory(<span class="kwrd">string</span> directory, <span class="kwrd">string</span> path)
{
    MeshObject meshObject = FindDirectory(directory);
    <span class="kwrd">if</span> (meshObject == <span class="kwrd">null</span>)
    {
        <span class="kwrd">return</span>;
    }
    DataFeed feed = (from f <span class="kwrd">in</span> meshObject.CreateQuery&lt;DataFeed&gt;().Execute()
                     <span class="kwrd">where</span> f.Resource.Type == <span class="str">"LiveMeshFiles"</span>
                     select f).First();
    Stream fileStream = File.Open(path, FileMode.Open, FileAccess.Read);
    feed.DataEntries.Add(fileStream, path, GetMimeType(path));
    <span class="rem">// Make sure all devices will get synchronized.</span>
    feed.SyncEntries.Synchronize();
    feed.Update();
}</pre>
</div>
<p>You can now add a file to a Live Mesh folder by calling the AddFileToFolder(directory, path) and the file will be uploaded to your Mesh. Check the Online Desktop to verify that it has been uploaded.</p>
<p><strong>Listing 10</strong> &#8211; Uploading About.txt</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="rem">// ...</span>
myMesh.AddFileToDirectory(<span class="str">"My new folder"</span>, <span class="str">"About.txt"</span>);
<span class="rem">// ...</span>
</pre>
</div>
<p><a href="#top">Top of page</a></p>
<p><a title="retrievefile" name="retrievefile"></a><strong>Retrieving A File</strong></p>
<p>We&#8217;re almost there. The only thing that remains to be done is to retrieve a file from Mesh. The GetFileByFilename() method shown in Listing 11 allows you to do just that.</p>
<p>It queries all the Mesh objects and returns the first data entry whose resource title matches the given filename.</p>
<p><strong>Listing 11</strong> &#8211; GetFileByFilename() method</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> DataEntry GetFileByFilename(<span class="kwrd">string</span> filename)
{
    IEnumerable&lt;MeshObject&gt; meshObjects = GetMeshObjects();
    <span class="kwrd">foreach</span>(var meshObject <span class="kwrd">in</span> meshObjects)
    {
        DataFeed feed = (from f <span class="kwrd">in</span> meshObject.CreateQuery&lt;DataFeed&gt;().Execute()
                         <span class="kwrd">where</span> f.Resource.Type == <span class="str">"LiveMeshFiles"</span>
                         select f).First();
        <span class="kwrd">if</span> (feed != <span class="kwrd">null</span>)
        {
            DataEntry dataEntry = (from e <span class="kwrd">in</span> feed.CreateQuery&lt;DataEntry&gt;().Execute()
                                   <span class="kwrd">where</span> e.Resource.Title == filename
                                   select e).FirstOrDefault();
            <span class="kwrd">if</span> (dataEntry != <span class="kwrd">null</span>)
            {
                <span class="kwrd">return</span> dataEntry;
            }
        }
    }
    <span class="kwrd">return</span> <span class="kwrd">null</span>;
}</pre>
</div>
<p>For example let&#8217;s search for the text file About.txt which we added in the previous section.</p>
<p><strong>Listing 12</strong> &#8211; Retrieving a file</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="rem">// Retrieve a file</span>
DataEntry dataEntry = myMesh.GetFileByFilename(<span class="str">"About.txt"</span>);
<span class="kwrd">if</span> (dataEntry != <span class="kwrd">null</span>)
{
    MemoryStream stream = <span class="kwrd">new</span> MemoryStream();
    dataEntry.ReadMediaResource(stream);
    stream.Seek(0, SeekOrigin.Begin);
    StreamReader reader = <span class="kwrd">new</span> StreamReader(stream);
    Console.WriteLine(reader.ReadToEnd());
}</pre>
</div>
<p>Once the DataEntry has been found you can call its ReadMediaResource() method to obtain a stream. The rest of the code reads the stream and writes the contents to the console.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="summary" name="summary"></a><strong>Summary</strong></p>
<p>I hope you enjoyed this brief introduction to Live Mesh and the Live Framework. Let&#8217;s recap what we&#8217;ve covered from a developer&#8217;s point of view:</p>
<ul>
<li>Connecting to the Live Operating Environment (Live Services)</li>
<li>Listing resources (directories)</li>
<li>Add (uploading) files to Mesh</li>
<li>Retrieving (downloading) files from Mesh</li>
</ul>
<p>Any comments, questions, tips&#8230;etc. are always appreciated.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="download" name="download"></a><strong>Download</strong></p>
<p>You can find the source code for this article on the <a href="http://cgeers.wordpress.com/download/" target="_blank">Download page</a> of this blog.</p>
<p><a href="#top">Top of page</a></p>
Posted in C#, Live Framework, Programming  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/590/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/590/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cgeers.wordpress.com/590/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cgeers.wordpress.com/590/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cgeers.wordpress.com/590/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cgeers.wordpress.com/590/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cgeers.wordpress.com/590/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cgeers.wordpress.com/590/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cgeers.wordpress.com/590/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cgeers.wordpress.com/590/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.wordpress.com&blog=2504479&post=590&subd=cgeers&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://cgeers.wordpress.com/2009/04/19/live-mesh-programming-against-the-live-framework/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1deb97b690d087dea7942250d7b03310?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/04/livemesh.png" medium="image">
			<media:title type="html">Live Mesh</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/04/mesh-systray-icon.jpg" medium="image">
			<media:title type="html">Mesh Developer Systemtray Icon</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/04/resource-model.jpg?w=300" medium="image">
			<media:title type="html">Live Framework Resource odel</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/04/my-mesh-objects.jpg" medium="image">
			<media:title type="html">My Mesh Objects</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/04/mesh-object-resources1.jpg" medium="image">
			<media:title type="html">Mesh Object Resources</media:title>
		</media:content>
	</item>
		<item>
		<title>Data Access Objects with the Entity Framework</title>
		<link>http://cgeers.wordpress.com/2009/03/14/data-access-objects-with-the-entity-framework/</link>
		<comments>http://cgeers.wordpress.com/2009/03/14/data-access-objects-with-the-entity-framework/#comments</comments>
		<pubDate>Sat, 14 Mar 2009 19:10:33 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[dao]]></category>
		<category><![CDATA[data access object]]></category>

		<guid isPermaLink="false">http://cgeers.wordpress.com/?p=478</guid>
		<description><![CDATA[Introduction
For this article / tutorial I will demonstrate a quick and easy way on how to use data access objects (DAO&#8217;s) with the Entity Framework. 
These data access objects form a layer between the business logic and the database access technology. The idea is that the business logic should remain ignorant of the technology used [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.wordpress.com&blog=2504479&post=478&subd=cgeers&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a title="introduction" name="introduction"></a><strong>Introduction</strong><img src="http://cgeers.files.wordpress.com/2009/03/database-access1.jpg?w=80&#038;h=80" alt="database-access1" title="database-access1" width="80" height="80" class="alignright size-full wp-image-482" /></p>
<p>For this article / tutorial I will demonstrate a quick and easy way on how to use data access objects (DAO&#8217;s) with the Entity Framework. </p>
<p>These data access objects form a layer between the business logic and the database access technology. The idea is that the business logic should remain ignorant of the technology used to access the database. Using this &#8220;DAO pattern&#8221; you can more easily interchange this backing technology.</p>
<p>In the text to come this will be demonstrated by setting up a simple domain model which will be modelled using the Entity Framework. Next a layer of DAO&#8217;s will be created on top of this domain model.  </p>
<p>The business logic will only use these DAO&#8217;s to request or send back data from or to the underlying data store. How these CRUD operations are handled is entirely up to the implementation of the DAO&#8217;s and should be of no concert to the business logic.</p>
<p>By decoupling the business objects from the backing data store you can more easily switch to another database access technology such as for say Linq To Sql.</p>
<p><span id="more-478"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#parts">The Various Parts</a></li>
<li><a href="#domainmodel">Domain Model</a></li>
<li><a href="#database">The Database</a></li>
<li><a href="#modelling">Modelling The Domain</a></li>
<li><a href="#daointerfaces">DAO Interfaces</a></li>
<li><a href="#daoimplementation">DAO Implementation</a></li>
<li><a href="#businesslogic">Business Logic</a></li>
<li><a href="#quickdemo">A Quick Demo</a></li>
<li><a href="#summary">Summary</a></li>
<li><a href="#download">Download</a></li>
</ul>
<p><a title="parts" name="parts"></a><strong>The Various Parts</strong></p>
<p>Let&#8217;s quickly iterate the various parts of the architecture we&#8217;re trying to achieve by illustrating them.</p>
<p><strong>Figure 1</strong> &#8211; The Various Parts</p>
<p><a href="http://cgeers.files.wordpress.com/2009/03/thevariousparts.jpg"><img src="http://cgeers.files.wordpress.com/2009/03/thevariousparts.jpg?w=400&#038;h=260" alt="The Various Parts" title="The Various Parts" width="400" height="260" class="aligncenter size-full wp-image-504" /></a></p>
<ol>
<li><strong>Data Store</strong>: The underlying data store for this article is, as usual, Microsoft SQL Server 2005 Express.</li>
<li><strong>Domain</strong>: The domain will  be modelled by the Entity Framework upon the tables found in the database.</li>
<li><strong>Data Access Objects (DAO&#8217;s)</strong>: The DAO&#8217;s are responsible for communicating with the domain in order to retrieve and pass data from and back to the underlying data store.</li>
<li><strong>Business Logic</strong>: The domain-specific logic that makes the application actually do stuff will be handled in the business logic or &#8220;Manager&#8221; layer. This layer consists out of manager class types who&#8217;s sole responsability is to handle the coordination of work. It uses DAO&#8217;s to retrieve and manipulate data. The actual CRUD operations are handled by the DAO&#8217;s. This layer should remain ignorant about how this is actually implemented.</li>
</ol>
<p><strong>Remark</strong>: As you may have noticed I skipped the fifth part shown in figure 1. Normally you should create a separate Data Transfer Object (DTO) for each of the objects found in your domain. These DTO&#8217;s should only carry data and should not contain any logic so that they can be easily serialized and deserialized, they are meant to only transfer data between two points. In this case the DAO&#8217;s and the business logic layer. </p>
<p>For this article I&#8217;ve choosen to use the domain objects generated by the Entity Framework as DTO&#8217;s. Although this has the disadvantage of establishing a coupling between the Entity Framework and the business logic layer (a reference to System.Data.Entity is required). </p>
<p>Use them strictly as DTO&#8217;s and don&#8217;t call any Entity Framework specific methods on them in the business logic layer or any other layer except in the layer that houses the DAO&#8217;s. In order words keep the coupling at the absolute minimum. Depending on the scope of the project this is acceptable in my humble opinion.</p>
<p>I hope version 2 of the Entity Framework offers better support for DTO/POCO objects. The IPOCO pattern they have chosen to follow for this first release makes this scenario not impossible but certainly tedious to achieve. </p>
<p><a href="#top">Top of page</a></p>
<p><a title="domainmodel" name="domainmodel"></a><strong>Domain Model</strong></p>
<p>Let&#8217;s quickly establish a small and simple domain model. Let&#8217;s ponder the following class diagram&#8230;</p>
<p><strong>Figure 2</strong> &#8211; Simple domain model<br />
<a href="http://cgeers.files.wordpress.com/2009/03/classdiagram1.jpg"><img src="http://cgeers.files.wordpress.com/2009/03/classdiagram1.jpg?w=480&#038;h=362" alt="Class Diagram" title="Class Diagram" width="480" height="362" class="aligncenter size-full wp-image-491" /></a></p>
<p>The above figure gives you an overview of a simple domain model. As you can see all domain objects are descendant from the BaseClass type. </p>
<p>The left branch of the class diagram displays an abstract class type Person which has two properties called FirstName and Name. Two concrete classes, namely Developer and Analyst in turn derive from this type and add a property specific to themselves.</p>
<p>The Developer class has a property named PreferedLanguage containing the developer&#8217;s programming language of choice and the Analyst type contains the methodology he likes to use to manage his projects.</p>
<p>On the right branch two types are located. An abstract class type titled Task which has a Name project to identify the task and a concrete implementation of this abstract type called Project which adds a Deadline property to signal when the project should be completed.</p>
<p>This domain model represents a collection of developers and analysts and the projects they are working on. Now we need to map this logical model to external data. In other words these objects need to be mapped to tables in a database.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="database" name="database"></a><strong>The Database</strong></p>
<p>To model the domain I&#8217;ve opted for the bottom-up approach. We start at the bottom by creating our database and then generate a domain/object model using the Entity Framework based on the previously created database. The other way around (Top-down approach) is certainly feasible, but in this case it isn&#8217;t the fastest approach.</p>
<p>Start by creating a new database named &#8220;Projects&#8221; by using SQL Server Management Studio Express (or any other tool). Only three tables are required, figures 3, 4 &amp; 5 show you the structure of these tables.</p>
<p><strong>Figure 3</strong> &#8211; Person table<br />
<img src="http://cgeers.files.wordpress.com/2009/03/the-person-table.jpg?w=332&#038;h=120" alt="Person Table" title="Person Table" width="332" height="120" class="alignnone size-full wp-image-523" /></p>
<p>The Developer and Analyst domain objects both map to the Person table. For the left branch depicted in the domain model (figure 2) I&#8217;ve gone for <a href="http://msdn.microsoft.com/en-us/library/bb738443.aspx" target="_blank">the table-per-hierarchy storage model</a>. </p>
<p>A developer and analyst are represented by different types in the domain model but derive from the same base type. However in the data store their data is stored in the same table, all that is required is a descriminator column. </p>
<p>The descriminator column in this case is called PersonType (int) and if it is equal to one the person is a developer or if equal to two an analyst.</p>
<p><strong>Figure 4</strong> &#8211; Project table<br />
<img src="http://cgeers.files.wordpress.com/2009/03/project-table.jpg?w=339&#038;h=79" alt="Project Table" title="Project Table" width="339" height="79" class="alignnone size-full wp-image-518" /></p>
<p>For the right branch only one table is needed. As you can see it is quite simple and has all the columns needed to represent the properties of the Project domain object. </p>
<p>If you were to create more descendants of the abstract Task type this table would also need a descriminator column if you were to opt for the table-per-hierarchy approach. </p>
<p><strong>Figure 5</strong> &#8211; ProjectsPerPerson table<br />
<img src="http://cgeers.files.wordpress.com/2009/03/projectsperperson-table.jpg?w=338&#038;h=59" alt="ProjectsPerPerson TAble" title="ProjectsPerPerson Table" width="338" height="59" class="alignnone size-full wp-image-519" /></p>
<p>The last table ProjectsPerPerson links persons (developers and analysts) to zero or multiple projects. Although this relation is not directly obvious by looking at figure 2 a person can have zero or multiple projects and a project can be worked upon by zero or multiple persons.</p>
<p><strong>Remark</strong>: The source code accompagnying this article contains an Sql script containing the necessary DDL statements so that you can quickly setup this database.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="modelling" name="modelling"></a><strong>Modelling The Domain</strong></p>
<p>Now that the database has been setup let&#8217;s proceed to model the domain or object model.</p>
<p>Fire up Visual Studio, create a new blank solution called &#8220;EntityFrameworkDao&#8221; and add a new class library titled &#8220;Domain&#8221;. Delete the automatically generated file Class1.cs and add a new ADO.NET Entity Data Model. Call it &#8220;Domain.edmx&#8221;. </p>
<p>When the Entity Data Model wizard pops up choose to generate the model from the database, but only add the Person table to begin with. You should end up with a model containing only one entity, namely Person. </p>
<p>You now have to manually break up this entity into three separate entities being Person, Developer and Analyst. <a href="http://channel9.msdn.com/posts/RobBagby/deCast-Entity-Framework-Modeling-Implementing-Table-Per-Hierarchy/" target="_blank">Instead of explaining this step-by-step I suggest you take a look the following screencast by Rob Bagby</a>. He does an excellent job at explaining it (<a href="http://blogs.msdn.com/bags/" target="_blank">Also take a look at his blog</a>).</p>
<p>When that is done update the model from the database and add the Project table. Since this table does not contain a descriminator column there is no need to break it up into other entities. </p>
<p>Last but not least add the ProjectsPerPerson table to the model. This will not result in a new entity being added but will insert a many-to-many relationship between the Person and Project entities.</p>
<p>Be sure to rename the entity sets and navigation properties to something more meaningful. You should end up with an entity data model resembling the following screenshot.</p>
<p><strong>Figure 6</strong> &#8211; The Entity Data Model<br />
<a href="http://cgeers.files.wordpress.com/2009/03/entity-data-model.jpg"><img src="http://cgeers.files.wordpress.com/2009/03/entity-data-model.jpg?w=480&#038;h=301" alt="Entity Data Model" title="Entity Data Model" width="480" height="301" class="aligncenter size-full wp-image-538" /></a></p>
<p>You could go as far as to have the Person and Project type share a common base type as shown in figure 2, but I&#8217;ve chosen not to do this as it would disable me from setting a different entity set name on those entities.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="daointerfaces" name="daointerfaces"></a><strong>DAO Interfaces</strong></p>
<p>If you recall figure 1 which lists the various parts required to setup our architecture we have now arrived at the third part, namely the nitty-gritty of this article being the Data Access Objects (DAO&#8217;s). The business logic layer will only obtain DTO&#8217;s or domain objects in this case through the use of DAO objects, it will not directly query the Entity Data Model.</p>
<p>To further decouple the business logic layer from the Entity Framework we will only program against interfaces which the DAO objects will implement. This way you can provide an implementation of the DAO interfaces that target the Entity Framework, another one that targets Linq To Sql&#8230;and so on. Since the business logic layer only programs against the DAO interfaces it does not care about the actual implementation.</p>
<p><strong>Remark</strong>: Of course this will work optimally if we don&#8217;t return domain objects to the business logic layer but DTO&#8217;s as previously mentioned. Since we&#8217;ve choosen to directly return domain objects our implementation still has a coupling to the Entity Framework. </p>
<p>But as said I find it acceptable if you threat these domain objects strictly as DTO&#8217;s in the business logic layer. This keeps the coupling as minimal as possible so you don&#8217;t have too much work should you ever need to replace the Entity Framework. </p>
<p>Should you &#8220;convert&#8221; these domain objects to DTO&#8217;s the business logic layer and any other layer on top of that (e.g. Presentation Layer) are not affected at all if you change the implementation of the DAO&#8217;s.</p>
<p>Let&#8217;s move on to the interfaces. Add a new code library named &#8220;Contracts&#8221; to the solution. </p>
<p>First we declare an all general purpose interface called IDao from which all the other DAO interfaces will descend. It declares three methods. Save(&#8230;) for adding / updating an entity, Delete(&#8230;) for deleting an entity and SaveChanges() to persist the changes.</p>
<p><strong>Listing 1</strong> &#8211; IDao Interface</p>
<div class="csharpcode">
<pre>
<span class="kwrd">public</span> <span class="kwrd">interface</span> IDao&lt;TEntity&gt;
{
    TEntity Save(TEntity entity);
    <span class="kwrd">void</span> Delete(TEntity entity);
    <span class="kwrd">void</span> SaveChanges();
}</pre>
</div>
<p>Listing 2 lists the other Dao interfaces found in the Contracts code library. As you can see the IDeveloperDao, IAnalystDao and IProjectDao interfaces each declare one method that needs to be implemented.</p>
<p><strong>Listing 2</strong> &#8211; Dao Interfaces</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">interface</span> IPersonDao : IDao&lt;Person&gt;
{ }

<span class="kwrd">public</span> <span class="kwrd">interface</span> IDeveloperDao : IPersonDao
{
    IEnumerable&lt;Developer&gt; GetDevelopers();
}

<span class="kwrd">public</span> <span class="kwrd">interface</span> IAnalystDao : IPersonDao
{
    IEnumerable&lt;Analyst&gt; GetAnalysts();
}

<span class="kwrd">public</span> <span class="kwrd">interface</span> IProjectDao : IDao&lt;Project&gt;
{
    IEnumerable&lt;Project&gt; GetProjectsOfPerson(Person person);
}</pre>
</div>
<p>Finally we also want to relieve the business logic layer from having to instantiate the DAO&#8217;s directly. To achieve this a factory will be used which needs to implement the following IDaoFactory interface.</p>
<p><strong>Listing 3</strong> &#8211; IDaoFactory interface</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">interface</span> IDaoFactory
{
    IPersonDao GetPersonDao();
    IDeveloperDao GetDeveloperDao();
    IAnalystDao GetAnalystDao();
    IProjectDao GetProjectDao();
}</pre>
</div>
<p><a href="#top">Top of page</a></p>
<p><a title="daoimplementation" name="daoimplementation"></a><strong>DAO Implementation</strong></p>
<p>Before building an Entity Framework implementation of the DAO interfaces we first have to develop a helper class and an extension method for the ObjectContext type.</p>
<p><strong>Listing 4</strong> &#8211; ObjectContextManager class</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> ObjectContextManager
{
    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> ProjectsEntities context = <span class="kwrd">new</span> ProjectsEntities();
    <span class="kwrd">private</span> ObjectContextManager() { }
    <span class="kwrd">public</span> <span class="kwrd">static</span> ProjectsEntities Context { get { <span class="kwrd">return</span> context; } }
}</pre>
</div>
<p>Each DAO object will share the same ObjectContext in order to communicate with the Entity Data Model. The ObjectContextManager class provides a static Context property which will always return the same ObjectContext instance. Don&#8217;t fret too much about the implementation of the ObjectContextManager class, I kept it very short for illustrative purposes. Feel free to improve on this, e.g. by providing a more generic approach so that it can be reused for each ObjectContext type.</p>
<p><strong>Remark</strong>: Be careful in which type of application you use the ObjectContext as it is not thread safe. For more information on this topic have a look at my previous article <a href="http://cgeers.wordpress.com/2009/02/21/entity-framework-objectcontext/" target="_blank">Entity Framework ObjectContext</a>.</p>
<p><strong>Listing 5</strong> &#8211; ObjectContext GetEntitySetName() extension method</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> ObjectContextExtensions
{
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">string</span> GetEntitySetName(<span class="kwrd">this</span> ObjectContext context, <span class="kwrd">string</span> entityTypeName)
    {
        var container = context.MetadataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace);
        <span class="kwrd">string</span> entitySetName = (from meta <span class="kwrd">in</span> container.BaseEntitySets
                                <span class="kwrd">where</span> meta.ElementType.Name == entityTypeName
                                select meta.Name).FirstOrDefault();
        <span class="kwrd">return</span> entitySetName;
    }
}</pre>
</div>
<p>The GetEntitySetName(&#8230;) extension method of the ObjectContext type returns the entity set name of a given entity. You&#8217;ll see in a second how this is used. This extension method queries the Entity Framework&#8217;s metadata in order to retrieve the entity set name. <a href="http://scip.be/index.php?Page=ArticlesNET26&amp;Lang=NL" target="_blank">Have a look at Stefan Cruysberghs article to learn how to do this</a>.</p>
<p>Now that the ground work has been laid, let&#8217;s finish up. Most of the DAO&#8217;s will share the same code, so let&#8217;s encapsulate this in an abstract base class. Take a look at the EntityDao type in Listing 6.</p>
<p><strong>Listing 6</strong> &#8211; EntityDao type</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> EntityDao&lt;TEntity&gt; : IDao&lt;TEntity&gt; <span class="kwrd">where</span> TEntity : EntityObject, <span class="kwrd">new</span>()
{
    <span class="preproc">#region</span> Helper methods

    <span class="kwrd">protected</span> ProjectsEntities Context
    {
        get
        {
            <span class="kwrd">return</span> ObjectContextManager.Context;
        }
    }

    <span class="kwrd">private</span> <span class="kwrd">string</span> entitySetName;
    <span class="kwrd">protected</span> <span class="kwrd">string</span> EntitySetName
    {
        get
        {
            <span class="kwrd">if</span> (String.IsNullOrEmpty(entitySetName))
            {
                entitySetName = Context.GetEntitySetName(<span class="kwrd">typeof</span>(TEntity).Name);
            }
            <span class="kwrd">return</span> entitySetName;
        }
    }

    <span class="preproc">#endregion</span>

    <span class="preproc">#region</span> IDao&lt;TEntity&gt; Members

    <span class="kwrd">public</span> TEntity Save(TEntity entity)
    {
        Context.AddObject(EntitySetName, entity);
        SaveChanges();
        <span class="kwrd">return</span> entity;
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> Delete(TEntity entity)
    {
        Context.DeleteObject(entity);
        SaveChanges();
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> SaveChanges()
    {
        Context.SaveChanges();
    }

    <span class="preproc">#endregion</span>
}</pre>
</div>
<p>This makes implementing the DOA interfaces a piece of cake. </p>
<p><strong>Listing 7</strong> &#8211; DAO&#8217;s</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> PersonDao : EntityDao&lt;Person&gt;, IPersonDao
{ }

<span class="kwrd">public</span> <span class="kwrd">class</span> DeveloperDao : PersonDao, IDeveloperDao
{
    <span class="preproc">#region</span> IDeveloperDao Members

    <span class="kwrd">public</span> IEnumerable&lt;Developer&gt; GetDevelopers()
    {
        <span class="kwrd">return</span> Context.People.OfType&lt;Developer&gt;();
    }

    <span class="preproc">#endregion</span>
}

<span class="kwrd">public</span> <span class="kwrd">class</span> AnalystDao : PersonDao, IAnalystDao
{
    <span class="preproc">#region</span> IAnalystDao Members

    <span class="kwrd">public</span> IEnumerable&lt;Analyst&gt; GetAnalysts()
    {
        <span class="kwrd">return</span> Context.People.OfType&lt;Analyst&gt;();
    }

    <span class="preproc">#endregion</span>
}

<span class="kwrd">public</span> <span class="kwrd">class</span> ProjectDao : EntityDao&lt;Project&gt;, IProjectDao
{
    <span class="preproc">#region</span> IProjectDao Members

    <span class="kwrd">public</span> IEnumerable&lt;Project&gt; GetProjectsOfPerson(Person person)
    {
        <span class="kwrd">return</span> from project <span class="kwrd">in</span> Context.Projects
               <span class="kwrd">where</span> project.People.Any(p =&gt; p.Id == person.Id)
               select project;
    }

    <span class="preproc">#endregion</span>
}</pre>
</div>
<p>Implementing the IDaoFactory interface is equally simple.</p>
<p><strong>Listing 8</strong> &#8211; DaoFactory class</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> DaoFactory : IDaoFactory
{
    <span class="preproc">#region</span> IDaoFactory Members

    <span class="kwrd">public</span> IPersonDao GetPersonDao()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> PersonDao();
    }

    <span class="kwrd">public</span> IDeveloperDao GetDeveloperDao()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> DeveloperDao();
    }

    <span class="kwrd">public</span> IAnalystDao GetAnalystDao()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> AnalystDao();
    }

    <span class="kwrd">public</span> IProjectDao GetProjectDao()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> ProjectDao();
    }

    <span class="preproc">#endregion</span>
}</pre>
</div>
<p><a href="#top">Top of page</a></p>
<p><a title="businesslogic" name="businesslogic"></a><strong>Business Logic</strong></p>
<p>For brevity&#8217;s sake (a bit too late at this point) let&#8217;s create a simple and light-weight manager class to represent the business logic layer for this article.</p>
<p><strong>Listing 9</strong> &#8211; PersonManager class</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> PersonManager
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> IDaoFactory daoFactory;

    <span class="kwrd">public</span> PersonManager(IDaoFactory daoFactory)
    {
        <span class="kwrd">this</span>.daoFactory = daoFactory;
    }

    <span class="kwrd">public</span> IEnumerable&lt;Developer&gt; GetDevelopers()
    {
        IDeveloperDao dao = daoFactory.GetDeveloperDao();
        <span class="kwrd">return</span> dao.GetDevelopers();
    }

    <span class="kwrd">public</span> IEnumerable&lt;Analyst&gt; GetAnalysts()
    {
        IAnalystDao dao = daoFactory.GetAnalystDao();
        <span class="kwrd">return</span> dao.GetAnalysts();
    }

    <span class="kwrd">public</span> IEnumerable&lt;Project&gt; GetProjectsOfPerson(Person person)
    {
        IProjectDao dao = daoFactory.GetProjectDao();
        <span class="kwrd">return</span> dao.GetProjectsOfPerson(person);
    }
}</pre>
</div>
<p>Forgive me for not adding too much logic in this class. Using the PersonManager class you can query the developers, analysts and find out on which projects a particular person (developer or analyst) is working.</p>
<p><strong>Remark</strong>: The constructor of the PersonManager class requires that you pass it an object which implements the IDaoFactory interface. This allows you to use your favorite dependency injection library in order to pass in any IDaoFactory implementation. This is all you need to do in order to interchange which DAO implementation will be used by the business logic.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="quickdemo" name="quickdemo"></a><strong>A Quick Demo</strong></p>
<p>Let&#8217;s put all this code to practice in a demo application. To quickly achieve this let&#8217;s create a new Console application. Add the code shown in Listing 10.</p>
<p><strong>Listing 10</strong> -Console Application Demo</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">class</span> Program
{
    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> IDaoFactory daoFactory = <span class="kwrd">new</span> DaoFactory();
    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> PersonManager manager = <span class="kwrd">new</span> PersonManager(daoFactory);

    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> ListProjects(Person person)
    {
        IEnumerable&lt;Project&gt; projects = manager.GetProjectsOfPerson(person);
        <span class="kwrd">foreach</span> (var project <span class="kwrd">in</span> projects)
        {
            Console.WriteLine(<span class="str">"\t{0}; Deadline: {1}"</span>, project.Name, project.Deadline);
        }
    }

    <span class="kwrd">static</span> <span class="kwrd">void</span> Main()
    {
        IEnumerable&lt;Developer&gt; developers = manager.GetDevelopers();
        <span class="kwrd">foreach</span>(var developer <span class="kwrd">in</span> developers)
        {
            Console.WriteLine(String.Format(<span class="str">"{0} {1}, {2}"</span>, developer.FirstName, developer.Name, developer.PreferedLanguage));
            ListProjects(developer);
        }

        IEnumerable&lt;Analyst&gt; analysts = manager.GetAnalysts();
        <span class="kwrd">foreach</span> (var analyst <span class="kwrd">in</span> analysts)
        {
            Console.WriteLine(String.Format(<span class="str">"{0} {1}, {2}"</span>, analyst.FirstName, analyst.Name, analyst.Methodology));
            ListProjects(analyst);
        }

        Console.ReadLine();
    }
}</pre>
</div>
<p>This code displays all the developers and analysts and shows the projects on which each person is working. The output should look something like this.</p>
<p><strong>Figure 7</strong> &#8211; Output<br />
<a href="http://cgeers.files.wordpress.com/2009/03/output.jpg"><img src="http://cgeers.files.wordpress.com/2009/03/output.jpg?w=480&#038;h=79" alt="Output" title="Output" width="480" height="79" class="aligncenter size-full wp-image-569" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="summary" name="summary"></a><strong>Summary</strong></p>
<p>This article shows you one possible approach on how to use Data Access Objects (DAO&#8217;s) together with the entity framework. I encourage the use of Data Transfer Objects (DTO&#8217;s) together with DAO&#8217;s if you want to go through the hassle of doing so. If done correctly you should wind up with a business logic layer that&#8217;s completely discoupled from the domain model.</p>
<p>This article skipped the use of DTO&#8217;s altogether and uses the domain objects themselves as DTO&#8217;s. This remains a viable option in my humble opinion as long as you strictly treat them as such. </p>
<p>The only disadvantage is that this requires you to add a reference to the System.Data.Entity assembly to each layer / project that sits on top of the DAO / domain layer thus establishing a coupling, although minimal, to the Entity Framework.</p>
<p>Another disadvantage is that the domain model is too tightly coupled to the Entity Framework technology because each domain object has several attributes and implements at least three interfaces which are all specific to the Entity Framework. Hopefully the EF team will address these Persistence Ignorance issues in the next release.</p>
<p>Dispite some disadvantages I personally feel that the Entity Framework offers too much too ignore and can certainly be a more than useful ORM tool.</p>
<p>For further reading I strongly recommend <a href="http://www.linkedin.com/in/vijaypmehta" target="_blank">Vijay P. Mehta</a>&#8217;s book &#8220;<a href="http://www.apress.com/book/view/1590599659" target="_blank">Pro LINQ Object Relational Mapping with C# 2008</a>&#8220;. </p>
<p><a href="#top">Top of page</a></p>
<p><a title="download" name="download"></a><strong>Download</strong></p>
<p>You can find the source code for this article on the <a href="http://cgeers.wordpress.com/download/" target="_blank">Download page</a> of this blog.</p>
<p><a href="#top">Top of page</a></p>
Posted in C#, Design Patterns, Entity Framework, Programming  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/478/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/478/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cgeers.wordpress.com/478/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cgeers.wordpress.com/478/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cgeers.wordpress.com/478/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cgeers.wordpress.com/478/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cgeers.wordpress.com/478/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cgeers.wordpress.com/478/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cgeers.wordpress.com/478/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cgeers.wordpress.com/478/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.wordpress.com&blog=2504479&post=478&subd=cgeers&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://cgeers.wordpress.com/2009/03/14/data-access-objects-with-the-entity-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1deb97b690d087dea7942250d7b03310?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/03/database-access1.jpg" medium="image">
			<media:title type="html">database-access1</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/03/thevariousparts.jpg" medium="image">
			<media:title type="html">The Various Parts</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/03/classdiagram1.jpg" medium="image">
			<media:title type="html">Class Diagram</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/03/the-person-table.jpg" medium="image">
			<media:title type="html">Person Table</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/03/project-table.jpg" medium="image">
			<media:title type="html">Project Table</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/03/projectsperperson-table.jpg" medium="image">
			<media:title type="html">ProjectsPerPerson Table</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/03/entity-data-model.jpg" medium="image">
			<media:title type="html">Entity Data Model</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/03/output.jpg" medium="image">
			<media:title type="html">Output</media:title>
		</media:content>
	</item>
		<item>
		<title>Entity Framework ObjectContext</title>
		<link>http://cgeers.wordpress.com/2009/02/21/entity-framework-objectcontext/</link>
		<comments>http://cgeers.wordpress.com/2009/02/21/entity-framework-objectcontext/#comments</comments>
		<pubDate>Sat, 21 Feb 2009 12:46:31 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[ObjectContext]]></category>

		<guid isPermaLink="false">http://cgeers.wordpress.com/?p=415</guid>
		<description><![CDATA[Introduction
It&#8217;s been a good two months since the last post. Today I finally found some spare time to write a new article about .NET. This will be the first article on this blog focusing solely on the Entity Framework. More in particular about using the Entity Framework in different environments such as Windows Applications and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.wordpress.com&blog=2504479&post=415&subd=cgeers&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a title="introduction" name="introduction"></a><strong>Introduction</strong><img src="http://cgeers.files.wordpress.com/2008/12/web-development.gif?w=80&#038;h=80" alt="Web Development" title="Web Development" width="80" height="80" class="alignright size-full wp-image-293" /></p>
<p>It&#8217;s been a good two months since the last post. Today I finally found some spare time to write a new article about .NET. This will be the first article on this blog focusing solely on the Entity Framework. More in particular about using the Entity Framework in different environments such as Windows Applications and in an ASP.NET environment. </p>
<p>The Entity Framework has some drawbacks that will hopefully be addressed in the second release, but in its current state it&#8217;s already a really useful technology to use for database access. </p>
<p>This article will not discuss every feature of the Entity Framework as that would entail writing an entire book. The primary focus is on how to deal with the ObjectContext in different environments such as a regular Windows Application and a Web Application (ASP.NET). Let&#8217;s get started&#8230;</p>
<p><span id="more-415"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#objectcontext">ObjectContext</a></li>
<li><a href="#demosolution">Demo Solution</a></li>
<li><a href="#windowsapplication">Windows Application</a></li>
<li><a href="#sharedobjectcontext">Shared ObjectContext</a></li>
<li><a href="#aspnet">ObjectContext in ASP.NET</a></li>
<li><a href="#summary">Summary</a></li>
<li><a href="#download">Download</a></li>
</ul>
<p><a title="objectcontext" name="objectcontext"></a><strong>ObjectContext</strong></p>
<p>As you may be aware every object returned by a query (Linq To Entities, Entities SQL&#8230;) is automatically attached to an object context. This context tracks the changes applied to these objects so that it can later figure out how to persist these changes to the underlying data store.</p>
<p>This object context is represented by a class fittingly named ObjectContext. The ObjectContext encapsulates a couple of things, namely:</p>
<ul>
<li>The connection to the underlying data store (database)</li>
<li>Metadata describing the Entity Data Model (EDM)</li>
<li>An ObjectStateManager for tracking changes to the objects</li>
</ul>
<p>As you will see in the next sections how you deal with the ObjectContext depends on the target platform of your application.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="demosolution" name="demosolution"></a><strong>Demo Solution</strong></p>
<p>Let&#8217;s quickly setup up a demo project that we can use throughout the rest of this text. First let us create a simple database using SQL Server consisting out of two tables [Customer] and [Order]. </p>
<p>The following two figures list the columns for each of these tables. You can find the DDL statements to build this database in the source code accompagnying this article. </p>
<p>I&#8217;ve called my database &#8220;Westwind&#8221; but feel free to choose a more appropriate name.</p>
<p><strong>Figure 1</strong> &#8211; Customer table<br />
<a href="http://cgeers.files.wordpress.com/2009/02/customer-table.gif"><img src="http://cgeers.files.wordpress.com/2009/02/customer-table.gif?w=342&#038;h=100" alt="Customer Table" title="Customer Table" width="342" height="100" class="aligncenter size-full wp-image-428" /></a></p>
<p><strong>Figure 2</strong> &#8211; Order table<br />
<a href="http://cgeers.files.wordpress.com/2009/02/order-table.gif"><img src="http://cgeers.files.wordpress.com/2009/02/order-table.gif?w=339&#038;h=103" alt="Order table" title="Order table" width="339" height="103" class="aligncenter size-full wp-image-429" /></a></p>
<p>The [Order] table contains a foreign key connecting it&#8217;s CustomerId column to the Id column of the [Customer] table. Thanks to this relation we can easily navigate back and forth between the Customer and Order entities in the resulting Entity Data Model (EDM).</p>
<p>Now fire up Visual Studio 2008 and create a new blank solution named &#8220;ObjectContext&#8221; and add a class library to it (C#) titled &#8220;DAL&#8221; (short for Data Access Layer). Delete the automatically generated class Class1 and add a new ADO.NET Entity Data Model called &#8220;Westwind.edmx&#8221;.</p>
<p>Using the resulting wizard choose the option &#8220;Generate from database&#8221; to let Visual Studio generate an Entity Data Model based upon the previously created database. After the model is generated the necessary references to the required assemblies are automatically added to the project.</p>
<p><strong>Figure 3</strong> &#8211; ObjectContext Solution<br />
<a href="http://cgeers.files.wordpress.com/2009/02/solution.gif"><img src="http://cgeers.files.wordpress.com/2009/02/solution.gif?w=255&#038;h=301" alt="ObjectContext Solution" title="ObjectContext Solution" width="255" height="301" class="aligncenter size-full wp-image-439" /></a></p>
<p>The Entity Data Model contains two entities, namely Customer and Order. I&#8217;ve renamed the Entity Set Name properties of the Customer and Order entities respectively to Customers and Orders. As a last step the navigation property Order on the Customer entity has been renamed to Orders as a customer can have one or more orders.</p>
<p><strong>Figure 4</strong> &#8211; Westwind Entities<br />
<a href="http://cgeers.files.wordpress.com/2009/02/entities.gif"><img src="http://cgeers.files.wordpress.com/2009/02/entities.gif?w=385&#038;h=203" alt="Westwind Entities" title="Westwind Entities" width="385" height="203" class="aligncenter size-full wp-image-442" /></a></p>
<p>Voila, that concludes setting up the demo project. Let&#8217;s move on to the next section&#8230;</p>
<p><strong>Remarks</strong></p>
<ul>
<li>Be sure you have the first service pack installed for both the .NET Framework 3.5 and Visual Studio 2008 as both are required in order to be able to work with the Entity Framework.</li>
<li>The example is kept as simple as possible in order to focus solely on the subject of this article. It&#8217;s not a guideline on how to organize your projects into different layers and such.</li>
</ul>
<p><a href="#top">Top of page</a></p>
<p><a title="windowsapplication" name="windowsapplication"></a><strong>Windows Application</strong></p>
<p>I&#8217;ve added some dummy data to the table using SQL Server Management Studio Express. There are three customer and each has exactly one order.</p>
<p><strong>Figure 5</strong> &#8211; Customer Data<br />
<a href="http://cgeers.files.wordpress.com/2009/02/customer-data.gif"><img src="http://cgeers.files.wordpress.com/2009/02/customer-data.gif?w=430&#038;h=109" alt="Customer Data" title="Customer Data" width="430" height="109" class="aligncenter size-full wp-image-445" /></a></p>
<p><strong>Figure 6</strong> &#8211; Order Data<br />
<a href="http://cgeers.files.wordpress.com/2009/02/order-data.gif"><img src="http://cgeers.files.wordpress.com/2009/02/order-data.gif?w=480&#038;h=93" alt="Order Data" title="Order Data" width="480" height="93" class="aligncenter size-full wp-image-446" /></a></p>
<p>Regular Windows Applications (Console, WinForms, WPF&#8230;) are the easiest to work with in regard to handling the ObjectContext. Let&#8217;s demonstrate this using a Console application. </p>
<p>Add a new Console application and add a reference to the DAL project and the System.Data.Entity assembly. Next add an application configuration file (App.config) and copy the connection string found in the App.config file of the DAL project. Finally add the code of Listing 1 to the main method.</p>
<p><strong>Listing 1</strong> &#8211; ObjectContext in a Console application</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">using</span> (var context = <span class="kwrd">new</span> WestwindEntities())
{
    <span class="rem">// Query all the orders.</span>
    var q = from o <span class="kwrd">in</span> context.Orders.Include(<span class="str">"Customer"</span>) orderby o.Total select o;
    <span class="kwrd">foreach</span>(var order <span class="kwrd">in</span> q)
    {
        Console.WriteLine(String.Format(<span class="str">"{0} {1} has an order costing {2}."</span>,
                                        order.Customer.Firstname, order.Customer.Lastname,
                                        order.Total));
    }
    Console.WriteLine();

    <span class="rem">// Update the first order.</span>
    Order firstOrder = q.FirstOrDefault();
    <span class="kwrd">if</span> (firstOrder != <span class="kwrd">null</span>)
    {
        firstOrder.Total += 10;
        context.SaveChanges();
    }

    <span class="rem">// Display the order once more.</span>
    <span class="kwrd">foreach</span> (var order <span class="kwrd">in</span> q)
    {
        Console.WriteLine(String.Format(<span class="str">"{0} {1} has an order costing {2}."</span>,
                                        order.Customer.Firstname, order.Customer.Lastname,
                                        order.Total));
    }

    Console.ReadLine();
}</pre>
</div>
<p>A new connection (context) is made to the database and the orders are queried and displayed. Next the first order found is updated and finally the orders are displayed once more. </p>
<p>All this happens using the same ObjectContext (see the using statement). It tracks the changes made to the order objects and generates the necessary SQL to persist these changes in the database upon the call to context.SaveChanges().</p>
<p><strong>Figure 7</strong> &#8211; The Output<br />
<a href="http://cgeers.files.wordpress.com/2009/02/order-output.gif"><img src="http://cgeers.files.wordpress.com/2009/02/order-output.gif?w=428&#038;h=166" alt="Orders output" title="Orders output" width="428" height="166" class="aligncenter size-full wp-image-452" /></a></p>
<p>If you&#8217;re interested in finding out what the generated SQL looks like I recommend using the <a href="http://sqlprofiler.googlepages.com/" target="_blank">AnfiniL&#8217;s SQL Express Profiler</a> tool. It&#8217;s free and easy to use.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="sharedobjectcontext" name="sharedobjectcontext"></a><strong>Shared ObjectContext</strong></p>
<p>You can as the previous example has shown create an ObjectContext when needed and dispose of it immediately after. However you can also choose to share the same ObjectContext accross multiple methods, instances&#8230;etc. if you want to limit the amount of ObjectContext instances in your application. </p>
<p>One way of doing this is to encapsulate the ObjectContext in a class that adheres to the singleton pattern. Take a look at the code in Listing 2.</p>
<p><strong>Listing 2</strong> &#8211; Shared ObjectContext</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> SharedObjectContext
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> WestwindEntities context;

    <span class="preproc">#region</span> Singleton Pattern

    <span class="rem">// Static members are lazily initialized.</span>
    <span class="rem">// .NET guarantees thread safety for static initialization.</span>
    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> SharedObjectContext instance = <span class="kwrd">new</span> SharedObjectContext();

    <span class="rem">// Make the constructor private to hide it. </span>
    <span class="rem">// This class adheres to the singleton pattern.</span>
    <span class="kwrd">private</span> SharedObjectContext()
    {
        <span class="rem">// Create the ObjectContext.</span>
        context = <span class="kwrd">new</span> WestwindEntities();
    }

    <span class="rem">// Return the single instance of the ClientSessionManager type.</span>
    <span class="kwrd">public</span> <span class="kwrd">static</span> SharedObjectContext Instance
    {
        get
        {
            <span class="kwrd">return</span> instance;
        }
    }   

    <span class="preproc">#endregion</span>

    <span class="kwrd">public</span> WestwindEntities Context
    {
        get
        {
            <span class="kwrd">return</span> context;
        }
    }
}</pre>
</div>
<p>The following Listing shows how you would use this shared ObjectContext.</p>
<p><strong>Listing 3</strong> &#8211; Usage Of The Shared ObjectContext</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
WestwindEntities context = SharedObjectContext.Instance.Context;

var q = from o <span class="kwrd">in</span> context.Orders.Include(<span class="str">"Customer"</span>) orderby o.Total select o;

<span class="kwrd">foreach</span> (var order <span class="kwrd">in</span> q)
{
    Console.WriteLine(String.Format(<span class="str">"{0} {1} has an order costing {2}."</span>,
                                    order.Customer.Firstname, order.Customer.Lastname,
                                    order.Total));
}

Console.ReadLine();</pre>
</div>
<p>You can find this code in the ConsoleSharedObjectContext project included in the demo source code.</p>
<p><strong>Remark</strong>: Limit the scope of the ObjectContext. It is recommended to use the ObjectContext instance within a using statement. This ensures that the resources associated with the ObjectContext are automatically disposed when the using statement exists. Make sure your application benefits from a shared ObjectContext, for instance if you bind control to objects maintained by the ObjectContext.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="aspnet" name="aspnet"></a><strong>ObjectContext in ASP.NET</strong></p>
<p>To quote <a href="http://www.msdn.com" target="_blank">MSDN</a>: &#8220;The ObjectContext class is not thread safe. The integrity of data objects in an ObjectContext cannot be ensured in multi-threaded scenarios.&#8221;.</p>
<p>This rules out using the afore mentioned approach in an ASP.NET environment as it is inheritly multi-threaded. Each request is handled by a separate thread. To circumvent the problem the solution is to use an ObjectContext per Http request. The following Listing shows one possible approach.</p>
<p><strong>Listing 4</strong> &#8211; ObjectContext Per Http Request</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> ObjectContextPerHttpRequest
{
    <span class="kwrd">public</span> <span class="kwrd">static</span> WestwindEntities Context
    {
        get
        {
            <span class="kwrd">string</span> objectContextKey = HttpContext.Current.GetHashCode().ToString(<span class="str">"x"</span>);
            <span class="kwrd">if</span> (!HttpContext.Current.Items.Contains(objectContextKey))
            {
                HttpContext.Current.Items.Add(objectContextKey, <span class="kwrd">new</span> WestwindEntities());
            }
            <span class="kwrd">return</span> HttpContext.Current.Items[objectContextKey] <span class="kwrd">as</span> WestwindEntities;
        }
    }
}</pre>
</div>
<p>To demonstrate its usage add a new Web Application project to the solution, add the necessary references to the DAL project and the System.Data.Entity assembly. Finally add the connection string to the Web.config file. </p>
<p>Open up the default.aspx page in design view and add a GridView. Add the following code to the code-behind in the Page_Load(&#8230;) event handler to bind some data to the grid.</p>
<p><strong>Listing 5</strong> &#8211; Default.aspx.cs code-behind</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">protected</span> <span class="kwrd">void</span> Page_Load(<span class="kwrd">object</span> sender, EventArgs e)
{
    WestwindEntities context = ObjectContextPerHttpRequest.Context;
    GridView1.DataSource = from c <span class="kwrd">in</span> context.Customers select c;
    GridView1.DataBind();
}</pre>
</div>
<p>The output is a list of the customers.</p>
<p><strong>Figure 8</strong> &#8211; The Output In ASP.NET<br />
<a href="http://cgeers.files.wordpress.com/2009/02/ie-output.gif"><img src="http://cgeers.files.wordpress.com/2009/02/ie-output.gif?w=480&#038;h=255" alt="ObjectContext in ASP.NET" title="ObjectContext in ASP.NET" width="480" height="255" class="aligncenter size-full wp-image-468" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="summary" name="summary"></a><strong>Summary</strong></p>
<p>While there is much debate going on about the Entity Framework I certainly feel that this first release offers a valid alternative to any prior existing data access technologies. </p>
<p>Working with the Entity Framework entails dealing with the ObjectContext. As demonstrated the way the ObjectContext is too be handled depends on the target platform. Sharing the ObjectContext on one thread poses no problem (Windows Applications), however as soon as you end up in a multi-threaded environment (ASP.NET) you must implement some custom logic to ensure the integrity of the data objects within the ObjectContext.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="download" name="download"></a><strong>Download</strong></p>
<p>You can find the source code for this article on the <a href="http://cgeers.wordpress.com/download/" target="_blank">Download page</a> of this blog.</p>
<p><a href="#top">Top of page</a></p>
Posted in ASP.NET, C#, Entity Framework, Programming  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/415/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/415/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cgeers.wordpress.com/415/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cgeers.wordpress.com/415/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cgeers.wordpress.com/415/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cgeers.wordpress.com/415/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cgeers.wordpress.com/415/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cgeers.wordpress.com/415/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cgeers.wordpress.com/415/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cgeers.wordpress.com/415/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.wordpress.com&blog=2504479&post=415&subd=cgeers&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://cgeers.wordpress.com/2009/02/21/entity-framework-objectcontext/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1deb97b690d087dea7942250d7b03310?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2008/12/web-development.gif" medium="image">
			<media:title type="html">Web Development</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/02/customer-table.gif" medium="image">
			<media:title type="html">Customer Table</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/02/order-table.gif" medium="image">
			<media:title type="html">Order table</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/02/solution.gif" medium="image">
			<media:title type="html">ObjectContext Solution</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/02/entities.gif" medium="image">
			<media:title type="html">Westwind Entities</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/02/customer-data.gif" medium="image">
			<media:title type="html">Customer Data</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/02/order-data.gif" medium="image">
			<media:title type="html">Order Data</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/02/order-output.gif" medium="image">
			<media:title type="html">Orders output</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2009/02/ie-output.gif" medium="image">
			<media:title type="html">ObjectContext in ASP.NET</media:title>
		</media:content>
	</item>
		<item>
		<title>MVP: Model View Presenter</title>
		<link>http://cgeers.wordpress.com/2008/12/14/mvp-model-view-presenter/</link>
		<comments>http://cgeers.wordpress.com/2008/12/14/mvp-model-view-presenter/#comments</comments>
		<pubDate>Sat, 13 Dec 2008 23:01:39 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Model]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Presenter]]></category>
		<category><![CDATA[View]]></category>

		<guid isPermaLink="false">http://cgeers.wordpress.com/?p=295</guid>
		<description><![CDATA[Introduction
Last week I was reading some articles about using WCF, the Entity Framework and how to transport entities across the service boundary. One of the articles I encountered included a demo project that made use of the Model View Presenter (MVP) pattern.
Having explored the demo project I thought it might be interesting to write an [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.wordpress.com&blog=2504479&post=295&subd=cgeers&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a title="introduction" name="introduction"></a><strong>Introduction</strong><a href="http://groups.google.be/group/ooadug" target="_blank"><img src="http://cgeers.files.wordpress.com/2008/03/ooadug.png" alt="OOADug" align="right" /></a></p>
<p>Last week I was reading some articles about using WCF, the Entity Framework and how to transport entities across the service boundary. One of the articles I encountered included a demo project that made use of the Model View Presenter (MVP) pattern.</p>
<p>Having explored the demo project I thought it might be interesting to write an article about this pattern. Your favorite search engine will happily supply you with a plethora of links to other articles that explain this pattern thoroughly.</p>
<p>For this article I&#8217;ve decided to supply a concrete implemention and to focus less on the theory behind the pattern.</p>
<p>Let&#8217;s roll&#8230;</p>
<p><span id="more-295"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#pattern">The Pattern</a></li>
<li><a href="#model">Model</a></li>
<li><a href="#business">Business Layer</a></li>
<li><a href="#view">View</a></li>
<li><a href="#presenter">Presenter</a></li>
<li><a href="#aspuserinterface">ASP.NET User Interface</a></li>
<li><a href="#winformsuserinterface">WinForms User Interface</a></li>
<li><a href="#summary">Summary</a></li>
<li><a href="#download">Download</a></li>
</ul>
<p><a title="pattern" name="pattern"></a><strong>The Pattern</strong></p>
<p>Of course a bit of theory is required, so let&#8217;s get it out of the way.</p>
<p>As you can deduct from the name the MVP pattern consists out of three distinct parts: the Model, View and Presenter. Each of these parts play their own role in establishing a separation of concerns between the presentation, business and data access layer.</p>
<p>The Model is responsible for handling the data access, the Presenter communicates with the Model and passes data from and to it. The View receives data from the Presenter and passes data back, it never communicates directly with the Model. The Presenter is the go-between for the View and Model.</p>
<p><strong>Figure 1</strong> &#8211; MVP Pattern Interaction<br />
<a href="http://cgeers.files.wordpress.com/2008/12/mvp3.gif"><img class="aligncenter size-full wp-image-320" title="Model View Presenter" src="http://cgeers.files.wordpress.com/2008/12/mvp3.gif" alt="Model View Presenter" width="300" height="171" /></a></p>
<p>The image above depicts the View as implementing an interface. The presentation layer be it an ASP.NET, WinForms or WPF applications needs to implement one or more view interfaces. The Presenter in turn communicates with the View implementation through this interface, it knows nothing about the actual implementation itself.</p>
<p>This provides a loose coupling and prevents your code from being dependant on the technology used for the Presentation Layer. The idea is that you should be able to replace this layer without it affecting your business and data access logic.</p>
<p>This might all seem a little vague, but things should clear up once we move on to the following points which provide an actual implementation of this pattern. For the example an ASP.NET application will be used.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="model" name="model"></a><strong>Model</strong></p>
<p>The most logical place to start with is the Model. Since it is responsible for handling data access and storage we first need to establish a physical data store. For this I used SQL Server 2005 Express, created a new database called Southwind and added one table titled Customer. The table has 3 fields, namely:</p>
<ul>
<li><strong>Id</strong>: Unique identifier (GUID) &amp; Primary key</li>
<li><strong>Firstname</strong>: nvarchar(50)</li>
<li><strong>Lastname</strong>: nvarchar(50)</li>
</ul>
<p>That&#8217;s it for the database. Let&#8217;s fire up Visual Studio 2008 and create a new blank solution named AvpPattern. Next add a class library titled &#8220;Database&#8221;.</p>
<p>Normally I&#8217;d give the project a name that follows the pattern &#8220;Company.Product.Library&#8221;, but for simplicity&#8217;s sake let&#8217;s keep it short and simple. Also delete the autogenerated class1.cs file after the project has been added to the solution.</p>
<p>Let&#8217;s create a model from the database using the Entity Framework (EF). So be sure you are using Visual Studio 2008 and have Service Pack 1 installed for Visual Studio and the .NET Framework 3.5. You can download the service packs <a href="http://msdn.microsoft.com/en-us/vstudio/cc533448.aspx" target="_blank">here</a>.</p>
<p>Add a Entity Framework data model to the class library by selecting Add, New Item, ADO.NET Entity Data Model from the project&#8217;s context menu in the Solution Explorer. Visual Studio will now show the Entity Data Model Wizard. Name the model Southwind and let Visual Studio generate the model for you. When asked which database objects you want to include in your model just select the Customer table from the tables node.</p>
<p><strong><span style="text-decoration:underline;">Remark</span></strong>: If you are not familiar with generating data models with the Entity Framework I highly suggest this <a href="http://www.asp.net/learn/3.5-videos/video-300.aspx" target="_blank">training video</a> from Alex James. It shows you how to build a simple Entity Data Model from scratch.</p>
<p>Figure 2 shows the resulting entity data model. The model can&#8217;t get much simpler than this. This is done on purpose to keep things as simple as possible and to keep the focus on the MVP pattern.</p>
<p><strong>Figure 2</strong> &#8211; Entity Data Model<br />
<a href="http://cgeers.files.wordpress.com/2008/12/entitydesignerdiagram.gif"><img class="aligncenter size-full wp-image-338" title="Entity Framework Data Model" src="http://cgeers.files.wordpress.com/2008/12/entitydesignerdiagram.gif" alt="Entity Framework Data Model" width="163" height="156" /></a></p>
<p>Be sure to rename your EntityTypes and EntitySets to an appropriate name after the data model has been generated. The rule of thumb is to use a single noun for the EntityType and a plural for the EntitySets. So in this case our EntityType should be named Customer and the EntitySet Customers. The name for the EntityType is already ok as it inherits it from the Customer table, so just select the Customer EntityType and adjust its Entity Set Name property.</p>
<p><strong>Figure 3</strong> &#8211; Entity Set Name<br />
<a href="http://cgeers.files.wordpress.com/2008/12/southwindmodelcustomer.gif"><img class="aligncenter size-full wp-image-353" title="Entity Set Name" src="http://cgeers.files.wordpress.com/2008/12/southwindmodelcustomer.gif" alt="Entity Set Name" width="353" height="172" /></a></p>
<p>The Entity Framework will automatically generate a partial class for the Customer table. You can choose to extend this partical Customer class if you want to. To prevent your custom additions from being erased when regenerating the model put this code in a separate class file. This is simular to working with strongly typed datasets. For the article this is not required however.</p>
<p><strong>Figure 4</strong> &#8211; Solution Explorer<br />
<a href="http://cgeers.files.wordpress.com/2008/12/solutionexplorer.gif"><img class="aligncenter size-full wp-image-343" title="Solution Explorer" src="http://cgeers.files.wordpress.com/2008/12/solutionexplorer.gif" alt="Solution Explorer" width="353" height="310" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="business" name="business"></a><strong>Business Layer</strong></p>
<p>Now that the model is in place let&#8217;s add a business layer on top of it where we can define our custom business logic. For simplicity&#8217;s sake I will keep the amount of code limited in this layer.</p>
<p>Note that these layers only enforce a logical separation (n-layer), not a physical one (n-tier). The layers all reside on the same machine, though you could certainly choose to disbribute them across multiple machines / tiers and create a truly distributed or n-tier application.</p>
<p>To setup the Business Layer add a new class library to the solution and call it Business. Next rename the default Class.cs file to CustomerManager.cs. Also add references to the previously created class library Database and to the System.Data.Entity assembly.</p>
<p>Listing 1 displays the CustomerManager class which contains some business logic for working with the Customer entity from the Entity Data Model (EDM). The code is pretty much self-explanatory.</p>
<p><strong>Listing 1</strong> &#8211; CustomerManager class</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre><span class="kwrd">using</span> System.Collections.Generic;
<span class="kwrd">using</span> System.Linq;
<span class="kwrd">using</span> Database;

<span class="kwrd">namespace</span> Business
{
    <span class="kwrd">public</span> <span class="kwrd">class</span> CustomerManager
    {
        <span class="kwrd">private</span> <span class="kwrd">readonly</span> SouthwindEntities context;

        <span class="preproc">#region</span> Constructor(s)

        <span class="kwrd">public</span> CustomerManager()
        {
            context = <span class="kwrd">new</span> SouthwindEntities();
        }

        <span class="preproc">#endregion</span>

        <span class="preproc">#region</span> Methods

        <span class="rem">// Retrieve a generic list of Customer entities.</span>
        <span class="rem">// This method will return all the customers found in the Customer table.</span>
        <span class="kwrd">public</span> List&lt;Customer&gt; GetCustomers()
        {
            var q = from c <span class="kwrd">in</span> context.Customers
                    select c;
            <span class="kwrd">return</span> q.ToList();
        }

        <span class="preproc">#endregion</span>
    }
}</pre>
</div>
<p><strong>Figure 5</strong> &#8211; Updated Solution<br />
<a href="http://cgeers.files.wordpress.com/2008/12/solutionexplorer2.gif"><img class="aligncenter size-full wp-image-357" title="Update Solution" src="http://cgeers.files.wordpress.com/2008/12/solutionexplorer2.gif" alt="Update Solution" width="353" height="141" /></a></p>
<p><strong><span style="text-decoration:underline;">Remark</span></strong>: Setting up an n-tier application would include introducing a Service Layer which the Presentation Layer calls into. The Service Layer then utilizes the business objects found in the Business Layer. There is no direct association between the Presentation and Business Layer anymore, the Service Layer acts as an intermediate. In a future article I will address this by showing how to transport EF Entities across the service boundary.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="view" name="view"></a><strong>View</strong></p>
<p>The Business Layer only contains one useful method, namely &#8220;List&lt;Customer&gt; GetCustomers()&#8221;. The Presenter in the MVP pattern will call this method on the CustomerManager business object in order to deliver the data to the view.</p>
<p>The example application only shows a list of customers using the MVP pattern. This might be a bit of overkill, but it&#8217;s kept as simple as possibly by design. The main goal of this &#8220;Hello World!&#8221; type of application is to get the idea across of how to implement this pattern. The actual functionality offered by the application is not that important.</p>
<p>The actual view implementation (ASPX page, WinForms, WPF&#8230;etc.) will need to implement a view interface. The view implementation needs to create an instance of the Presenter and pass itself as a parameter in its constructor. The Presenter&#8217;s constructor has one parameter which is the type of the view interface.</p>
<p>Listing 2 lists the IView interface which we will implement shortly in an ASP.NET ASPX page. It has one event named PrepareView. The PrepareView event uses a delegate whose signature specifies that it returns nothing and takes no parameters.</p>
<p>The View should only raise these kind of &#8220;empty events&#8221; as to signify to the Presenter that some action should be performed. The action in this case signifies that the Presenter should refresh the list of Customers that the view implementation maintains. The Presenter can access this list of customers through the IList&lt;Customer&gt; Customers property which is declared as part of the interface.</p>
<p><strong>Listing 2</strong> &#8211; View Interface</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre><span class="kwrd">public</span> <span class="kwrd">delegate</span> <span class="kwrd">void</span> VoidEventHandler();

<span class="kwrd">public</span> <span class="kwrd">interface</span> IView
{
    <span class="kwrd">event</span> VoidEventHandler PrepareView;
    IList&lt;Customer&gt; Customers { set; }
}</pre>
</div>
<p>To add the view interface to your project first add a new class library project to the solution called Presentation. Next add a new interface and copy and paste the code shown in the above listing. The Presentation code library will also contain the Presenters and the interfaces they implement.</p>
<p>I separate the view interfaces and presenters in a separate code library so that you can easily share them between multiple &#8220;view frameworks&#8221; such as ASP.NET, WinForms, WPF&#8230;etc. Figure 6 shows how I&#8217;ve chosen to organise this code library.</p>
<p><strong>Figure 6</strong> &#8211; Updated Solution<br />
<a href="http://cgeers.files.wordpress.com/2008/12/solutionexplorer3.gif"><img class="aligncenter size-full wp-image-366" title="Updated Solution" src="http://cgeers.files.wordpress.com/2008/12/solutionexplorer3.gif" alt="Updated Solution" width="353" height="208" /></a></p>
<p>Don&#8217;t forget to add references to the Database and Business projects and the System.Data.Entity assembly.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="presenter" name="presenter"></a><strong>Presenter</strong></p>
<p>For the final part of the MVP pattern we need to provide a Presenter. The CustomersPresenter class shown in Listing 3 takes a reference to an IView implementation in its constructor. This way it can communicate with the view without actually knowing anything about the actual implementation. It is this loose coupling that makes the MVP pattern so suitable for different &#8220;view frameworks&#8221;.</p>
<p>Also in the constructor all the events of the view interface are hooked up to an event handler. In this case there is only one event. The PrepareView event is hooked up to the view_PrepareView event handler. This in turn calls the Presenter&#8217;s private method GetCustomers() which returns a &#8220;refreshed&#8221; Customers collection and assigns it to the Customers collection maintained by the view implementation.</p>
<p><strong>Listing 3</strong> &#8211; CustomersPresenter class</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre><span class="kwrd">public</span> <span class="kwrd">class</span> CustomersPresenter : ICustomersPresenter
{
    <span class="preproc">#region</span> Fields

    <span class="kwrd">private</span> <span class="kwrd">readonly</span> IView view;

    <span class="preproc">#endregion</span>

    <span class="preproc">#region</span> Constructor(s)

    <span class="kwrd">public</span> CustomersPresenter(IView view)
    {
        <span class="rem">// Save a reference to the view</span>
        <span class="kwrd">this</span>.view = view;

        <span class="rem">// Hook up an event handler for the events of the view</span>
        view.PrepareView += view_PrepareView;
    }

    <span class="preproc">#endregion</span>

    <span class="preproc">#region</span> Private methods

    <span class="kwrd">private</span> List&lt;Customer&gt; GetCustomers()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> CustomerManager().GetCustomers();
    }

    <span class="preproc">#endregion</span>

    <span class="preproc">#region</span> ICustomersPresenter Members

    <span class="kwrd">public</span> <span class="kwrd">virtual</span> <span class="kwrd">void</span> view_PrepareView()
    {
        view.Customers = GetCustomers();
    }

    <span class="preproc">#endregion</span>
}</pre>
</div>
<p>The above Presenter also implements an interface. In the sample source code this interface is left empty. I&#8217;ve only put it there for illustrative purposes. You can flesh out this interface if you desire. You might need it for your favorite unit testing framework to mock presenters for example.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="aspuserinterface" name="aspuserinterface"></a><strong>ASP.NET User Interface</strong></p>
<p>So the view or ASPX page in our case only needs to implement the view interface and trigger the PrepareView event in order to receive an updated customers list from the Presenter. The view itself does not communicate with the database or Business Layer directly. The Presenter handles the communication with the Business Layer which retrieves the data by addressing the Model (or Data Access Layer if you will).</p>
<p>To finish up this article let&#8217;s see how this all comes together in an ASP.NET demo project. Add a new project using the ASP.NET Web Application project template to the solution. Add references to the Presentation and Database projects and the System.Data.Entity assembly.</p>
<p>Add a GridView named &#8220;GridView1&#8243; and a Button named &#8220;btnRefresh&#8221; to the Default.aspx page. Add the code in Listing 4 to the code behind of the page.</p>
<p><strong>Listing 4</strong> &#8211; Default.aspx Code Behind</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre><span class="kwrd">public</span> <span class="kwrd">partial</span> <span class="kwrd">class</span> _Default : System.Web.UI.Page, IView
{
    <span class="kwrd">private</span> CustomersPresenter presenter;

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> OnInit(EventArgs e)
    {
        presenter = <span class="kwrd">new</span> CustomersPresenter(<span class="kwrd">this</span>);
    }

    <span class="kwrd">protected</span> <span class="kwrd">void</span> Page_Load(<span class="kwrd">object</span> sender, EventArgs e)
    {
        <span class="kwrd">if</span> (!IsPostBack)
        {
            PrepareView();
        }
    }

    <span class="kwrd">protected</span> <span class="kwrd">void</span> btnRefresh_Click(<span class="kwrd">object</span> sender, EventArgs e)
    {
        PrepareView();
    }

    <span class="preproc">#region</span> IView Members

    <span class="kwrd">public</span> <span class="kwrd">event</span> VoidEventHandler PrepareView;

    <span class="kwrd">public</span> IList&lt;Database.Customer&gt; Customers
    {
        set
        {
            GridView1.DataSource = <span class="kwrd">value</span>;
            GridView1.DataBind();
        }
    }

    <span class="preproc">#endregion</span>
}</pre>
</div>
<p>All the code behind of the ASPX page does is implement the IView interface, create a Presenter and pass an IView implementation, being itself, into its constructor. Then all that remains is to trigger the PrepareView() event of the IView interface at the appropriate times.</p>
<p>During the creation of the Presenter an event handler is automatically assigned to this event which makes sure that when it is triggered the Presenter knows how to update the Customers collection maintained by the page. The page itself knows nothing of where this data is coming from or how it is retrieved. The dumber a view the better.</p>
<p>When viewing this page in a browser this is the result:</p>
<p><strong>Figure 7</strong> &#8211; ASP.NET Website Demo<br />
<a href="http://cgeers.files.wordpress.com/2008/12/mvpresult.gif"><img class="aligncenter size-full wp-image-392" title="MVP Result" src="http://cgeers.files.wordpress.com/2008/12/mvpresult.gif" alt="MVP Result" width="480" height="254" /></a></p>
<p><strong><u>Remark</u></strong>: Don&#8217;t forget to add the connectionstring required by the Entity Framework to the web.config configuration file. You can find the connectionstring in the App.config file of the Database class library project. It was inserted there automatically when Visual Studio generated the Entity Data Model. </p>
<p>Of course the connection strings in supplied in the sample source code won&#8217;t work on your computer as they were constructed against a local database of mine. So be sure to adjust them accordingly.</p>
<p><strong>Figure 8</strong> &#8211; Updated Solution<br />
<a href="http://cgeers.files.wordpress.com/2008/12/solutionexplorer4.gif"><img src="http://cgeers.files.wordpress.com/2008/12/solutionexplorer4.gif" alt="Updated Solution" title="Updated Solution" width="353" height="213" class="aligncenter size-full wp-image-401" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="winformsuserinterface" name="winformsuserinterface"></a><strong>WinForms User Interface</strong></p>
<p>As the final step of this article let&#8217;s create a view using a Windows Forms application just to show you how flexible the MVP pattern really is. The steps to do this are nearly identical to the previous example of creating an ASP.NET website. Add a new Windows Forms application to your solution and add references to the Database and Presentation project and the System.Data.Entity assembly.</p>
<p>Next add a DataGridView and Button control to the form. The code for the form is displayed in the listing below. It is almost identical to that of the Default.aspx page. Also don&#8217;t forget to add the Entity Framework connection string to the App.config configuration file.</p>
<p><strong>Listing 5</strong> &#8211; Form1.cs code</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Windows.Forms;
<span class="kwrd">using</span> Presentation.Presenters;
<span class="kwrd">using</span> Presentation.ViewInterfaces;

<span class="kwrd">namespace</span> WindowsFormsApplication
{
    <span class="kwrd">public</span> <span class="kwrd">partial</span> <span class="kwrd">class</span> Form1 : Form, IView
    {
        <span class="kwrd">private</span> CustomersPresenter presenter;

        <span class="kwrd">public</span> Form1()
        {
            InitializeComponent();

            presenter = <span class="kwrd">new</span> CustomersPresenter(<span class="kwrd">this</span>);
        }

        <span class="kwrd">private</span> <span class="kwrd">void</span> Form1_Load(<span class="kwrd">object</span> sender, EventArgs e)
        {
            PrepareView();
        }

        <span class="kwrd">private</span> <span class="kwrd">void</span> btnRefresh_Click(<span class="kwrd">object</span> sender, EventArgs e)
        {
            PrepareView();
        }

        <span class="preproc">#region</span> IView Members

        <span class="kwrd">public</span> <span class="kwrd">event</span> VoidEventHandler PrepareView;

        <span class="kwrd">public</span> System.Collections.Generic.IList&lt;Database.Customer&gt; Customers
        {
            set
            {
                dataGridView1.DataSource = <span class="kwrd">value</span>;
            }
        }

        <span class="preproc">#endregion</span>
    }
}</pre>
</div>
<p>Voila, we&#8217;re finally done. Note that although the ASP.NET and WinForms example are almost identical in code this might not be the case in more complex applications. The types of interactions in these two types of user interfaces are vastly different and coming up with a presenter you can use in all situations might not be that clear cut.</p>
<p><strong>Figure 9</strong> &#8211; Windows Forms Application Demo<br />
<a href="http://cgeers.files.wordpress.com/2008/12/winformsdemo.gif"><img src="http://cgeers.files.wordpress.com/2008/12/winformsdemo.gif" alt="Windows Forms Application Demo" title="Windows Forms Application Demo" width="431" height="197" class="aligncenter size-full wp-image-405" /></a></p>
<p><strong>Figure 10</strong> &#8211; Updated Solution<br />
<a href="http://cgeers.files.wordpress.com/2008/12/solutionexplorer5.gif"><img src="http://cgeers.files.wordpress.com/2008/12/solutionexplorer5.gif" alt="Updated Solution" title="Updated Solution" width="353" height="225" class="aligncenter size-full wp-image-407" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="summary" name="summary"></a><strong>Summary</strong></p>
<p>For this article the classic interpretation of the MVP pattern was used and demonstrated by implementing it an ASP.NET solution. The original MVP pattern is deemed &#8220;<a href="http://martinfowler.com/eaaDev/ModelViewPresenter.html" target="_blank">retired</a>&#8221; ever since Martin Fowler announced so. The pattern can be split into two camps now, being:</p>
<ul>
<li>Passive View</li>
<li>Supervising Controller</li>
</ul>
<p>Read this Microsoft Patterns &amp; Practices <a href="http://msdn.microsoft.com/en-us/library/cc304760.aspx" target="_blank">article</a> for more information.</p>
<p>I wrote this article to supply a concrete implementation of the MVP pattern as I was exploring it at the time. However it might be wise to stay clear of it and wait until Microsoft releases the ASP.NET MVC framework. For those wishing to mimic an Model-View-Controller (MVC) framework now I suggest reading <a href="http://msdn.microsoft.com/en-us/library/ms998540.aspx" target="_blank">this article</a> by Microsoft Patterns &amp; Practices.</p>
<p><strong><span style="text-decoration:underline;">Remark</span></strong>: The MVP pattern is a derivative of the Model View Controller pattern (MVC). At the time of this writing Microsoft is currently busy developing the <a href="http://www.asp.net/mvc" target="_blank">ASP.NET MVC Framework</a>. When mapping out the architecture for a new website project I suggest checking out this framework.</p>
<p>The main difference between the MVP and MVC patterns can be pinpointed to who is responsible for handling the user input such as keyboard and moue events. In the MVP pattern the GUI itself is responsible and needs to delegate them to the Presenter through events. In the MVC pattern the controller is responsible for handling these events.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="download" name="download"></a><strong>Download</strong></p>
<p>You can find the source code for this article on the <a href="http://cgeers.wordpress.com/download/" target="_blank">Download page</a> of this blog.</p>
<p><a href="#top">Top of page</a></p>
Posted in ASP.NET, C#, Design Patterns, Programming  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/295/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/295/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cgeers.wordpress.com/295/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cgeers.wordpress.com/295/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cgeers.wordpress.com/295/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cgeers.wordpress.com/295/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cgeers.wordpress.com/295/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cgeers.wordpress.com/295/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cgeers.wordpress.com/295/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cgeers.wordpress.com/295/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.wordpress.com&blog=2504479&post=295&subd=cgeers&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://cgeers.wordpress.com/2008/12/14/mvp-model-view-presenter/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1deb97b690d087dea7942250d7b03310?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2008/03/ooadug.png" medium="image">
			<media:title type="html">OOADug</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2008/12/mvp3.gif" medium="image">
			<media:title type="html">Model View Presenter</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2008/12/entitydesignerdiagram.gif" medium="image">
			<media:title type="html">Entity Framework Data Model</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2008/12/southwindmodelcustomer.gif" medium="image">
			<media:title type="html">Entity Set Name</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2008/12/solutionexplorer.gif" medium="image">
			<media:title type="html">Solution Explorer</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2008/12/solutionexplorer2.gif" medium="image">
			<media:title type="html">Update Solution</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2008/12/solutionexplorer3.gif" medium="image">
			<media:title type="html">Updated Solution</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2008/12/mvpresult.gif" medium="image">
			<media:title type="html">MVP Result</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2008/12/solutionexplorer4.gif" medium="image">
			<media:title type="html">Updated Solution</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2008/12/winformsdemo.gif" medium="image">
			<media:title type="html">Windows Forms Application Demo</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2008/12/solutionexplorer5.gif" medium="image">
			<media:title type="html">Updated Solution</media:title>
		</media:content>
	</item>
		<item>
		<title>ASP.NET Menu: Sliding Doors of CSS</title>
		<link>http://cgeers.wordpress.com/2008/12/06/aspnet-menu-sliding-doors-of-css/</link>
		<comments>http://cgeers.wordpress.com/2008/12/06/aspnet-menu-sliding-doors-of-css/#comments</comments>
		<pubDate>Sat, 06 Dec 2008 22:55:44 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Add new tag]]></category>
		<category><![CDATA[Site map]]></category>
		<category><![CDATA[Submenu]]></category>
		<category><![CDATA[Tabular Menu]]></category>

		<guid isPermaLink="false">http://cgeers.wordpress.com/?p=176</guid>
		<description><![CDATA[Introduction
The purpose of this article is to create a slick looking and easy to use menu for an ASP.NET enabled website. In order to accomplish this we&#8217;ll use the standard functionality of the ASP.NET Menu web control and enhance the look purely by using Cascading Style Sheets (CSS).
For those of you familiar with CSS the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.wordpress.com&blog=2504479&post=176&subd=cgeers&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a title="introduction" name="introduction"></a><strong>Introduction</strong><img src="http://cgeers.files.wordpress.com/2008/12/web-development.gif?w=80&#038;h=80" alt="Web Development" title="Web Development" width="80" height="80" class="alignright size-full wp-image-293" /></p>
<p>The purpose of this article is to create a slick looking and easy to use menu for an ASP.NET enabled website. In order to accomplish this we&#8217;ll use the standard functionality of the ASP.NET Menu web control and enhance the look purely by using Cascading Style Sheets (CSS).</p>
<p>For those of you familiar with CSS the title of this article will surely ring a bell. The CSS used to enhance the look and feel of the ASP.NET Menu control is decribed in a widely known article on <a href="http://www.alistapart.com/" target="_blank">A List Apart</a>, entitled &#8220;<a href="http://www.alistapart.com/articles/slidingdoors/" target="_blank">Sliding Doors of CSS</a>&#8220;.</p>
<p>The CSS used to improve the look and feel of the menu is thoroughly explained in the article on <a href="http://www.alistapart.com/articles/slidingdoors/" target="_blank">A List Apart</a>. Credit when credit is due. Thank Douglas Bowman for supplying us with the CSS. Be sure to read <a href="http://www.alistapart.com/articles/slidingdoors/" target="_blank">his article</a> first if you are not familiar with it.</p>
<p>The focus of this article is on how to simulate such a menu in an ASP.NET environment. Let&#8217;s get started&#8230;</p>
<p><span id="more-176"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#sitemap">Sitemap</a></li>
<li><a href="#cssfriendly">CSS Friendly Adapters</a></li>
<li><a href="#styling">Styling The Menu</a></li>
<li><a href="#submenu">Sub Menu</a></li>
<li><a href="#finishingup">Finishing Up</a></li>
<li><a href="#summary">Summary</a></li>
<li><a href="#download">Download</a></li>
</ul>
<p><a title="sitemap" name="sitemap"></a><strong>Sitemap</strong></p>
<p>Let&#8217;s fire up Visual Studio 2008 and create a new project using the ASP.NET Web Application project template. This template will automatically add a default web form appropriately named &#8220;Default.aspx&#8221;. Open it in the editor and add the Menu control from the Toolbox which you can find under the Navigation tab. If you run the website now you&#8217;ll wind up staring at a blank page. For the menu to display anything it first has to be bound to some data.</p>
<p>The easiest way to define data for the menu control to use and enable the visitors to navigate through the website is to bind it to a site map. Add a new site map item to the project using the proposed name of &#8220;Web.sitemap&#8221;. The site map is an Xml file that organizes the pages of the site in a hierarchical manner. An added advantage is that it is automatically referenced by the SiteMapDataSource control.</p>
<p>Next add some pages to the sitemap as displayed in the listing below.</p>
<p><strong>Listing 1</strong> &#8211; Web.sitemap</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre><span class="kwrd">&lt;?</span><span class="html">xml</span> <span class="attr">version</span><span class="kwrd">="1.0"</span> <span class="attr">encoding</span><span class="kwrd">="utf-8"</span> ?<span class="kwrd">&gt;</span>
<span class="kwrd">&lt;</span><span class="html">siteMap</span> <span class="attr">xmlns</span><span class="kwrd">="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0"</span> <span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">siteMapNode</span> <span class="attr">url</span><span class="kwrd">=""</span> <span class="attr">title</span><span class="kwrd">=""</span>  <span class="attr">description</span><span class="kwrd">=""</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">siteMapNode</span> <span class="attr">url</span><span class="kwrd">="Default.aspx"</span> <span class="attr">title</span><span class="kwrd">="Home"</span>  <span class="attr">description</span><span class="kwrd">="Take me back to the dasboard"</span> <span class="kwrd">/&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">siteMapNode</span> <span class="attr">url</span><span class="kwrd">="Products.aspx"</span> <span class="attr">title</span><span class="kwrd">="Products"</span>  <span class="attr">description</span><span class="kwrd">="Browse our catalog"</span> <span class="kwrd">/&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">siteMapNode</span> <span class="attr">url</span><span class="kwrd">="Download.aspx"</span> <span class="attr">title</span><span class="kwrd">="Download"</span>  <span class="attr">description</span><span class="kwrd">="Download neat stuff"</span> <span class="kwrd">/&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">siteMapNode</span> <span class="attr">url</span><span class="kwrd">="Forum.aspx"</span> <span class="attr">title</span><span class="kwrd">="Forum"</span>  <span class="attr">description</span><span class="kwrd">="Ask questions on our forum"</span> <span class="kwrd">/&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">siteMapNode</span> <span class="attr">url</span><span class="kwrd">="Contact.aspx"</span> <span class="attr">title</span><span class="kwrd">="Contact"</span>  <span class="attr">description</span><span class="kwrd">="Contact us"</span> <span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">siteMapNode</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">siteMap</span><span class="kwrd">&gt;</span></pre>
</div>
<p>Now add a SiteMapDataSource control to the page and set the DataSourceID property of the menu control to the Id of the data source. Also set the Orientation property of the menu control to horizontal as it defaults to vertical. Last but not least set the ShowStartingNode property of the SiteMapDataSource to false. If you don&#8217;t do this only the root node will be displayed and we don&#8217;t want to include this base node in the menu. Your code should now resemble the code displayed in Listing 2.</p>
<p><strong>Listing 2</strong> &#8211; Default.aspx</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre><span class="kwrd">&lt;</span><span class="html">asp:Menu</span> <span class="attr">ID</span><span class="kwrd">="Menu1"</span> <span class="attr">runat</span><span class="kwrd">="server"</span> <span class="attr">DataSourceID</span><span class="kwrd">="SitemapDataSource1"</span> <span class="attr">Orientation</span><span class="kwrd">="Horizontal"</span><span class="kwrd">&gt;&lt;/</span><span class="html">asp:Menu</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;</span><span class="html">asp:SiteMapDataSource</span> <span class="attr">ID</span><span class="kwrd">="SiteMapDataSource1"</span> <span class="attr">runat</span><span class="kwrd">="server"</span> <span class="attr">ShowStartingNode</span><span class="kwrd">="False"</span> <span class="kwrd">/&gt;</span></pre>
</div>
<p>If you view the page in a browser now you should see a functional, yet boring menu.</p>
<p><strong>Figure 1</strong> &#8211; Plain horizontal menu</p>
<div id="attachment_215" class="wp-caption aligncenter" style="width: 490px"><a href="http://cgeers.files.wordpress.com/2008/12/slidingdoors_menu11.gif"><img class="size-full wp-image-215" title="Sliding Doors Menu 1" src="http://cgeers.files.wordpress.com/2008/12/slidingdoors_menu11.gif?w=480&#038;h=149" alt="ASP.NET Menu control in action" width="480" height="149" /></a><p class="wp-caption-text">ASP.NET Menu control in action</p></div>
<p><a href="#top">Top of page</a></p>
<p><a title="cssfriendly" name="cssfriendly"></a><strong>CSS Friendly Adapters</strong></p>
<p>Before we can start applying CSS to the menu there is another issue that needs to be addressed first. If you take a look at the resulting HTML code that is generated when you request the default.aspx page you&#8217;ll notice that the menu control does not generate the most flexible HTML code. By default it wraps each menu item in a table. This does not lend itself for easily applying CSS. It would be better if the Menu control generated an unordererd list which contains all the menu items.</p>
<p>Luckily the generated HTML can be adjusted by using control adapters. Control adapters allow you to render the HTML you prefer. Thankfully such control adapters are readily available on <a href="http://www.codeplex.com" target="_blank">CodePlex</a>. The <a href="http://www.codeplex.com/cssfriendly" target="_blank">CSS Friendly Control Adapters kit</a> provides pre-built control adapters, including one for the ASP.NET Menu control.</p>
<p>To use the CSS Friendly Control Adapters follow these steps:</p>
<ul>
<li>Download the <a href="http://www.codeplex.com/cssfriendly/Release/ProjectReleases.aspx?ReleaseId=2159" target="_blank">latest release</a>. Download the version containing the source code and not the compiled assembly.</li>
<li>Add the downloaded project to your solution.</li>
<li>Download the <a href="http://www.codeplex.com/cssfriendly/Release/ProjectReleases.aspx?ReleaseId=2159" target="_blank">CSSFriendlyAdapters.browser</a> file and add it to the App_Browsers folder of your ASP.NET Website project.</li>
</ul>
<p>It is necessary to use the source code and compile the CSSFriendly.dll assembly ourselves because we need to tweak some of the CSS used by the adapters later on in this article.</p>
<p>When adding the CSSFriendly project to your solution the Visual Studio Conversion Wizard will popup. Just execute the conversion, everything should go smoothly. When the conversion has completed all that remains is to add a reference to the CSSFriendly project from the ASP.NET Website project.</p>
<p>Just run the website and take a look at the generated HTML code now.</p>
<p><strong>Listing 3</strong> &#8211; CSS Friendly HTML code</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre><span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="AspNet-Menu-Horizontal"</span> <span class="attr">id</span><span class="kwrd">="Menu1"</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">ul</span> <span class="attr">class</span><span class="kwrd">="AspNet-Menu"</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">li</span> <span class="attr">class</span><span class="kwrd">="AspNet-Menu-Leaf  AspNet-Menu-Selected"</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">a</span> <span class="attr">href</span><span class="kwrd">="/Default.aspx"</span> <span class="attr">class</span><span class="kwrd">="AspNet-Menu-Link  AspNet-Menu-Selected"</span> <span class="attr">title</span><span class="kwrd">="Take me back to the dasboard"</span><span class="kwrd">&gt;</span>Home<span class="kwrd">&lt;/</span><span class="html">a</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;/</span><span class="html">li</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">li</span> <span class="attr">class</span><span class="kwrd">="AspNet-Menu-Leaf"</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">a</span> <span class="attr">href</span><span class="kwrd">="/Products.aspx"</span> <span class="attr">class</span><span class="kwrd">="AspNet-Menu-Link"</span> <span class="attr">title</span><span class="kwrd">="Browse our catalog"</span><span class="kwrd">&gt;</span>Products<span class="kwrd">&lt;/</span><span class="html">a</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;/</span><span class="html">li</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">li</span> <span class="attr">class</span><span class="kwrd">="AspNet-Menu-Leaf"</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">a</span> <span class="attr">href</span><span class="kwrd">="/Download.aspx"</span> <span class="attr">class</span><span class="kwrd">="AspNet-Menu-Link"</span> <span class="attr">title</span><span class="kwrd">="Download neat stuff"</span><span class="kwrd">&gt;</span>Download<span class="kwrd">&lt;/</span><span class="html">a</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;/</span><span class="html">li</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">li</span> <span class="attr">class</span><span class="kwrd">="AspNet-Menu-Leaf"</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">a</span> <span class="attr">href</span><span class="kwrd">="/Forum.aspx"</span> <span class="attr">class</span><span class="kwrd">="AspNet-Menu-Link"</span> <span class="attr">title</span><span class="kwrd">="Ask questions on our forum"</span><span class="kwrd">&gt;</span>Forum<span class="kwrd">&lt;/</span><span class="html">a</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;/</span><span class="html">li</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">li</span> <span class="attr">class</span><span class="kwrd">="AspNet-Menu-Leaf"</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">a</span> <span class="attr">href</span><span class="kwrd">="/Contact.aspx"</span> <span class="attr">class</span><span class="kwrd">="AspNet-Menu-Link"</span> <span class="attr">title</span><span class="kwrd">="Contact us"</span><span class="kwrd">&gt;</span>Contact<span class="kwrd">&lt;/</span><span class="html">a</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;/</span><span class="html">li</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">ul</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span></pre>
</div>
<p>Things are looking up now.</p>
<p><strong><span style="text-decoration:underline;">Remark</span></strong>: The CSSFriendlyAdapters.browser file allows you to specify which CSS Friendly control adapters should be used. I make a habbit of commenting all of the adapters except the ones I want to use. This way no other controls are &#8220;adapted&#8221; and they&#8217;ll keep generating the default HTML.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="styling" name="styling"></a><strong>Styling The Menu</strong></p>
<p>As you can see from the code displayed in the listing above the adapter for the menu control automatically injects the necessary CSS classes for the &lt;ul&gt;, &lt;li&gt; and &lt;a&gt; tags. This saves us the trouble from having to define these.</p>
<p>It is also quite common for a single page to contain more than a single adapter control such as a menu. If you want a distinct look and feel for each control then set the CssSelectorClass for the adapted control. For instance, you might set the value of the CssSelectorClass property as follows:</p>
<p><strong>Listing 4</strong> &#8211; CssSelectorClass property</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre><span class="kwrd">&lt;</span><span class="html">asp:Menu</span> <span class="attr">ID</span><span class="kwrd">="Menu1"</span> <span class="attr">runat</span><span class="kwrd">="server"</span> <span class="attr">DataSourceID</span><span class="kwrd">="SitemapDataSource1"</span> <span class="attr">Orientation</span><span class="kwrd">="Horizontal"</span> <span class="attr">CssSelectorClass</span><span class="kwrd">="PrettyMenu"</span><span class="kwrd">&gt;</span></pre>
</div>
<p>The result is that the HTML code generated by the adapted control will be contained within a new layer (&lt;div&gt;).</p>
<p><strong>Listing 5</strong> &#8211; Wrapping the generated HTML code</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre><span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="PrettyMenu"</span> <span class="attr">id</span><span class="kwrd">="Menu1"</span><span class="kwrd">&gt;</span>
<span class="rem">&lt;!-- Other HTML code --&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span></pre>
</div>
<p>Note that this property is specific to the CSS Friendly Adapters. It is a custom (expando) attribute which you can set for the controls supported by this library. It you require more information about the way the Friendly Adapters work, then please consult the following links:</p>
<ul>
<li><a href="http://www.asp.net/CSSAdapters/WalkThru/WalkThrough.aspx" target="_blank">ASP.NET 2.0 CSS Friendly Control Adapters: The Walkthrough</a></li>
<li><a href="http://www.asp.net/CSSAdapters/WhitePaper.aspx" target="_blank">ASP.NET 2.0 CSS Friendly Control Adapters: The White Paper</a></li>
</ul>
<p>With the CssSelectorClass generating a separate layer (&lt;div&gt;) around the menu and the automatically injected CSS classes in place we are finally ready to commence styling the menu.</p>
<p>The CSS used is simular to that of the <a href="http://www.alistapart.com/articles/slidingdoors/" target="_blank">A List Apart article</a>. As mentioned before the focus of this article isn&#8217;t on the structure of the CSS but rather on how to apply it to the ASP.NET Menu control in order to obtain a neat looking tabular menu. The finished result can be seen in Figure 2.</p>
<p><strong>Figure 2</strong> &#8211; The Finished result</p>
<div id="attachment_251" class="wp-caption aligncenter" style="width: 490px"><a href="http://cgeers.files.wordpress.com/2008/12/slidingdoors_menu2.gif"><img class="size-full wp-image-251" title="ASP.NET Sliding Doors" src="http://cgeers.files.wordpress.com/2008/12/slidingdoors_menu2.gif?w=480&#038;h=141" alt="Fancy menu in action" width="480" height="141" /></a><p class="wp-caption-text">Fancy menu in action</p></div>
<p>On the <a href="http://cgeers.wordpress.com/download/" target="_blank">download page</a> you can find the source code for this article. It contains the style sheet and the necessary images. Just perform the following steps to recreate the finished result:</p>
<ul>
<li>Add a Theme called &#8220;Default&#8221; under the ASP.NET folder Asp_Themes</li>
<li>Add the existing images found in the compressed file containing the source code for this article under the newly create theme folder</li>
<li>Add a style sheet called global.css to the Default theme</li>
<li>Copy the contents of my global.css style sheet and paste them into your style sheet</li>
<li>Open the web.config file and set the Theme property for the &lt;Pages&gt; node to Default. (See Listing 6)</li>
</ul>
<p><strong>Listing 6</strong> &#8211; Web.config excerpt</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">system.web</span><span class="kwrd">&gt;</span>
  <span class="rem">&lt;!-- ... --&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">pages</span> <span class="attr">theme</span><span class="kwrd">="Default"</span><span class="kwrd">&gt;</span>
    <span class="rem">&lt;!-- ... --&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">pages</span><span class="kwrd">&gt;</span>
  <span class="rem">&lt;!-- ... --&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">system.web</span><span class="kwrd">&gt;</span></pre>
</div>
<p>The CSS used in my solution is simular to that of the article on A List Apart, but there are some changes. Mainly the changes correlate to the CSS structure applied by the CSS Friendly Adapters.</p>
<p>In order to apply the CSS the correct structure needs to used. When styling a control whose HTML is adjusted by a Friendly Adapter I find it handy to use diagrams mentioned in the white paper. These diagrams clearly show you how the CSS is structured.</p>
<p>You can find the diagram for the menu control <a href="http://www.asp.net/CSSAdapters/images/Whitepaper/Css_Menu.gif" target="_blank">here</a>.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="submenu" name="submenu"></a><strong>Sub Menu</strong></p>
<p>One question I frequently came accross on a lot of forums is how to implement a <span style="text-decoration:underline;">horizontal</span> sub menu which changes when the user selects a different tab from the top level menu. To create this we first need to adjust our site map.</p>
<p>Listing 7 shows the adjusted site map.</p>
<p><strong>Listing 7</strong> &#8211; Web.sitemap with &#8220;sub menu items&#8221;</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre><span class="kwrd">&lt;?</span><span class="html">xml</span> <span class="attr">version</span><span class="kwrd">="1.0"</span> <span class="attr">encoding</span><span class="kwrd">="utf-8"</span> ?<span class="kwrd">&gt;</span>
<span class="kwrd">&lt;</span><span class="html">siteMap</span> <span class="attr">xmlns</span><span class="kwrd">="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0"</span> <span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">siteMapNode</span> <span class="attr">url</span><span class="kwrd">=""</span> <span class="attr">title</span><span class="kwrd">=""</span>  <span class="attr">description</span><span class="kwrd">=""</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">siteMapNode</span> <span class="attr">url</span><span class="kwrd">="Default.aspx"</span> <span class="attr">title</span><span class="kwrd">="Home"</span>  <span class="attr">description</span><span class="kwrd">="Take me back to the dasboard"</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">siteMapNode</span> <span class="attr">url</span><span class="kwrd">="About.aspx"</span> <span class="attr">title</span><span class="kwrd">="About us"</span> <span class="attr">description</span><span class="kwrd">=""</span> <span class="kwrd">/&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">siteMapNode</span> <span class="attr">url</span><span class="kwrd">="Foo.aspx"</span> <span class="attr">title</span><span class="kwrd">="Foo"</span> <span class="attr">description</span><span class="kwrd">=""</span> <span class="kwrd">/&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">siteMapNode</span> <span class="attr">url</span><span class="kwrd">="Bar.aspx"</span> <span class="attr">title</span><span class="kwrd">="Bar"</span> <span class="attr">description</span><span class="kwrd">=""</span> <span class="kwrd">/&gt;</span>
      <span class="kwrd">&lt;/</span><span class="html">siteMapNode</span><span class="kwrd">&gt;</span>
      <span class="rem">&lt;!-- ... --&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">siteMap</span><span class="kwrd">&gt;</span></pre>
</div>
<p>For brevity&#8217;s sake Listing 7 only displays the sub menu items (nodes) for the Home node. Check out the Web.sitemap in the source code for the complete version. Now when you browse the website using this site map you&#8217;ll see the effect shown in Figure 3.</p>
<p><strong>Figure 3</strong> &#8211; Sub menu items</p>
<div id="attachment_264" class="wp-caption aligncenter" style="width: 489px"><a href="http://cgeers.files.wordpress.com/2008/12/slidingdoors_menu3.gif"><img class="size-full wp-image-264" title="Sliding Doors Menu" src="http://cgeers.files.wordpress.com/2008/12/slidingdoors_menu3.gif?w=479&#038;h=146" alt="Sub menu items in action" width="479" height="146" /></a><p class="wp-caption-text">Sub menu items in action</p></div>
<p>To disable this effect set the MaximumDynamicDisplayLevels property of the menu control to zero as shown in Listing 8.</p>
<p><strong>Listing 8</strong> &#8211; MaximumDynamicDisplayLevels property</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre><span class="kwrd">&lt;</span><span class="html">asp:Menu</span> <span class="attr">ID</span><span class="kwrd">="Menu1"</span> <span class="attr">runat</span><span class="kwrd">="server"</span> <span class="attr">DataSourceID</span><span class="kwrd">="SitemapDataSource1"</span>
          <span class="attr">Orientation</span><span class="kwrd">="Horizontal"</span> <span class="attr">CssSelectorClass</span><span class="kwrd">="PrettyMenu"</span>
          <span class="attr">MaximumDynamicDisplayLevels</span><span class="kwrd">="0"</span><span class="kwrd">&gt;</span></pre>
</div>
<p>Next add a second Menu and SiteMapDataSource control and set their properties as shown in Listing 9.</p>
<p><strong>Listing 9</strong> &#8211; Sub menu control</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">asp:Menu</span> <span class="attr">ID</span><span class="kwrd">="Menu1"</span> <span class="attr">runat</span><span class="kwrd">="server"</span> <span class="attr">DataSourceID</span><span class="kwrd">="SitemapDataSource1"</span>
    <span class="attr">Orientation</span><span class="kwrd">="Horizontal"</span> <span class="attr">CssSelectorClass</span><span class="kwrd">="PrettyMenu"</span>
    <span class="attr">MaximumDynamicDisplayLevels</span><span class="kwrd">="0"</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">asp:Menu</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;</span><span class="html">asp:Menu</span> <span class="attr">ID</span><span class="kwrd">="Menu2"</span> <span class="attr">runat</span><span class="kwrd">="server"</span> <span class="attr">DataSourceID</span><span class="kwrd">="SitemapDataSource2"</span>
    <span class="attr">Orientation</span><span class="kwrd">="Horizontal"</span> <span class="attr">CssSelectorClass</span><span class="kwrd">="PrettySubMenu"</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">asp:Menu</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;</span><span class="html">asp:SiteMapDataSource</span> <span class="attr">ID</span><span class="kwrd">="SiteMapDataSource1"</span> <span class="attr">runat</span><span class="kwrd">="server"</span> <span class="attr">ShowStartingNode</span><span class="kwrd">="False"</span> <span class="kwrd">/&gt;</span>
<span class="kwrd">&lt;</span><span class="html">asp:SiteMapDataSource</span> <span class="attr">ID</span><span class="kwrd">="SiteMapDataSource2"</span> <span class="attr">runat</span><span class="kwrd">="server"</span> <span class="attr">StartingNodeOffset</span><span class="kwrd">="1"</span> <span class="attr">ShowStartingNode</span><span class="kwrd">="False"</span> <span class="kwrd">/&gt;</span></pre>
</div>
<p>We basically tell the second menu that it should display the second level of nodes found in the site map and that it should not display the starting node which corresponds to the selected tab of the first menu.</p>
<p>Also the CssSelectorClass for the second menu is set to PrettySubMenu. The CSS for this menu is simular to the first menu. Download the source code if you want to check it out. Running the website now will give you this spiffy result.</p>
<p><strong>Figure 4</strong> &#8211; Styled sub menu items</p>
<div id="attachment_272" class="wp-caption aligncenter" style="width: 490px"><a href="http://cgeers.files.wordpress.com/2008/12/slidingdoors_menu4.gif"><img class="size-full wp-image-272" title="Sliding Doors Menu" src="http://cgeers.files.wordpress.com/2008/12/slidingdoors_menu4.gif?w=480&#038;h=159" alt="Styled Sub Menu Items" width="480" height="159" /></a><p class="wp-caption-text">Styled Sub Menu Items</p></div>
<p><a href="#top">Top of page</a></p>
<p><a title="finishingup" name="finishingup"></a><strong>Finishing Up</strong></p>
<p>One last issue needs to be resolved. In order to illustrate this issue the project needs to be reorganized.</p>
<p>First let&#8217;s add a master page to the project called Site.master. Move the code, the menus and data sources, from the Default.aspx page to the master page and place it just before the first content place holder in the body. Afterwards you can safely delete the Default.aspx page.</p>
<p>Now let&#8217;s add a few Web Content Form items to the project.  Add Web Content Forms that correspond to the items of the first node of the site map and its sub nodes, namely:</p>
<ul>
<li>Default.aspx</li>
<li>About.aspx</li>
<li>Foo.aspx</li>
<li>Bar.aspx</li>
</ul>
<p>Be sure to choose Site.master as the master page for each of these web content forms. The other pages mentioned in the Web.sitemap are purely there for illustrative purposes.</p>
<p>Launch the site again, and navigate to the Foo page. This will reveal the issue.</p>
<p><strong>Figure 5</strong> &#8211; Selection issue</p>
<div id="attachment_281" class="wp-caption aligncenter" style="width: 490px"><a href="http://cgeers.files.wordpress.com/2008/12/slidingdoors_menu5.gif"><img class="size-full wp-image-281" title="slidingdoors_menu5" src="http://cgeers.files.wordpress.com/2008/12/slidingdoors_menu5.gif?w=480&#038;h=159" alt="Which Top Level Menu is selected?" width="480" height="159" /></a><p class="wp-caption-text">Which Top Level Menu is selected?</p></div>
<p>Because we have navigated to the bottom level in the site map the top level menu does not know which menu item it should mark as selected. We will need do some coding in the master page&#8217;s code behind in order to solve this.</p>
<p>Listing 10 shows you the necessary morsel of code.</p>
<p><strong>Listing 10</strong> &#8211; Selecting the correct top level menu item</p>
<div class="csharpcode"><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre><span class="kwrd">namespace</span> MenuWebApplication
{
    <span class="kwrd">public</span> <span class="kwrd">partial</span> <span class="kwrd">class</span> Site : System.Web.UI.MasterPage
    {
        <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">string</span> ExtractBaseUrl(<span class="kwrd">string</span> url)
        {
            <span class="kwrd">return</span> url.Contains(<span class="str">"?"</span>) ? url.Remove(url.IndexOf(<span class="str">'?'</span>)) : url;
        }

        <span class="kwrd">protected</span> <span class="kwrd">void</span> Page_Load(<span class="kwrd">object</span> sender, EventArgs e)
        {
            Menu1.DataBind();

            <span class="rem">// Which node in the site map is currently selected?</span>
            SiteMapNode currentNode = SiteMap.CurrentNode;
            <span class="kwrd">if</span> (currentNode != <span class="kwrd">null</span>)
            {
                <span class="rem">// Obtain the Url of the currently selected node's parent node.</span>
                <span class="kwrd">string</span> parentUrl = String.Empty;
                SiteMapNode parentNode = currentNode.ParentNode;
                <span class="kwrd">if</span> (parentNode != <span class="kwrd">null</span>)
                {
                    parentUrl = ExtractBaseUrl(parentNode.Url);
                }

                <span class="rem">// Obtain the Url of the currently selected node.</span>
                <span class="kwrd">string</span> currentUrl = ExtractBaseUrl(currentNode.Url);

                <span class="rem">// Iterate the top level menu tier.</span>
                <span class="kwrd">foreach</span> (MenuItem menuItem <span class="kwrd">in</span> Menu1.Items)
                {
                    <span class="rem">// Compare the menu item's Url against the currently </span>
                    <span class="rem">// selected node's Url or the Url of its parent.</span>
                    <span class="kwrd">string</span> menuItemUrl = ExtractBaseUrl(menuItem.NavigateUrl);
                    <span class="kwrd">if</span> ((currentUrl == menuItemUrl) || (parentUrl == menuItemUrl))
                    {
                        <span class="rem">// If either matches then mark the top level menu item as selected.</span>
                        Menu1.Items[Menu1.Items.IndexOf(menuItem)].Selected = <span class="kwrd">true</span>;
                        <span class="kwrd">break</span>;
                    }
                }
            }
        }
    }
}</pre>
</div>
<p>Now you are free to select any of the sub menu items. It&#8217;s corresponding top level menu item will stay selected to give the visitor a visual clue as to where he currently is located within the website.</p>
<p><strong>Figure 6</strong> &#8211; Selection issue fixed</p>
<div id="attachment_286" class="wp-caption aligncenter" style="width: 490px"><a href="http://cgeers.files.wordpress.com/2008/12/slidingdoors_menu6.gif"><img class="size-full wp-image-286" title="Sliding Doors Menu" src="http://cgeers.files.wordpress.com/2008/12/slidingdoors_menu6.gif?w=480&#038;h=159" alt="Sub Menu Item Tracking" width="480" height="159" /></a><p class="wp-caption-text">Sub Menu Item Tracking</p></div>
<p><a href="#top">Top of page</a></p>
<p><a title="summary" name="summary"></a><strong>Summary</strong></p>
<p>It&#8217;s quite a bit of work to establish a fancy tabular menu with a context sensitive horizontal sub menu but in the end you wind up with a slick looking and user friendly menu.</p>
<p>I suggest that you implement such a menu in a user control and include that user control on your web site&#8217;s master page. In most cases one such menu will be used throughout the entire website.</p>
<p>If you have any comments or suggestions I&#8217;ll be glad to hear them.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="download" name="download"></a><strong>Download</strong></p>
<p>You can find the source code for this article on the <a href="http://cgeers.wordpress.com/download/" target="_blank">Download page</a> of this blog.</p>
<p><a href="#top">Top of page</a></p>
Posted in ASP.NET, C#, Programming  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/176/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/176/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cgeers.wordpress.com/176/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cgeers.wordpress.com/176/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cgeers.wordpress.com/176/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cgeers.wordpress.com/176/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cgeers.wordpress.com/176/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cgeers.wordpress.com/176/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cgeers.wordpress.com/176/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cgeers.wordpress.com/176/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.wordpress.com&blog=2504479&post=176&subd=cgeers&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://cgeers.wordpress.com/2008/12/06/aspnet-menu-sliding-doors-of-css/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1deb97b690d087dea7942250d7b03310?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2008/12/web-development.gif" medium="image">
			<media:title type="html">Web Development</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2008/12/slidingdoors_menu11.gif" medium="image">
			<media:title type="html">Sliding Doors Menu 1</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2008/12/slidingdoors_menu2.gif" medium="image">
			<media:title type="html">ASP.NET Sliding Doors</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2008/12/slidingdoors_menu3.gif" medium="image">
			<media:title type="html">Sliding Doors Menu</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2008/12/slidingdoors_menu4.gif" medium="image">
			<media:title type="html">Sliding Doors Menu</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2008/12/slidingdoors_menu5.gif" medium="image">
			<media:title type="html">slidingdoors_menu5</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2008/12/slidingdoors_menu6.gif" medium="image">
			<media:title type="html">Sliding Doors Menu</media:title>
		</media:content>
	</item>
	</channel>
</rss>