<?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>Tony Sneed&#039;s Blog</title>
	<atom:link href="http://blog.tonysneed.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.tonysneed.com</link>
	<description>A glimpse into the lives of Tony &#38; Zuzana Sneed</description>
	<lastBuildDate>Thu, 26 Jan 2012 09:42:47 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='blog.tonysneed.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://0.gravatar.com/blavatar/ccbe733658db4b886c4776fed57fcd38?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Tony Sneed&#039;s Blog</title>
		<link>http://blog.tonysneed.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://blog.tonysneed.com/osd.xml" title="Tony Sneed&#039;s Blog" />
	<atom:link rel='hub' href='http://blog.tonysneed.com/?pushpress=hub'/>
		<item>
		<title>OData, Where Art Thou?</title>
		<link>http://blog.tonysneed.com/2011/11/11/odata-where-art-thou/</link>
		<comments>http://blog.tonysneed.com/2011/11/11/odata-where-art-thou/#comments</comments>
		<pubDate>Fri, 11 Nov 2011 14:53:59 +0000</pubDate>
		<dc:creator>Tony Sneed</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[OData]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">https://tonysneed.wordpress.com/2011/11/11/odata-where-art-thou/</guid>
		<description><![CDATA[Gave a talk last night to the Dallas .NET Developer Group on OData and WCF Data Services. I’ll update this post with some info on the topic, but in the meantime you can download the slides and code for the &#8230; <a href="http://blog.tonysneed.com/2011/11/11/odata-where-art-thou/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&amp;blog=14038854&amp;post=393&amp;subd=tonysneed&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Gave a talk last night to the <a href="http://www.ddnug.net" target="_blank">Dallas .NET Developer Group</a> on <a href="http://www.odata.org/" target="_blank">OData</a> and <a href="http://msdn.microsoft.com/en-us/data/bb931106" target="_blank">WCF Data Services</a>.</p>
<p><a href="http://www.odata.org/"><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="odata-logo" border="0" alt="odata-logo" src="http://tonysneed.files.wordpress.com/2011/11/odata-logo.png?w=323&#038;h=39" width="323" height="39"></a></p>
<p>I’ll update this post with some info on the topic, but in the meantime you can download the slides and code for the talk here: <a title="http://bit.ly/odata-talk" href="http://bit.ly/odata-talk">http://bit.ly/odata-talk</a>. Enjoy.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tonysneed.wordpress.com/393/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tonysneed.wordpress.com/393/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tonysneed.wordpress.com/393/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tonysneed.wordpress.com/393/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tonysneed.wordpress.com/393/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tonysneed.wordpress.com/393/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tonysneed.wordpress.com/393/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tonysneed.wordpress.com/393/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tonysneed.wordpress.com/393/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tonysneed.wordpress.com/393/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tonysneed.wordpress.com/393/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tonysneed.wordpress.com/393/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tonysneed.wordpress.com/393/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tonysneed.wordpress.com/393/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&amp;blog=14038854&amp;post=393&amp;subd=tonysneed&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.tonysneed.com/2011/11/11/odata-where-art-thou/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/878b354347e93c317b20a2a540f3ce04?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tonysneed</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/11/odata-logo.png" medium="image">
			<media:title type="html">odata-logo</media:title>
		</media:content>
	</item>
		<item>
		<title>More NLog Goodness</title>
		<link>http://blog.tonysneed.com/2011/10/31/more-nlog-goodness/</link>
		<comments>http://blog.tonysneed.com/2011/10/31/more-nlog-goodness/#comments</comments>
		<pubDate>Mon, 31 Oct 2011 13:42:04 +0000</pubDate>
		<dc:creator>Tony Sneed</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[NLog]]></category>

		<guid isPermaLink="false">https://tonysneed.wordpress.com/?p=384</guid>
		<description><![CDATA[This is a follow-up to my post on Using NLog with Dependency Injection.&#160; There I showed how you can abstract away a specific logging implementation from your application by implementing a common interface and using a DI container, such as &#8230; <a href="http://blog.tonysneed.com/2011/10/31/more-nlog-goodness/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&amp;blog=14038854&amp;post=384&amp;subd=tonysneed&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This is a follow-up to my post on <a href="http://blog.tonysneed.com/2011/10/09/using-nlog-with-dependency-injection/" target="_blank">Using NLog with Dependency Injection</a>.&nbsp; There I showed how you can abstract away a specific logging implementation from your application by implementing a common interface and using a DI container, such as Ninject or StructureMap, to resolve the concrete implementation at runtime.&nbsp; This time around, I thought I would call out a few more features of NLog which I found useful.</p>
<p><em>Download the </em><a href="http://tonysneed.com/download/ninject-nlog.zip" target="_blank"><em>code</em></a><em> for this blog post.</em></p>
<p>One of the most common uses of logging is to record log entries in a database table. NLog has an interesting feature that allows you to include the table definition in your NLog.config file and run a command-line utility to create the database and logging table, as well as set up other targets, such as a Windows Event Log or performance counters.&nbsp; To take advantage of this feature, you need to run the NLog installer, which you can download from <a href="http://nlog.codeplex.com/releases/view/32639" target="_blank">here</a>.&nbsp; This will give you the documentation, Visual Studio item templates for sample configuration files, schemas for XML intellisense in config files, extended layout renderers, and the config-driven installer utility.</p>
<p><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="nlog-items" border="0" alt="nlog-items" src="http://tonysneed.files.wordpress.com/2011/10/nlog-items.jpg?w=612&#038;h=403" width="612" height="403"></p>
<p>To find these goodies, you need to go to the directory where NLog is installed after running the setup program, which is probably <strong>&#8220;%ProgramFiles(x86)%\NLog\.NET Framework 4.0&#8243;</strong>.</p>
<p><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="nlog-install-dir" border="0" alt="nlog-install-dir" src="http://tonysneed.files.wordpress.com/2011/10/nlog-install-dir.jpg?w=505&#038;h=366" width="505" height="366"></p>
<p>A common question is where to place the NLog config file.&nbsp; There are a number of <a href="http://nlog-project.org/wiki/Configuration_file#Configuration_file_locations" target="_blank">options</a>.&nbsp; If you want to perform logging at the class library level, and perhaps have a logging test project, you may want to place the NLog.config at the solution level, and link to it from projects where you want to perform logging.&nbsp; To do this, right-click on the project and select Add Existing Item.&nbsp; Then navigate to the solution directory where you placed the NLog.config file and, instead of clicking the Add button, select the drop-down on the Add button and choose <strong>Add As Link</strong>.</p>
<p><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="add-as-link" border="0" alt="add-as-link" src="http://tonysneed.files.wordpress.com/2011/11/add-as-link.jpg?w=597&#038;h=365" width="597" height="365"></p>
<p>Then select properties for the linked file and set <strong>Copy to Output Directory</strong> to “Copy Always.”</p>
<p><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="nlog-props" border="0" alt="nlog-props" src="http://tonysneed.files.wordpress.com/2011/11/nlog-props.jpg?w=372&#038;h=216" width="372" height="216"></p>
<p>For web apps, you’ll probably need to have a physical NLog.config file in the root directory (with Copy to Output Directory set to “Do Not Copy”), because placing the file in the bin directory does not seem to work (regardless of what the documentation states).</p>
<p>One change I wanted to make to my log output is to include the <strong>identity</strong> of the current user.&nbsp; If you look at the list of <a href="http://nlog-project.org/wiki/Layout_renderers" target="_blank">built-in layout renderers</a>, you’ll find the <a href="http://nlog-project.org/wiki/Identity_layout_renderer" target="_blank">${identity}</a> tag, which provides the identity of the thread’s current principal.</p>
<pre class="code"><span style="color:blue;">static void </span>Main(<span style="color:blue;">string</span>[] args)
{
    <span style="color:green;">// Set user identity
    </span><span style="color:#2b91af;">Thread</span>.CurrentPrincipal = <span style="color:blue;">new </span><span style="color:#2b91af;">WindowsPrincipal</span>(<span style="color:#2b91af;">WindowsIdentity</span>.GetCurrent());

    <span style="color:green;">// Other code follows ...
</span>}</pre>
<p>In web applications, this will give you the application pool’s identity rather the end user’s identity.&nbsp; The <a href="http://nlog-project.org/wiki/Aspnet-user-identity_layout_renderer" target="_blank">${aspnet-user-identity}</a> tag will return the identity of the logged on user, but you can use only this tag if you reference the <strong>NLog.Extended.dll</strong> assembly.&nbsp; If you’re using NLog via NuGet, add the <strong>NLog for Extended Profile</strong> package, which will add the reference.</p>
<p><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="nlog-ext" border="0" alt="nlog-ext" src="http://tonysneed.files.wordpress.com/2011/10/nlog-ext.jpg?w=619&#038;h=331" width="619" height="331"></p>
<p>For an ASP.NET MVC app, you’ll need to include pieces from the <em>Internet Application</em> MVC3 template to enable users to authenticate via a LogOn view.</p>
<p><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="mvc-int" border="0" alt="mvc-int" src="http://tonysneed.files.wordpress.com/2011/10/mvc-int.jpg?w=484&#038;h=440" width="484" height="440"></p>
<p>All you have to do to log on is run the app and register as a new user.&nbsp; A database will be created according to the “ApplicationServices” connection string in web.config.</p>
<p><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="asp-user-reg" border="0" alt="asp-user-reg" src="http://tonysneed.files.wordpress.com/2011/11/asp-user-reg.jpg?w=488&#038;h=421" width="488" height="421"></p>
<p>The next piece is enabling <strong>database logging</strong>. For this you simply create a logging target with xsi:type=&#8221;Database&#8221;.&nbsp; One of the issues I ran into is specifying the date-time in a format SQL Server understands. The <a href="http://nlog-project.org/wiki/Date_layout_renderer" target="_blank">${date}</a> tag accepts a format parameter that can be any argument accepted by DateTime.ToString(format). I found the standard “s” <a href="http://msdn.microsoft.com/en-us/library/az4se3k1.aspx#Sortable" target="_blank">Sortable Format Specifier</a> to be a good choice.</p>
<pre class="code"><span style="color:blue;">&lt;</span><span style="color:#a31515;">target </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">database</span>"
        <span style="color:red;">xsi:type</span><span style="color:blue;">=</span>"<span style="color:blue;">Database</span>"<span style="color:blue;">&gt;

  &lt;!-- </span><span style="color:green;">SQL command to be executed for each entry </span><span style="color:blue;">--&gt;
  &lt;</span><span style="color:#a31515;">commandText</span><span style="color:blue;">&gt;</span>INSERT INTO LogEvent(EventDateTime, EventLevel, UserName, MachineName, EventMessage, ErrorSource, ErrorClass, ErrorMethod, ErrorMessage, InnerErrorMessage) VALUES(@EventDateTime, @EventLevel, @UserName, @MachineName, @EventMessage, @ErrorSource, @ErrorClass, @ErrorMethod, @ErrorMessage, @InnerErrorMessage)<span style="color:blue;">&lt;/</span><span style="color:#a31515;">commandText</span><span style="color:blue;">&gt;

  &lt;!-- </span><span style="color:green;">parameters for the command </span><span style="color:blue;">--&gt;
  &lt;</span><span style="color:#a31515;">parameter </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">@EventDateTime</span>" <span style="color:red;">layout</span><span style="color:blue;">=</span>"<span style="color:blue;">${date:s}</span>" <span style="color:blue;">/&gt;
  &lt;</span><span style="color:#a31515;">parameter </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">@EventLevel</span>" <span style="color:red;">layout</span><span style="color:blue;">=</span>"<span style="color:blue;">${level}</span>" <span style="color:blue;">/&gt;
  &lt;</span><span style="color:#a31515;">parameter </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">@UserName</span>" <span style="color:red;">layout</span><span style="color:blue;">=</span>"<span style="color:blue;">${identity}</span>" <span style="color:blue;">/&gt;
  &lt;</span><span style="color:#a31515;">parameter </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">@MachineName</span>" <span style="color:red;">layout</span><span style="color:blue;">=</span>"<span style="color:blue;">${machinename}</span>" <span style="color:blue;">/&gt;
  &lt;</span><span style="color:#a31515;">parameter </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">@EventMessage</span>" <span style="color:red;">layout</span><span style="color:blue;">=</span>"<span style="color:blue;">${message}</span>" <span style="color:blue;">/&gt;
  &lt;</span><span style="color:#a31515;">parameter </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">@ErrorSource</span>" <span style="color:red;">layout</span><span style="color:blue;">=</span>"<span style="color:blue;">${event-context:item=error-source}</span>" <span style="color:blue;">/&gt;
  &lt;</span><span style="color:#a31515;">parameter </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">@ErrorClass</span>" <span style="color:red;">layout</span><span style="color:blue;">=</span>"<span style="color:blue;">${event-context:item=error-class}</span>" <span style="color:blue;">/&gt;
  &lt;</span><span style="color:#a31515;">parameter </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">@ErrorMethod</span>" <span style="color:red;">layout</span><span style="color:blue;">=</span>"<span style="color:blue;">${event-context:item=error-method}</span>" <span style="color:blue;">/&gt;
  &lt;</span><span style="color:#a31515;">parameter </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">@ErrorMessage</span>" <span style="color:red;">layout</span><span style="color:blue;">=</span>"<span style="color:blue;">${event-context:item=error-message}</span>" <span style="color:blue;">/&gt;
  &lt;</span><span style="color:#a31515;">parameter </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">@InnerErrorMessage</span>" <span style="color:red;">layout</span><span style="color:blue;">=</span>"<span style="color:blue;">${event-context:item=inner-error-message}</span>" <span style="color:blue;">/&gt;

  &lt;!-- </span><span style="color:green;">connection string </span><span style="color:blue;">--&gt;
  &lt;</span><span style="color:#a31515;">dbProvider</span><span style="color:blue;">&gt;</span>System.Data.SqlClient<span style="color:blue;">&lt;/</span><span style="color:#a31515;">dbProvider</span><span style="color:blue;">&gt;
  &lt;</span><span style="color:#a31515;">connectionString</span><span style="color:blue;">&gt;</span>Data Source=.\SQLEXPRESS;Initial Catalog=Logging;Integrated Security=True<span style="color:blue;">&lt;/</span><span style="color:#a31515;">connectionString</span><span style="color:blue;">&gt;

&lt;/</span><span style="color:#a31515;">target</span><span style="color:blue;">&gt;</span></pre>
<p>If you try running this straight away, you won’t notice anything unusual, even though no database logging has taken place – because you haven’t even created the database!&nbsp; If you want to find out if there’s a problem with logging, one thing you can do is configure the logger to throw exceptions.&nbsp; This will cause an exception to be raised in the logger if NLog cannot initialize a target, but problems writing to the database won’t come up. For that you’ll want to log internal NLog exceptions.</p>
<p><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="nlog-console-error" border="0" alt="nlog-console-error" src="http://tonysneed.files.wordpress.com/2011/11/nlog-console-error.jpg?w=620&#038;h=248" width="620" height="248"></p>
<p>You can log them to the console, but in a real-world scenario, you’ll want to log NLog internal errors to a text file.&nbsp; That way, you can inspect it on the server where your app is deployed.</p>
<pre class="code"><span style="color:blue;">&lt;</span><span style="color:#a31515;">nlog </span><span style="color:red;">xmlns</span><span style="color:blue;">=</span>"<span style="color:blue;">http://www.nlog-project.org/schemas/NLog.xsd</span>"
      <span style="color:red;">xmlns:xsi</span><span style="color:blue;">=</span>"<span style="color:blue;">http://www.w3.org/2001/XMLSchema-instance</span>"
      <span style="color:red;">throwExceptions</span><span style="color:blue;">=</span>"<span style="color:blue;">true</span>"
      <span style="color:red;">internalLogLevel</span><span style="color:blue;">=</span>"<span style="color:blue;">Error</span>"
      <span style="color:red;">internalLogFile</span><span style="color:blue;">=</span>"<span style="color:blue;">..\..\..\nlog-app.log</span>"<span style="color:blue;">&gt;</span></pre>
<p>This relative path will place the log in the solution directory for the project.&nbsp; However, the location of the internal log file for a web app will need to be determined at runtime, based on Server.MapPath.&nbsp; This means you’ll need to set the log file path in the Application_Start method of Global.asax.cs.</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">MvcApplication </span>: System.Web.HttpApplication
{
    <span style="color:blue;">protected void </span>Application_Start()
    {
        <span style="color:blue;">string </span>nlogPath = Server.MapPath(<span style="color:#a31515;">"nlog-web.log"</span>);
        InternalLogger.LogFile = nlogPath;
    }
}</pre>
<p>Now that we can see errors generated by NLog, we need to create the database and table where we want to store our logs.&nbsp; NLog comes with a handy command-line tool called <strong>InstallNLogConfig.exe</strong>, which you can run on your NLog.config file.&nbsp; If the config file includes information about the definition of the database table, this tool will create the table for you.&nbsp; You can even have it drop and re-create the logging database.&nbsp; The tool will also create the windows event log or performance counters if those targets are specified.</p>
<pre class="code"><span style="color:blue;">&lt;!-- </span><span style="color:green;">command to install logging database </span><span style="color:blue;">--&gt;
&lt;</span><span style="color:#a31515;">install-command</span><span style="color:blue;">&gt;
  &lt;</span><span style="color:#a31515;">text</span><span style="color:blue;">&gt;</span>CREATE DATABASE Logging<span style="color:blue;">&lt;/</span><span style="color:#a31515;">text</span><span style="color:blue;">&gt;
  &lt;</span><span style="color:#a31515;">connectionString</span><span style="color:blue;">&gt;</span>Data Source=.\SQLEXPRESS;Initial Catalog=Master;Integrated Security=True<span style="color:blue;">&lt;/</span><span style="color:#a31515;">connectionString</span><span style="color:blue;">&gt;
  &lt;</span><span style="color:#a31515;">ignoreFailures</span><span style="color:blue;">&gt;</span>true<span style="color:blue;">&lt;/</span><span style="color:#a31515;">ignoreFailures</span><span style="color:blue;">&gt;
&lt;/</span><span style="color:#a31515;">install-command</span><span style="color:blue;">&gt;

&lt;!-- </span><span style="color:green;">command to create logging table </span><span style="color:blue;">--&gt;
&lt;</span><span style="color:#a31515;">install-command</span><span style="color:blue;">&gt;
  &lt;</span><span style="color:#a31515;">text</span><span style="color:blue;">&gt;
    </span>CREATE TABLE LogEvent(
    EventId int primary key not null identity(1,1),
    EventDateTime datetime,
    EventLevel nvarchar(50),
    UserName nvarchar(50),
    MachineName nvarchar(1024),
    EventMessage nvarchar(MAX),
    ErrorSource nvarchar(1024),
    ErrorClass nvarchar(1024),
    ErrorMethod nvarchar(1024),
    ErrorMessage nvarchar(MAX),
    InnerErrorMessage nvarchar(MAX))
  <span style="color:blue;">&lt;/</span><span style="color:#a31515;">text</span><span style="color:blue;">&gt;
&lt;/</span><span style="color:#a31515;">install-command</span><span style="color:blue;">&gt;

&lt;!-- </span><span style="color:green;">command to drop logging database </span><span style="color:blue;">--&gt;
&lt;</span><span style="color:#a31515;">uninstall-command</span><span style="color:blue;">&gt;
  &lt;</span><span style="color:#a31515;">text</span><span style="color:blue;">&gt;</span>DROP DATABASE Logging<span style="color:blue;">&lt;/</span><span style="color:#a31515;">text</span><span style="color:blue;">&gt;
  &lt;</span><span style="color:#a31515;">connectionString</span><span style="color:blue;">&gt;</span>Data Source=.\SQLEXPRESS;Initial Catalog=Master;Integrated Security=True<span style="color:blue;">&lt;/</span><span style="color:#a31515;">connectionString</span><span style="color:blue;">&gt;
  &lt;</span><span style="color:#a31515;">ignoreFailures</span><span style="color:blue;">&gt;</span>true<span style="color:blue;">&lt;/</span><span style="color:#a31515;">ignoreFailures</span><span style="color:blue;">&gt;
&lt;/</span><span style="color:#a31515;">uninstall-command</span><span style="color:blue;">&gt;</span></pre>
<p>Logging is one of those things we can take for granted – until we need it.&nbsp; NLog is a nice tool that can provide logging to multiple targets.&nbsp; I’ve just scratched the surface on what NLog can do.&nbsp; For more info, check out the NLog <a href="http://nlog-project.org/wiki/Documentation" target="_blank">docs</a> and download the NLog <a href="https://github.com/jkowalski/NLog/" target="_blank">source code</a>, which includes some good examples.&nbsp; You can download the code for this post <a href="http://tonysneed.com/download/ninject-nlog.zip" target="_blank">here</a>.&nbsp; Enjoy.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tonysneed.wordpress.com/384/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tonysneed.wordpress.com/384/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tonysneed.wordpress.com/384/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tonysneed.wordpress.com/384/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tonysneed.wordpress.com/384/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tonysneed.wordpress.com/384/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tonysneed.wordpress.com/384/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tonysneed.wordpress.com/384/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tonysneed.wordpress.com/384/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tonysneed.wordpress.com/384/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tonysneed.wordpress.com/384/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tonysneed.wordpress.com/384/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tonysneed.wordpress.com/384/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tonysneed.wordpress.com/384/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&amp;blog=14038854&amp;post=384&amp;subd=tonysneed&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.tonysneed.com/2011/10/31/more-nlog-goodness/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/878b354347e93c317b20a2a540f3ce04?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tonysneed</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/10/nlog-items.jpg" medium="image">
			<media:title type="html">nlog-items</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/10/nlog-install-dir.jpg" medium="image">
			<media:title type="html">nlog-install-dir</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/11/add-as-link.jpg" medium="image">
			<media:title type="html">add-as-link</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/11/nlog-props.jpg" medium="image">
			<media:title type="html">nlog-props</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/10/nlog-ext.jpg" medium="image">
			<media:title type="html">nlog-ext</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/10/mvc-int.jpg" medium="image">
			<media:title type="html">mvc-int</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/11/asp-user-reg.jpg" medium="image">
			<media:title type="html">asp-user-reg</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/11/nlog-console-error.jpg" medium="image">
			<media:title type="html">nlog-console-error</media:title>
		</media:content>
	</item>
		<item>
		<title>Using Ninject with WCF Services</title>
		<link>http://blog.tonysneed.com/2011/10/24/using-ninject-with-wcf-services/</link>
		<comments>http://blog.tonysneed.com/2011/10/24/using-ninject-with-wcf-services/#comments</comments>
		<pubDate>Mon, 24 Oct 2011 14:07:52 +0000</pubDate>
		<dc:creator>Tony Sneed</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[DI]]></category>
		<category><![CDATA[Ninject]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">https://tonysneed.wordpress.com/2011/10/24/using-ninject-with-wcf-services/</guid>
		<description><![CDATA[Download the code for this post. In my post on the Onion Architecture I highlight the use of Dependency Injection to loosen the coupling between application components.&#160; In an ASP.NET MVC application, it is possible to use repositories directly from &#8230; <a href="http://blog.tonysneed.com/2011/10/24/using-ninject-with-wcf-services/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&amp;blog=14038854&amp;post=379&amp;subd=tonysneed&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>Download the <a href="http://tonysneed.com/download/ninject-wcf.zip" target="_blank">code</a> for this post.</em></p>
<p>In my <a href="http://blog.tonysneed.com/2011/10/08/peeling-back-the-onion-architecture/" target="_blank">post</a> on the Onion Architecture I highlight the use of Dependency Injection to loosen the coupling between application components.&nbsp; In an ASP.NET MVC application, it is possible to use repositories directly from controllers, but it may be desirable to place a WCF services façade over the data access layer, so that other kinds of clients, such as Silverlight or WPF, won’t directly access the database.&nbsp; This is commonly referred to as an n-tier application architecture.</p>
<p>For a service type to rely on a DI container for a repository interface, it would likely have a constructor that accepts an I_X_Repository parameter.</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">GreetingService </span>: <span style="color:#2b91af;">IGreetingService
</span>{
    <span style="color:blue;">private </span><span style="color:#2b91af;">IGreetingRepository </span>_greetingRepo;

    <span style="color:blue;">public </span>GreetingService(<span style="color:#2b91af;">IGreetingRepository </span>greetingRepo)
    {
        _greetingRepo = greetingRepo;
    }

    <span style="color:blue;">public string </span>Hello()
    {
        <span style="color:blue;">return </span>_greetingRepo.GetGreeting();
    }
}</pre>
<p>However, using this service type will result in an error:<em> “The service type provided could not be loaded as a service because it does not have a default (parameter-less) constructor.”</em></p>
<p><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="service-error" border="0" alt="service-error" src="http://tonysneed.files.wordpress.com/2011/10/service-error.jpg?w=634&#038;h=336" width="634" height="336"></p>
<p>To remedy this, you can use a custom instance provider to obtain the GreetingService from a DI container.&nbsp; Thankfully, there is a NuGet package available that provides this service: <strong>Ninject.Extensions.Wcf</strong>.</p>
<p><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="ninject-wcf" border="0" alt="ninject-wcf" src="http://tonysneed.files.wordpress.com/2011/10/ninject-wcf.jpg?w=629&#038;h=364" width="629" height="364"></p>
<p>To use this for a non-web host, set the KernelContainer’s Kernel property to an kernel initialized with a Ninject module that binds your types and interfaces.&nbsp; Then use NinjectServiceHost in lieu of ServiceHost.</p>
<pre class="code"><span style="color:blue;">class </span><span style="color:#2b91af;">Program
</span>{
    <span style="color:blue;">static void </span>Main(<span style="color:blue;">string</span>[] args)
    {
        <span style="color:green;">// Init Ninject
        </span><span style="color:#2b91af;">IKernel </span>kernel = <span style="color:blue;">new </span><span style="color:#2b91af;">StandardKernel</span>(<span style="color:blue;">new </span><span style="color:#2b91af;">HelloModule</span>());
        <span style="color:#2b91af;">KernelContainer</span>.Kernel = kernel;

        <span style="color:green;">// Create service host
        </span><span style="color:blue;">using </span>(<span style="color:blue;">var </span>host = <span style="color:blue;">new </span><span style="color:#2b91af;">NinjectServiceHost</span>(<span style="color:blue;">typeof</span>(<span style="color:#2b91af;">GreetingService</span>),
            <span style="color:blue;">new </span><span style="color:#2b91af;">Uri</span>(<span style="color:#a31515;">"http://localhost:1234/GreetingService"</span>)))
        {
            host.Open();
            <span style="color:#2b91af;">Console</span>.ReadKey();
        }
    }
}</pre>
<p>The HelloModule binds both IGreetingRepository and ServiceHost.</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">HelloModule </span>: <span style="color:#2b91af;">NinjectModule
</span>{
    <span style="color:blue;">public override void </span>Load()
    {
        Kernel.Bind&lt;<span style="color:#2b91af;">IGreetingRepository</span>&gt;().To&lt;<span style="color:#2b91af;">GreetingRepository</span>&gt;();
        Kernel.Bind&lt;<span style="color:#2b91af;">ServiceHost</span>&gt;().To&lt;<span style="color:#2b91af;">NinjectServiceHost</span>&gt;();
    }
}</pre>
<p>In the .svc file for a web host, you would set the Factory property to <strong>NinjectServiceHostFactory</strong>.</p>
<pre class="code"><span style="background:yellow;">&lt;%</span><span style="color:blue;">@ </span><span style="color:maroon;">ServiceHost </span><span style="color:red;">Service</span><span style="color:blue;">="HelloNinjectWcf.Service.GreetingService"
    </span><span style="color:red;">Factory</span><span style="color:blue;">="Ninject.Extensions.Wcf.NinjectServiceHostFactory" </span><span style="background:yellow;">%&gt;</span></pre>
<p>Then add a Global.asax file that extends <strong>NinjectWcfApplication</strong> and overrides <strong>CreateKernel</strong> to return an initialized Ninject kernel.</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">Global </span>: <span style="color:#2b91af;">NinjectWcfApplication
</span>{
    <span style="color:blue;">protected override </span><span style="color:#2b91af;">IKernel </span>CreateKernel()
    {
        <span style="color:#2b91af;">IKernel </span>kernel = <span style="color:blue;">new </span><span style="color:#2b91af;">StandardKernel</span>(<span style="color:blue;">new </span><span style="color:#2b91af;">HelloModule</span>());
        <span style="color:blue;">return </span>kernel;
    }
}</pre>
<p>This works great for configuring a WCF service to use dependency injection, but there are times when you might need to spin up a WCF service for an integration test using a testing framework such as NUnit or MSTest.&nbsp; This can get rather tedious, especially with DI in the mix.&nbsp; For that reason, it’s convenient to use a helper class responsible for initializing both service host and client.&nbsp; (Disclaimer: I have to credit my friend, Pete Young, for coming up with a <a href="https://github.com/peteyoung/ServiceHostHelper" target="_blank">helper</a> that does this same sort of thing.)</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">NinjectServiceHelper</span>&lt;TServiceContract, TServiceType&gt; : <span style="color:#2b91af;">IDisposable
</span>{
    <span style="color:blue;">bool </span>_disposed;

    <span style="color:blue;">public </span>NinjectServiceHelper(<span style="color:blue;">string </span>address, <span style="color:#2b91af;">Binding </span>binding, <span style="color:blue;">params </span><span style="color:#2b91af;">Uri</span>[] baseAddresses)
    {
        <span style="color:green;">// Init Ninject service host
        </span>_serviceHost = <span style="color:blue;">new </span><span style="color:#2b91af;">NinjectServiceHost</span>(<span style="color:blue;">typeof</span>(TServiceType), baseAddresses);
        _serviceHost.AddServiceEndpoint(<span style="color:blue;">typeof</span>(TServiceContract), binding, address);
        _serviceHost.Open();

        <span style="color:green;">// Init client
        </span><span style="color:blue;">var </span>factory = <span style="color:blue;">new </span><span style="color:#2b91af;">ChannelFactory</span>&lt;TServiceContract&gt;(binding);
        _client = factory.CreateChannel(<span style="color:blue;">new </span><span style="color:#2b91af;">EndpointAddress</span>(address));
    }

    <span style="color:blue;">private readonly </span><span style="color:#2b91af;">ServiceHost </span>_serviceHost;
    <span style="color:blue;">public </span><span style="color:#2b91af;">ServiceHost </span>ServiceHost
    {
        <span style="color:blue;">get
        </span>{
            <span style="color:blue;">if </span>(_disposed)
                <span style="color:blue;">throw new </span><span style="color:#2b91af;">ObjectDisposedException</span>(<span style="color:#a31515;">"NinjectServiceHelper"</span>);
            <span style="color:blue;">return </span>_serviceHost;
        }
    }

    <span style="color:blue;">private readonly </span>TServiceContract _client;
    <span style="color:blue;">public </span>TServiceContract Client
    {
        <span style="color:blue;">get
        </span>{
            <span style="color:blue;">if </span>(_disposed)
                <span style="color:blue;">throw new </span><span style="color:#2b91af;">ObjectDisposedException</span>(<span style="color:#a31515;">"NinjectServiceHelper"</span>);
            <span style="color:blue;">return </span>_client;
        }
    }

    <span style="color:blue;">public void </span>Dispose()
    {
        <span style="color:blue;">if </span>(!_disposed)
        {
            ((<span style="color:#2b91af;">IDisposable</span>)_serviceHost).Dispose();
            ((<span style="color:#2b91af;">IDisposable</span>)_client).Dispose();
            _disposed = <span style="color:blue;">true</span>;
        }
    }
}</pre>
<p>The code in the Test class then becomes nice and clean.</p>
<pre class="code">[<span style="color:#2b91af;">TestFixture</span>]
<span style="color:blue;">public class </span><span style="color:#2b91af;">GreetingServiceTests
</span>{
    <span style="color:blue;">private </span><span style="color:#2b91af;">NinjectServiceHelper</span>&lt;<span style="color:#2b91af;">IGreetingService</span>, <span style="color:#2b91af;">GreetingService</span>&gt; _serviceHelper;

    [<span style="color:#2b91af;">TestFixtureSetUp</span>]
    <span style="color:blue;">public void </span>FixtureSetup()
    {
        <span style="color:green;">// Init Ninject
        </span><span style="color:#2b91af;">IKernel </span>kernel = <span style="color:blue;">new </span><span style="color:#2b91af;">StandardKernel</span>(<span style="color:blue;">new </span><span style="color:#2b91af;">HelloModule</span>());
        <span style="color:#2b91af;">KernelContainer</span>.Kernel = kernel;

        <span style="color:green;">// Create service host
        </span>_serviceHelper = <span style="color:blue;">new </span><span style="color:#2b91af;">NinjectServiceHelper</span>&lt;<span style="color:#2b91af;">IGreetingService</span>, <span style="color:#2b91af;">GreetingService</span>&gt;
            (<span style="color:#a31515;">"http://localhost:2345/GreetingService"</span>, <span style="color:blue;">new </span><span style="color:#2b91af;">BasicHttpBinding</span>());
    }

    [<span style="color:#2b91af;">TestFixtureTearDown</span>]
    <span style="color:blue;">public void </span>FixtureTearDown()
    {
        ((<span style="color:#2b91af;">IDisposable</span>)_serviceHelper).Dispose();
    }

    [<span style="color:#2b91af;">Test</span>]
    <span style="color:blue;">public void </span>Greeting_Method_Should_Return_Hello()
    {
        <span style="color:#2b91af;">IGreetingService </span>client = _serviceHelper.Client;
        <span style="color:blue;">using </span>((<span style="color:#2b91af;">IDisposable</span>)client)
        {
            <span style="color:blue;">string </span>greeting = client.Hello();
            <span style="color:#2b91af;">Assert</span>.That(greeting, <span style="color:#2b91af;">Is</span>.StringMatching(<span style="color:#a31515;">"Hello"</span>));
        }
    }
}</pre>
<p><a href="https://github.com/ninject/ninject.extensions.wcf" target="_blank">Ninject.Extensions.Wcf</a> makes it easy to leverage Ninject for dependency injection with WCF services.&nbsp; My <strong>NinjectServiceHelper</strong> makes it easier to write integration tests that spin up the service and at the same time provides a client for invoking methods on the service and writing asserts on the results.&nbsp; You can download the code for this blog post <a href="http://tonysneed.com/download/ninject-wcf.zip" target="_blank">here</a>.&nbsp; Enjoy.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tonysneed.wordpress.com/379/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tonysneed.wordpress.com/379/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tonysneed.wordpress.com/379/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tonysneed.wordpress.com/379/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tonysneed.wordpress.com/379/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tonysneed.wordpress.com/379/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tonysneed.wordpress.com/379/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tonysneed.wordpress.com/379/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tonysneed.wordpress.com/379/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tonysneed.wordpress.com/379/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tonysneed.wordpress.com/379/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tonysneed.wordpress.com/379/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tonysneed.wordpress.com/379/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tonysneed.wordpress.com/379/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&amp;blog=14038854&amp;post=379&amp;subd=tonysneed&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.tonysneed.com/2011/10/24/using-ninject-with-wcf-services/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/878b354347e93c317b20a2a540f3ce04?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tonysneed</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/10/service-error.jpg" medium="image">
			<media:title type="html">service-error</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/10/ninject-wcf.jpg" medium="image">
			<media:title type="html">ninject-wcf</media:title>
		</media:content>
	</item>
		<item>
		<title>Global Error Handling in ASP.NET MVC 3 with Ninject</title>
		<link>http://blog.tonysneed.com/2011/10/21/global-error-handling-in-asp-net-mvc-3-with-ninject/</link>
		<comments>http://blog.tonysneed.com/2011/10/21/global-error-handling-in-asp-net-mvc-3-with-ninject/#comments</comments>
		<pubDate>Fri, 21 Oct 2011 12:49:16 +0000</pubDate>
		<dc:creator>Tony Sneed</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[ASP.NET-MVC]]></category>
		<category><![CDATA[DI]]></category>
		<category><![CDATA[Nin]]></category>
		<category><![CDATA[NLog]]></category>

		<guid isPermaLink="false">https://tonysneed.wordpress.com/2011/10/21/global-error-handling-in-asp-net-mvc-3-with-ninject/</guid>
		<description><![CDATA[Download the code for this blog post. In my last blog post I explained how to decouple infrastructure concerns, such as logging, from the rest of your application using a Dependency Injection container, such as Ninject. I implemented an ILoggingService &#8230; <a href="http://blog.tonysneed.com/2011/10/21/global-error-handling-in-asp-net-mvc-3-with-ninject/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&amp;blog=14038854&amp;post=376&amp;subd=tonysneed&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>Download the <a href="http://tonysneed.com/download/exception-handling.zip" target="_blank">code</a> for this blog post.</em></p>
<p>In my <a href="http://blog.tonysneed.com/2011/10/09/using-nlog-with-dependency-injection" target="_blank">last blog post</a> I explained how to decouple infrastructure concerns, such as logging, from the rest of your application using a <a href="http://msdn.microsoft.com/en-us/magazine/cc163739.aspx" target="_blank">Dependency Injection</a> container, such as <a href="http://ninject.org/" target="_blank">Ninject</a>. I implemented an ILoggingService interface with an open-source logger called <a href="http://nlog-project.org/" target="_blank">NLog</a>.&nbsp; In this post I will show you how to implement centralized error handling in an ASP.NET MVC 3 application, so that you can handle exceptions in one place, where you can perform logging as well as display a custom error page.</p>
<p>One of the worst things you can do to handle errors is place a try / catch block in every action of every controller.&nbsp; Not only does it clutter the app with unnecessary code, it creates the possibility that you or another developer will forget to place the try / catch on an action and an unexpected exception will slip through.</p>
<p>A better approach is to handle exceptions in one place through an interception mechanism.&nbsp; <a href="http://www.asp.net/mvc" target="_blank">ASP.NET MVC</a> allows you to hook into the request pipeline by defining an <a href="http://msdn.microsoft.com/en-us/library/gg416513(v=vs.98).aspx" target="_blank">Action Filter</a>.&nbsp; In fact, one such filter that comes out of the box is a <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.handleerrorattribute(v=vs.98).aspx" target="_blank">HandleError</a> attribute.&nbsp; While it allows you to direct users to a particular view when certain errors occur, you cannot use it to log the exception.&nbsp; The other problem is that you would have to place the attribute on every controller in your application – not much of an improvement over a proliferation of try / catch’s.</p>
<p>It turns out, however, that implementing <strong>IExceptionFilter</strong> is quite easy (especially if you use <a href="http://www.reflector.net/" target="_blank">Reflector</a> to reverse engineer HandleErrorAttribute <img style="border-style:none;" class="wlEmoticon wlEmoticon-winkingsmile" alt="Winking smile" src="http://tonysneed.files.wordpress.com/2011/10/wlemoticon-winkingsmile.png?w=500">).&nbsp; The difference is that you can add a constructor which accepts an ILoggingService interface and is injected into the filter by your DI container.&nbsp; The nice thing about Ninject is that there is an <a href="http://nuget.org/List/Packages/Ninject.MVC3" target="_blank">extension</a> for MVC3 apps, which you can easily add as a <a href="http://nuget.org/" target="_blank">NuGet</a> package.&nbsp; After installing the package, you get a <strong>NinjectMVC3.cs</strong> file placed in an App_Start folder with bootstrapping code.&nbsp; There you can load a Ninject module for binding the ILoggingSservice to a concrete implementation.&nbsp; I had to hunt for the source code and documentation for the Ninject.MVC3 extension, but I eventually found it <a href="https://github.com/ninject/ninject.web.mvc/wiki/MVC3" target="_blank">here</a> on <a href="https://github.com/" target="_blank">Github</a>.</p>
<p>I implemented IExceptionFilter in a <strong>HandleExceptionFilter</strong> class, which performs logging in addition to creating a ViewResult with a custom error view.</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">HandleExceptionFilter </span>: <span style="color:#2b91af;">IExceptionFilter
</span>{
    <span style="color:blue;">private string </span>_view;
    <span style="color:blue;">private string </span>_master;
    <span style="color:blue;">private </span><span style="color:#2b91af;">ILoggingService </span>_loggingService;

    <span style="color:blue;">public </span>HandleExceptionFilter(<span style="color:#2b91af;">ILoggingService </span>loggingService, <span style="color:blue;">string </span>master, <span style="color:blue;">string </span>view)
    {
        _loggingService = loggingService;
        _master = master ?? <span style="color:blue;">string</span>.Empty;
        _view = view ?? <span style="color:blue;">string</span>.Empty;
    }

    <span style="color:blue;">public virtual void </span>OnException(<span style="color:#2b91af;">ExceptionContext </span>filterContext)
    {
        <span style="color:blue;">if </span>(filterContext == <span style="color:blue;">null</span>)
        {
            <span style="color:blue;">throw new </span><span style="color:#2b91af;">ArgumentNullException</span>(<span style="color:#a31515;">"filterContext"</span>);
        }

        <span style="color:blue;">if </span>(!filterContext.IsChildAction &amp;&amp; (!filterContext.ExceptionHandled
            &amp;&amp; filterContext.HttpContext.IsCustomErrorEnabled))
            {
            <span style="color:#2b91af;">Exception </span>exception = filterContext.Exception;
            <span style="color:blue;">if </span>((<span style="color:blue;">new </span><span style="color:#2b91af;">HttpException</span>(<span style="color:blue;">null</span>, exception).GetHttpCode() == 500))
            {
                <span style="color:green;">// Log exception
                </span>_loggingService.Error(exception);

                <span style="color:green;">// Show error view
                </span><span style="color:#2b91af;">ErrorFilterHelper</span>.SetFilerContext(filterContext, _master, _view);
            }
        }
    }
}</pre>
<p>I consolidated code to show the error view in an <strong>ErrorFilterHelper</strong>. </p>
<pre class="code"><span style="color:blue;">internal static class </span><span style="color:#2b91af;">ErrorFilterHelper
</span>{
    <span style="color:blue;">public static void </span>SetFilerContext(<span style="color:#2b91af;">ExceptionContext </span>filterContext, <span style="color:blue;">string </span>master, <span style="color:blue;">string </span>view)
    {
        <span style="color:green;">// Show error view
        </span><span style="color:blue;">string </span>controllerName = (<span style="color:blue;">string</span>)filterContext.RouteData.Values[<span style="color:#a31515;">"controller"</span>];
        <span style="color:blue;">string </span>actionName = (<span style="color:blue;">string</span>)filterContext.RouteData.Values[<span style="color:#a31515;">"action"</span>];
        <span style="color:blue;">var </span>model = <span style="color:blue;">new </span><span style="color:#2b91af;">HandleErrorInfo</span>(filterContext.Exception, controllerName, actionName);
        <span style="color:blue;">var </span>result = <span style="color:blue;">new </span><span style="color:#2b91af;">ViewResult
        </span>{
            ViewName = view,
            MasterName = master,
            ViewData = <span style="color:blue;">new </span><span style="color:#2b91af;">ViewDataDictionary</span>&lt;<span style="color:#2b91af;">HandleErrorInfo</span>&gt;(model),
            TempData = filterContext.Controller.TempData
        };
        filterContext.Result = result;
        filterContext.ExceptionHandled = <span style="color:blue;">true</span>;
        filterContext.HttpContext.Response.Clear();
        filterContext.HttpContext.Response.StatusCode = 200;
        filterContext.HttpContext.Response.TrySkipIisCustomErrors = <span style="color:blue;">true</span>;
    }
}</pre>
<p>The next issue is how to insert HandleExceptionFilter into the pipeline.&nbsp; Luckily Ninject.MVC3 comes with a <strong>BindFilter</strong> extension method which allows you to bind action filters to classes implementing IActionFilter.&nbsp; To use it simply add a using directive for Ninject.Web.Mvc.FilterBindingSyntax, then supply a type argument for your filter.</p>
<pre class="code"><span style="color:blue;">private static void </span>RegisterServices(<span style="color:#2b91af;">IKernel </span>kernel)
{
    <span style="color:green;">// Load logging module
    </span>kernel.Load(<span style="color:blue;">new </span><span style="color:#2b91af;">LoggingModule</span>());

    <span style="color:green;">// Bind exception handling filter
    </span><strong>kernel.BindFilter&lt;<span style="color:#2b91af;">HandleExceptionFilter</span>&gt;</strong>(<span style="color:#2b91af;">FilterScope</span>.Global, 0)
        .When(r =&gt; <span style="color:blue;">true</span>)
        .WithConstructorArgument(<span style="color:#a31515;">"master"</span>, <span style="color:blue;">string</span>.Empty)
        .WithConstructorArgument(<span style="color:#a31515;">"view"</span>, <span style="color:#a31515;">"Error"</span>);
}</pre>
<p>Unhandled exceptions will now be routed to the HandleExceptionFilter, which will log the exception and take the user to the “Error” view.</p>
<p>This covers all unexpected exceptions.&nbsp; But what if you want to show a different view for particular exceptions?&nbsp; For this you will need to create a class that extends <strong>FilterAttribute</strong> and has an ExceptionType property.&nbsp; In this case you will want to use an <em>injected property</em> rather than an overloaded constructor.&nbsp; You will also want to set the Order property to greater than zero, so that it will intercept and deal with errors before your global error handling filter.</p>
<pre class="code">[<span style="color:#2b91af;">AttributeUsage</span>(<span style="color:#2b91af;">AttributeTargets</span>.Method | <span style="color:#2b91af;">AttributeTargets</span>.Class, Inherited = <span style="color:blue;">true</span>, AllowMultiple = <span style="color:blue;">true</span>)]
<span style="color:blue;">public class </span><span style="color:#2b91af;">HandleExceptionAttribute </span>: <span style="color:#2b91af;">FilterAttribute</span>, <span style="color:#2b91af;">IExceptionFilter
</span>{
    <span style="color:blue;">public </span>HandleExceptionAttribute()
    {
        <span style="color:green;">// Errors come here before other error filters
        </span>Order = 1;
    }

    [<span style="color:#2b91af;">Inject</span>]
    <span style="color:blue;">public </span><span style="color:#2b91af;">ILoggingService </span>LoggingService { <span style="color:blue;">private get</span>; <span style="color:blue;">set</span>; }

    <span style="color:blue;">public virtual void </span>OnException(<span style="color:#2b91af;">ExceptionContext </span>filterContext)
    {</pre>
<p>Now you can place the <strong>HandleException</strong> attribute on an action, indicating the specific exception type you want to handle, and the name of the view you want to show the user.&nbsp; If another exception occurs, HandleErrorFilter will log the error and show the default Error view.</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">HomeController </span>: <span style="color:#2b91af;">Controller
</span>{
<span style="color:green;">    // GET: /
    // ?errorcode=1
    </span><strong>[<span style="color:#2b91af;">HandleException</span>(ExceptionType = <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">CustomException</span>), View=<span style="color:#a31515;">"CustomError"</span>)]
</strong>    <span style="color:blue;">public </span><span style="color:#2b91af;">ActionResult </span>Index(<span style="color:blue;">int</span>? errorCode)
    {
        <span style="color:blue;">switch </span>(errorCode.GetValueOrDefault())
        {
            <span style="color:blue;">case </span>1:
                <span style="color:green;">// This code will result in a DivideByZeroException
                // No need for try/catch because exception filter will handle it
                </span><span style="color:blue;">int </span>a = 1;
                <span style="color:blue;">int </span>b = 0;
                <span style="color:blue;">int </span>result = a / b;
                <span style="color:blue;">break</span>;
            <span style="color:blue;">case </span>2:
                <span style="color:blue;">throw new </span><span style="color:#2b91af;">CustomException</span>(<span style="color:#a31515;">"Expected Error"</span>);
        }
        <span style="color:blue;">return </span>View();
    }
}</pre>
<p>In this example, the CustomException thrown in case 2 will be intercepted by HandleExceptionAttribute, where it will be logged and the exception marked as handled.&nbsp; The user will then see the “CustomError” view specified as a parameter for the HandleException attribute that appears on the Home controller’s Index action. But the DivideByZeroException, which is unexpected, will be handled by the HandleErrorFilter, which will log the exception and show the default “Error” view.&nbsp; To enable error filters, you need to set the mode of the &lt;customErrors&gt; element in web.config to “On” (set it to “RemoteOnly” if you want the unhandled exception to appear in the “Yellow Screen of Death.”)</p>
<p>You can download the code for this blog post <a href="http://tonysneed.com/download/exception-handling.zip" target="_blank">here</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tonysneed.wordpress.com/376/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tonysneed.wordpress.com/376/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tonysneed.wordpress.com/376/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tonysneed.wordpress.com/376/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tonysneed.wordpress.com/376/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tonysneed.wordpress.com/376/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tonysneed.wordpress.com/376/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tonysneed.wordpress.com/376/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tonysneed.wordpress.com/376/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tonysneed.wordpress.com/376/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tonysneed.wordpress.com/376/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tonysneed.wordpress.com/376/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tonysneed.wordpress.com/376/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tonysneed.wordpress.com/376/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&amp;blog=14038854&amp;post=376&amp;subd=tonysneed&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.tonysneed.com/2011/10/21/global-error-handling-in-asp-net-mvc-3-with-ninject/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/878b354347e93c317b20a2a540f3ce04?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tonysneed</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/10/wlemoticon-winkingsmile.png" medium="image">
			<media:title type="html">Winking smile</media:title>
		</media:content>
	</item>
		<item>
		<title>Using NLog with Dependency Injection</title>
		<link>http://blog.tonysneed.com/2011/10/09/using-nlog-with-dependency-injection/</link>
		<comments>http://blog.tonysneed.com/2011/10/09/using-nlog-with-dependency-injection/#comments</comments>
		<pubDate>Sun, 09 Oct 2011 19:46:48 +0000</pubDate>
		<dc:creator>Tony Sneed</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[DI]]></category>
		<category><![CDATA[Ninject]]></category>
		<category><![CDATA[NLog]]></category>

		<guid isPermaLink="false">https://tonysneed.wordpress.com/2011/10/09/using-nlog-with-dependency-injection/</guid>
		<description><![CDATA[Download the code for this blog post. In my last post I blogged about using Dependency Injection to break tight coupling between application components.&#160; This lets you to treat infrastructure pieces, such as data access or logging, as swappable entities, &#8230; <a href="http://blog.tonysneed.com/2011/10/09/using-nlog-with-dependency-injection/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&amp;blog=14038854&amp;post=373&amp;subd=tonysneed&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>Download the <a href="http://tonysneed.com/download/ninject-nlog.zip">code</a> for this blog post.</em></p>
<p>In my <a href="http://blog.tonysneed.com/2011/10/08/peeling-back-the-onion-architecture/">last post</a> I blogged about using <a href="http://martinfowler.com/articles/injection.html">Dependency Injection</a> to break tight coupling between application components.&nbsp; This lets you to treat infrastructure pieces, such as data access or logging, as swappable entities, allowing your application to change with the times as new technology stacks replace obsolete or deprecated ones.</p>
<p><a href="http://nlog-project.org/" target="_blank"><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="NLog" border="0" alt="NLog" src="http://tonysneed.files.wordpress.com/2011/10/nlog.png?w=377&#038;h=99" width="377" height="99"></a></p>
<p>In this blog post I will share how I took an open-source logging framework, called <a href="http://nlog-project.org/">NLog</a>, and made it injectable by an DI (Ioc) container, such as <a href="http://ninject.org/">Ninject</a>.&nbsp; There’s no reason you couldn’t apply this same technique with other logging frameworks, such as <a href="http://www.google.com/url?sa=t&amp;source=web&amp;cd=1&amp;ved=0CCkQFjAA&amp;url=http%3A%2F%2Flogging.apache.org%2Flog4net%2F&amp;ei=YO-RTtGHG5CHsAK-p93DAQ&amp;usg=AFQjCNEdDcVKM8X4j-ILZQt9pLW1G13vdA&amp;sig2=JWhCbCn9h_Pht12S_Fb1kw">Log4Net</a>, or DI containers, such as <a href="http://www.google.com/url?sa=t&amp;source=web&amp;cd=1&amp;sqi=2&amp;ved=0CCMQFjAA&amp;url=http%3A%2F%2Fstructuremap.net%2Fstructuremap%2F&amp;ei=dO-RTtKZHOaksQKX6fyZAQ&amp;usg=AFQjCNFr57xobjMgTLoFvHJIXdnrC--NiA&amp;sig2=B35Ow5zdxdKJm9KRmmVtgg">StructureMap</a>.</p>
<p><a href="http://ninject.org/" target="_blank"><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="ninject-logo" border="0" alt="ninject-logo" src="http://tonysneed.files.wordpress.com/2011/10/ninject-logo.jpg?w=458&#038;h=197" width="458" height="197"></a></p>
<p>Before I set out, I searched for an existing solution and found <a href="http://nuget.org/List/Packages/Ninject.Extensions.Logging.nlog2">Ninject.Extensions.Logging.nlog2</a> in the <a href="http://nuget.org/">NuGet</a> online gallery.&nbsp; However, when I applied the solution I ran into a <a href="https://github.com/ninject/ninject.extensions.logging/issues/4">security exception</a> that stopped me in my tracks. (The author as promised to fix it in the next version but has not set a timeline.)&nbsp; In addition, I found some shortcomings in how NLog records exception details and ended up building a thin wrapper that provides richer information on exceptions, such as the assembly, class and method in which the exception occurred.</p>
<p>My first order of business was to create an <strong>ILoggingService</strong> interface, so as to decouple consumers from the actual logging framework.</p>
<pre class="code"><span style="color:blue;">public interface </span><span style="color:#2b91af;">ILoggingService
</span>{
    <span style="color:blue;">bool </span>IsDebugEnabled { <span style="color:blue;">get</span>; }
    <span style="color:blue;">bool </span>IsErrorEnabled { <span style="color:blue;">get</span>; }
    <span style="color:blue;">bool </span>IsFatalEnabled { <span style="color:blue;">get</span>; }
    <span style="color:blue;">bool </span>IsInfoEnabled { <span style="color:blue;">get</span>; }
    <span style="color:blue;">bool </span>IsTraceEnabled { <span style="color:blue;">get</span>; }
    <span style="color:blue;">bool </span>IsWarnEnabled { <span style="color:blue;">get</span>; }

    <span style="color:blue;">void </span>Debug(<span style="color:#2b91af;">Exception </span>exception);
    <span style="color:blue;">void </span>Debug(<span style="color:blue;">string </span>format, <span style="color:blue;">params object</span>[] args);
    <span style="color:blue;">void </span>Debug(<span style="color:#2b91af;">Exception </span>exception, <span style="color:blue;">string </span>format, <span style="color:blue;">params object</span>[] args);
    <span style="color:blue;">void </span>Error(<span style="color:#2b91af;">Exception </span>exception);
    <span style="color:blue;">void </span>Error(<span style="color:blue;">string </span>format, <span style="color:blue;">params object</span>[] args);
    <span style="color:blue;">void </span>Error(<span style="color:#2b91af;">Exception </span>exception, <span style="color:blue;">string </span>format, <span style="color:blue;">params object</span>[] args);
    <span style="color:blue;">void </span>Fatal(<span style="color:#2b91af;">Exception </span>exception);
    <span style="color:blue;">void </span>Fatal(<span style="color:blue;">string </span>format, <span style="color:blue;">params object</span>[] args);
    <span style="color:blue;">void </span>Fatal(<span style="color:#2b91af;">Exception </span>exception, <span style="color:blue;">string </span>format, <span style="color:blue;">params object</span>[] args);
    <span style="color:blue;">void </span>Info(<span style="color:#2b91af;">Exception </span>exception);
    <span style="color:blue;">void </span>Info(<span style="color:blue;">string </span>format, <span style="color:blue;">params object</span>[] args);
    <span style="color:blue;">void </span>Info(<span style="color:#2b91af;">Exception </span>exception, <span style="color:blue;">string </span>format, <span style="color:blue;">params object</span>[] args);
    <span style="color:blue;">void </span>Trace(<span style="color:#2b91af;">Exception </span>exception);
    <span style="color:blue;">void </span>Trace(<span style="color:blue;">string </span>format, <span style="color:blue;">params object</span>[] args);
    <span style="color:blue;">void </span>Trace(<span style="color:#2b91af;">Exception </span>exception, <span style="color:blue;">string </span>format, <span style="color:blue;">params object</span>[] args);
    <span style="color:blue;">void </span>Warn(<span style="color:#2b91af;">Exception </span>exception);
    <span style="color:blue;">void </span>Warn(<span style="color:blue;">string </span>format, <span style="color:blue;">params object</span>[] args);
    <span style="color:blue;">void </span>Warn(<span style="color:#2b91af;">Exception </span>exception, <span style="color:blue;">string </span>format, <span style="color:blue;">params object</span>[] args);
}</pre>
<p>I then implemented the interface in a <strong>LoggingService</strong> class, placing it in a separate assembly than ILoggingService, so that consumers could reference the interface without referencing the implementation assembly, which included some custom layout renderers for UTC dates and web variables (borrowed from <a href="http://dotnetdarren.wordpress.com/2010/07/28/logging-in-mvc-part-3-%E2%80%93-nlog/">here</a>).&nbsp; I also had to call an overload of the Log method that accepts the custom logger type so that NLog would ignore the logger when analyzing the call stack.</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">LoggingService </span>: NLog.<span style="color:#2b91af;">Logger</span>, <span style="color:#2b91af;">ILoggingService
</span>{
    <span style="color:blue;">private const string </span>_loggerName = <span style="color:#a31515;">"NLogLogger"</span>;

    <span style="color:blue;">public static </span><span style="color:#2b91af;">ILoggingService </span>GetLoggingService()
    {
        <span style="color:#2b91af;">ConfigurationItemFactory</span>.Default.LayoutRenderers
            .RegisterDefinition(<span style="color:#a31515;">"utc_date"</span>, <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">UtcDateRenderer</span>));
        <span style="color:#2b91af;">ConfigurationItemFactory</span>.Default.LayoutRenderers
            .RegisterDefinition(<span style="color:#a31515;">"web_variables"</span>, <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">WebVariablesRenderer</span>));
        <span style="color:#2b91af;">ILoggingService </span>logger = (<span style="color:#2b91af;">ILoggingService</span>)<span style="color:#2b91af;">LogManager</span>.GetLogger(<span style="color:#a31515;">"NLogLogger"</span>, <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">LoggingService</span>));
        <span style="color:blue;">return </span>logger;
    }

    <span style="color:blue;">public void </span>Debug(<span style="color:#2b91af;">Exception </span>exception, <span style="color:blue;">string </span>format, <span style="color:blue;">params object</span>[] args)
    {
        <span style="color:blue;">if </span>(!<span style="color:blue;">base</span>.IsDebugEnabled) <span style="color:blue;">return</span>;
        <span style="color:blue;">var </span>logEvent = GetLogEvent(_loggerName, <span style="color:#2b91af;">LogLevel</span>.Debug, exception, format, args);
        <span style="color:blue;">base</span>.Log(<span style="color:blue;">typeof</span>(<span style="color:#2b91af;">LoggingService</span>), logEvent);
    }

    <span style="color:blue;">public void </span>Error(<span style="color:#2b91af;">Exception </span>exception, <span style="color:blue;">string </span>format, <span style="color:blue;">params object</span>[] args)
    {
        <span style="color:blue;">if </span>(!<span style="color:blue;">base</span>.IsErrorEnabled) <span style="color:blue;">return</span>;
        <span style="color:blue;">var </span>logEvent = GetLogEvent(_loggerName, <span style="color:#2b91af;">LogLevel</span>.Error, exception, format, args);
        <span style="color:blue;">base</span>.Log(<span style="color:blue;">typeof</span>(<span style="color:#2b91af;">LoggingService</span>), logEvent);
    }

    <span style="color:blue;">public void </span>Fatal(<span style="color:#2b91af;">Exception </span>exception, <span style="color:blue;">string </span>format, <span style="color:blue;">params object</span>[] args)
    {
        <span style="color:blue;">if </span>(!<span style="color:blue;">base</span>.IsFatalEnabled) <span style="color:blue;">return</span>;
        <span style="color:blue;">var </span>logEvent = GetLogEvent(_loggerName, <span style="color:#2b91af;">LogLevel</span>.Fatal, exception, format, args);
        <span style="color:blue;">base</span>.Log(<span style="color:blue;">typeof</span>(<span style="color:#2b91af;">LoggingService</span>), logEvent);
    }

    <span style="color:blue;">public void </span>Info(<span style="color:#2b91af;">Exception </span>exception, <span style="color:blue;">string </span>format, <span style="color:blue;">params object</span>[] args)
    {
        <span style="color:blue;">if </span>(!<span style="color:blue;">base</span>.IsInfoEnabled) <span style="color:blue;">return</span>;
        <span style="color:blue;">var </span>logEvent = GetLogEvent(_loggerName, <span style="color:#2b91af;">LogLevel</span>.Info, exception, format, args);
        <span style="color:blue;">base</span>.Log(<span style="color:blue;">typeof</span>(<span style="color:#2b91af;">LoggingService</span>), logEvent);
    }

    <span style="color:blue;">public void </span>Trace(<span style="color:#2b91af;">Exception </span>exception, <span style="color:blue;">string </span>format, <span style="color:blue;">params object</span>[] args)
    {
        <span style="color:blue;">if </span>(!<span style="color:blue;">base</span>.IsTraceEnabled) <span style="color:blue;">return</span>;
        <span style="color:blue;">var </span>logEvent = GetLogEvent(_loggerName, <span style="color:#2b91af;">LogLevel</span>.Trace, exception, format, args);
        <span style="color:blue;">base</span>.Log(<span style="color:blue;">typeof</span>(<span style="color:#2b91af;">LoggingService</span>), logEvent);
    }

    <span style="color:blue;">public void </span>Warn(<span style="color:#2b91af;">Exception </span>exception, <span style="color:blue;">string </span>format, <span style="color:blue;">params object</span>[] args)
    {
        <span style="color:blue;">if </span>(!<span style="color:blue;">base</span>.IsWarnEnabled) <span style="color:blue;">return</span>;
        <span style="color:blue;">var </span>logEvent = GetLogEvent(_loggerName, <span style="color:#2b91af;">LogLevel</span>.Warn, exception, format, args);
        <span style="color:blue;">base</span>.Log(<span style="color:blue;">typeof</span>(<span style="color:#2b91af;">LoggingService</span>), logEvent);
    }

    <span style="color:blue;">public void </span>Debug(<span style="color:#2b91af;">Exception </span>exception)
    {
        <span style="color:blue;">this</span>.Debug(exception, <span style="color:blue;">string</span>.Empty);
    }

    <span style="color:blue;">public void </span>Error(<span style="color:#2b91af;">Exception </span>exception)
    {
        <span style="color:blue;">this</span>.Error(exception, <span style="color:blue;">string</span>.Empty);
    }

    <span style="color:blue;">public void </span>Fatal(<span style="color:#2b91af;">Exception </span>exception)
    {
        <span style="color:blue;">this</span>.Fatal(exception, <span style="color:blue;">string</span>.Empty);
    }

    <span style="color:blue;">public void </span>Info(<span style="color:#2b91af;">Exception </span>exception)
    {
        <span style="color:blue;">this</span>.Info(exception, <span style="color:blue;">string</span>.Empty);
    }

    <span style="color:blue;">public void </span>Trace(<span style="color:#2b91af;">Exception </span>exception)
    {
        <span style="color:blue;">this</span>.Trace(exception, <span style="color:blue;">string</span>.Empty);
    }

    <span style="color:blue;">public void </span>Warn(<span style="color:#2b91af;">Exception </span>exception)
    {
        <span style="color:blue;">this</span>.Warn(exception, <span style="color:blue;">string</span>.Empty);
    }

    <span style="color:blue;">private </span><span style="color:#2b91af;">LogEventInfo </span>GetLogEvent(<span style="color:blue;">string </span>loggerName, <span style="color:#2b91af;">LogLevel </span>level, <span style="color:#2b91af;">Exception </span>exception, <span style="color:blue;">string </span>format, <span style="color:blue;">object</span>[] args)
    {
        <span style="color:blue;">string </span>assemblyProp = <span style="color:blue;">string</span>.Empty;
        <span style="color:blue;">string </span>classProp = <span style="color:blue;">string</span>.Empty;
        <span style="color:blue;">string </span>methodProp = <span style="color:blue;">string</span>.Empty;
        <span style="color:blue;">string </span>messageProp = <span style="color:blue;">string</span>.Empty;
        <span style="color:blue;">string </span>innerMessageProp = <span style="color:blue;">string</span>.Empty;

        <span style="color:blue;">var </span>logEvent = <span style="color:blue;">new </span><span style="color:#2b91af;">LogEventInfo
            </span>(level, loggerName, <span style="color:blue;">string</span>.Format(format, args));

        <span style="color:blue;">if </span>(exception != <span style="color:blue;">null</span>)
        {
            assemblyProp = exception.Source;
            classProp = exception.TargetSite.DeclaringType.FullName;
            methodProp = exception.TargetSite.Name;
            messageProp = exception.Message;

            <span style="color:blue;">if </span>(exception.InnerException != <span style="color:blue;">null</span>)
            {
                innerMessageProp = exception.InnerException.Message;
            }
        }

        logEvent.Properties[<span style="color:#a31515;">"error-source"</span>] = assemblyProp;
        logEvent.Properties[<span style="color:#a31515;">"error-class"</span>] = classProp;
        logEvent.Properties[<span style="color:#a31515;">"error-method"</span>] = methodProp;
        logEvent.Properties[<span style="color:#a31515;">"error-message"</span>] = messageProp;
        logEvent.Properties[<span style="color:#a31515;">"inner-error-message"</span>] = innerMessageProp;

        <span style="color:blue;">return </span>logEvent;
    }
}</pre>
<p>The Visual Studio solution includes a DependencyResolution project in the solution with a <strong>NinjectModule</strong> class that binds ILoggingService to the concrete LoggingService implementation. It turns out that the NLog.config file needs to be placed in the same directory as this assembly’s dll, by setting the “Copy to Output Directory” property of the file to “Copy Always.”&nbsp; While I could have created a custom exception renderer, I simply used the convenient <a href="http://nlog-project.org/wiki/Event-context_layout_renderer">Event-context</a> layout renderer.</p>
<pre class="code"><span style="color:blue;">&lt;?</span><span style="color:#a31515;">xml </span><span style="color:red;">version</span><span style="color:blue;">=</span>"<span style="color:blue;">1.0</span>" <span style="color:red;">encoding</span><span style="color:blue;">=</span>"<span style="color:blue;">utf-8</span>" <span style="color:blue;">?&gt;
&lt;</span><span style="color:#a31515;">nlog </span><span style="color:red;">xmlns</span><span style="color:blue;">=</span>"<span style="color:blue;">http://www.nlog-project.org/schemas/NLog.xsd</span>"
      <span style="color:red;">xmlns:xsi</span><span style="color:blue;">=</span>"<span style="color:blue;">http://www.w3.org/2001/XMLSchema-instance</span>"<span style="color:blue;">&gt;

  &lt;!-- </span><span style="color:green;">make sure to set 'Copy To Output Directory' option for this file </span><span style="color:blue;">--&gt;
  &lt;!-- </span><span style="color:green;">go to http://nlog-project.org/wiki/Configuration_file for more information </span><span style="color:blue;">--&gt;

  &lt;</span><span style="color:#a31515;">targets</span><span style="color:blue;">&gt;
    &lt;</span><span style="color:#a31515;">target </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">console</span>"
            <span style="color:red;">xsi:type</span><span style="color:blue;">=</span>"<span style="color:blue;">ColoredConsole</span>"
            <span style="color:red;">layout</span><span style="color:blue;">=</span>"<span style="color:blue;">Server-Date: ${longdate}; UTC-Date: ${utc_date}; Level: ${level}; Log-Message: ${message}; Error-Source: ${event-context:item=error-source}; Error-Class: ${event-context:item=error-class}; Error-Method: ${event-context:item=error-method}; Error-Message: ${event-context:item=error-message}; Inner-Error-Message: ${event-context:item=inner-error-message}</span>" <span style="color:blue;">/&gt;
    &lt;</span><span style="color:#a31515;">target </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">debug</span>"
            <span style="color:red;">xsi:type</span><span style="color:blue;">=</span>"<span style="color:blue;">Debugger</span>"
            <span style="color:red;">layout</span><span style="color:blue;">=</span>"<span style="color:blue;">Server-Date: ${longdate}; UTC-Date: ${utc_date}; Level: ${level}; Log-Message: ${message}; Error-Source: ${event-context:item=error-source}; Error-Class: ${event-context:item=error-class}; Error-Method: ${event-context:item=error-method}; Error-Message: ${event-context:item=error-message}; Inner-Error-Message: ${event-context:item=inner-error-message}</span>" <span style="color:blue;">/&gt;
  &lt;/</span><span style="color:#a31515;">targets</span><span style="color:blue;">&gt;

  &lt;</span><span style="color:#a31515;">rules</span><span style="color:blue;">&gt;
    &lt;</span><span style="color:#a31515;">logger </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">*</span>"
            <span style="color:red;">minlevel</span><span style="color:blue;">=</span>"<span style="color:blue;">Trace</span>"
            <span style="color:red;">writeTo</span><span style="color:blue;">=</span>"<span style="color:blue;">console,debug</span>" <span style="color:blue;">/&gt;
  &lt;/</span><span style="color:#a31515;">rules</span><span style="color:blue;">&gt;
&lt;/</span><span style="color:#a31515;">nlog</span><span style="color:blue;">&gt;</span></pre>
<p>I created a simple console app to test the logger by newing up a widget and calling a method that throws an exception.</p>
<pre class="code"><span style="color:blue;">class </span><span style="color:#2b91af;">Program
</span>{
    <span style="color:blue;">static void </span>Main(<span style="color:blue;">string</span>[] args)
    {
        <span style="color:#2b91af;">IKernel </span>kernel = <span style="color:blue;">new </span><span style="color:#2b91af;">StandardKernel</span>(<span style="color:blue;">new </span><span style="color:#2b91af;">LoggingModule</span>());

        <span style="color:blue;">var </span>provider = kernel.Get&lt;<span style="color:#2b91af;">WidgetProvider</span>&gt;();

        <span style="color:blue;">var </span>widget = <span style="color:blue;">new </span><span style="color:#2b91af;">Widget</span>();

        provider.UseWidget(widget);

        <span style="color:#2b91af;">Console</span>.WriteLine(<span style="color:#a31515;">"Press Enter to Exit"</span>);
        <span style="color:#2b91af;">Console</span>.ReadLine();
    }
}</pre>
<p>The UseWidget method catches an exception thrown by the Widget.Foo method, calling ILoggingService.Error and passing the exception.</p>
<p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">WidgetProvider
</span>{
    <span style="color:blue;">private readonly </span><strong><span style="color:#2b91af;">ILoggingService </span>_logger</strong>;

    <span style="color:blue;">public </span>WidgetProvider(<strong><span style="color:#2b91af;">ILoggingService </span>logger</strong>)
    {
        _logger = logger;
    }

    <span style="color:blue;">public void </span>UseWidget(<span style="color:#2b91af;">Widget </span>widget)
    {
        <span style="color:blue;">try
        </span>{
            widget.Foo();
        }
        <span style="color:blue;">catch </span>(<span style="color:#2b91af;">Exception </span>ex)
        {
            <strong><font>_logger.Error(ex);</font></strong>
        }
    }
}</pre>
</p>
<p>Here is the exception thrown by Widget.Foo:</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">Widget
</span>{
    <span style="color:blue;">public void </span>Foo()
    {
        <span style="color:blue;">throw new </span><span style="color:#2b91af;">Exception</span>(<span style="color:#a31515;">"Never divide by zero"</span>,
            <span style="color:blue;">new </span><span style="color:#2b91af;">DivideByZeroException</span>());
    }
}</pre>
<p>Running the console app produces the following output from the “console” logging target:</p>
<p><a href="http://tonysneed.files.wordpress.com/2011/10/console-err-log.jpg"><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="console-err-log" border="0" alt="console-err-log" src="http://tonysneed.files.wordpress.com/2011/10/console-err-log_thumb.jpg?w=641&#038;h=147" width="641" height="147"></a></p>
<p>The Debug window shows the output of the “debug” logging target:</p>
<p><a href="http://tonysneed.files.wordpress.com/2011/10/debug-err-log.jpg"><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="debug-err-log" border="0" alt="debug-err-log" src="http://tonysneed.files.wordpress.com/2011/10/debug-err-log_thumb.jpg?w=632&#038;h=80" width="632" height="80"></a></p>
<p>Application components can log messages or exceptions using the injected ILoggingService interface.&nbsp; You can download the code for this blog post <a href="http://tonysneed.com/download/ninject-nlog.zip">here</a>.&nbsp; Enjoy.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tonysneed.wordpress.com/373/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tonysneed.wordpress.com/373/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tonysneed.wordpress.com/373/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tonysneed.wordpress.com/373/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tonysneed.wordpress.com/373/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tonysneed.wordpress.com/373/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tonysneed.wordpress.com/373/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tonysneed.wordpress.com/373/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tonysneed.wordpress.com/373/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tonysneed.wordpress.com/373/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tonysneed.wordpress.com/373/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tonysneed.wordpress.com/373/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tonysneed.wordpress.com/373/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tonysneed.wordpress.com/373/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&amp;blog=14038854&amp;post=373&amp;subd=tonysneed&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.tonysneed.com/2011/10/09/using-nlog-with-dependency-injection/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/878b354347e93c317b20a2a540f3ce04?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tonysneed</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/10/nlog.png" medium="image">
			<media:title type="html">NLog</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/10/ninject-logo.jpg" medium="image">
			<media:title type="html">ninject-logo</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/10/console-err-log_thumb.jpg" medium="image">
			<media:title type="html">console-err-log</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/10/debug-err-log_thumb.jpg" medium="image">
			<media:title type="html">debug-err-log</media:title>
		</media:content>
	</item>
		<item>
		<title>Peeling Back the Onion Architecture</title>
		<link>http://blog.tonysneed.com/2011/10/08/peeling-back-the-onion-architecture/</link>
		<comments>http://blog.tonysneed.com/2011/10/08/peeling-back-the-onion-architecture/#comments</comments>
		<pubDate>Sat, 08 Oct 2011 21:39:35 +0000</pubDate>
		<dc:creator>Tony Sneed</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[ASP.NET-MVC]]></category>
		<category><![CDATA[DI]]></category>
		<category><![CDATA[MOQ]]></category>
		<category><![CDATA[Ninject]]></category>

		<guid isPermaLink="false">https://tonysneed.wordpress.com/2011/10/08/peeling-back-the-onion-architecture/</guid>
		<description><![CDATA[Download the code for this article. Updated 14-Oct-2011: I modified the code sample to include controller unit tests and improved the config and logging services. I recently started a consulting project as an architect on an ASP.NET MVC application and &#8230; <a href="http://blog.tonysneed.com/2011/10/08/peeling-back-the-onion-architecture/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&amp;blog=14038854&amp;post=366&amp;subd=tonysneed&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>Download the <a href="http://tonysneed.com/download/onion-arch.zip">code</a> for this article.</em></p>
<p><strong>Updated 14-Oct-2011</strong>: I modified the code sample to include controller unit tests and improved the config and logging services.</p>
<p>I recently started a consulting project as an architect on an <a href="http://www.asp.net/mvc">ASP.NET MVC</a> application and quickly found myself immersed in the world of <strong>N*</strong> open source tools.&nbsp; <a href="http://en.wikipedia.org/wiki/Model-view-controller">MVC</a> (which stands for Model-View-Controller) lends itself to an <a href="http://en.wikipedia.org/wiki/Agile_software_development">Agile</a> development methodology where <a href="http://en.wikipedia.org/wiki/Test-driven_development">TDD</a> and <a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">BDD</a> (Test-Driven and Behavior-Driven Development) are important components.&nbsp; Writing applications that are testable requires that you separate business logic from presentation logic so that they can be independently tested.&nbsp; This is a concept known as <em>separation of concerns</em> (<a href="http://en.wikipedia.org/wiki/Separation_of_concerns">SoC</a>), which, in addition to testability, provides other benefits, such as greater application longevity and maintainability.&nbsp; The life of an application is extended because loose coupling makes it easer to upgrade or replace components without affecting other parts of the system.</p>
<p>This is where the “Onion Architecture” comes in.&nbsp; The term was first coined by Jeffery Palermo back in 2008 in a series of <a href="http://jeffreypalermo.com/blog/the-onion-architecture-part-1/">blog posts</a>.&nbsp; It is intended to provide some insurance against the evolution of technology that can make products obsolete not long after they are developed (the technical term is “deprecated”).&nbsp; A classic example is Microsoft’s data access stack, which tends to change every few years (remember the <a href="http://blogs.msdn.com/b/adonet/archive/2008/10/29/update-on-linq-to-sql-and-linq-to-entities-roadmap.aspx">demise</a> of LINQ to SQL?).&nbsp; What Jeffery proposed (although he’s not the first) is for the application to reference interfaces so that the concrete implementation can be supplied at runtime.&nbsp; If, for example, the data access layer is represented by a number of <a href="http://martinfowler.com/eaaCatalog/repository.html">repository</a> interfaces, you can swap out LINQ to SQL with <a href="http://msdn.microsoft.com/en-us/data/aa937723">Entity Framework</a> or <a href="http://nhforge.org/">NHibernate</a> (or your favorite ORM) without breaking other parts of the application.&nbsp; This same approach is used to decouple things like configuration and logging so they become replaceable components.</p>
<p><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="onion-arch" border="0" alt="onion-arch" src="http://tonysneed.files.wordpress.com/2011/10/onion-arch.jpg?w=600&#038;h=600" width="600" height="600"></p>
<p>In this depiction, the “core” of the onion is the object model, which represents your domain. This layer would contain your <a href="http://en.wikipedia.org/wiki/Plain_Old_CLR_Object">POCO</a> entities. Surrounding your domain entities are repository interfaces, which are in turn surrounded by service interfaces.&nbsp; Representing your repositories and services as interfaces decouples consumers from concrete implementations, enabling you to swap one out for another without affecting consumers, such as client UI’s or tests.&nbsp; The data access layer is represented in the outer layer as a set of repository classes which implement the repository interfaces.&nbsp; Similarly the logging component implements a logging interface in the service interfaces layer.</p>
<p><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="onion-proj" border="0" alt="onion-proj" src="http://tonysneed.files.wordpress.com/2011/10/onion-proj.jpg?w=282&#038;h=494" width="282" height="494"></p>
<p>Here is the project structure for a Visual Studio solution I created to demonstrate the Onion Architecture.&nbsp; I inserted solution folders and aligned project and folder names for ease of use.&nbsp; Infrastructure.Data uses <a href="http://nhforge.org/">NHibernate</a> to implement repositories for ICategoryRepository and IProductRepository in Domain.Interfaces.&nbsp; Infrastructure.Logging uses <a href="http://nlog-project.org/">NLog</a> to implement ILogging in Infrastructure.Interfaces.&nbsp; The Web.Ui project has a ProductService class that implements IProductService in Services.Interfaces. (In a future post I will incorporate WCF into the project structure, but the Service implementation would go in a Service.Core project, with a Web.Services project for the service host.)</p>
<p>You may be asking, “How are concrete implementations of repositories and services created?” If components in the outer layer were to create instances directly, they would be tightly coupled to those implementations, defeating the whole purpose of the Onion Architecture and jeopardizing the application’s long-term viability.&nbsp; The answer is <a href="http://martinfowler.com/articles/injection.html">Dependency Injection</a> (also known as Inversion of Control, or IoC).&nbsp; Components on the <a href="http://www.starwars.com/vault/books/atlas/news20090910/index.html">outer rim</a> of the diagram have constructors that accept service or repository interfaces, and it’s the job of the DI framework to serve up a concrete instance, based on some initial configuration or setup.&nbsp; For example, the ProductController class in the ASP.NET MVC application has a constructor that accepts an IProductService, which has methods to get categories and products.&nbsp; The controller doesn’t care about how the interface is implemented and what API the data access component uses.</p>
<pre class="code">

<span style="color:blue;">public class </span><span style="color:#2b91af;">ProductController </span>: <span style="color:#2b91af;">Controller
</span>{
    <span style="color:green;">// Services will be injected
    </span><span style="color:blue;">private </span><span style="color:#2b91af;">IProductService </span>_productService;

<strong>    <span style="color:blue;">public </span>ProductController(<font><span style="color:#2b91af;">IProductService </span>productService</font>)
    {
        _productService = productService;
    }
</strong>
    <span style="color:green;">//
    // GET: /Product/

    </span><span style="color:blue;">public </span><span style="color:#2b91af;">ActionResult </span>Index()
    {
        <span style="color:green;">// Get products
        </span><span style="color:blue;">var </span>products = _productService.GetProducts

            (selectedCategoryId);

        <span style="color:green;">// Rest of method follows ...
    </span>}
}
</pre>
<p>There are a number of <a href="http://manning.com/seemann">DI / IoC containers</a> out there.&nbsp; One of my favorites is <a href="http://ninject.org">Ninject</a>, which can be added using the <a href="http://nuget.org/">NuGet</a> package manager and has an extension for ASP.NET MVC applications.&nbsp; Installing the <a href="http://nuget.org/List/Packages/Ninject.MVC3">Ninject.MVC3</a> package places a bootstrapper class in the App_Start folder.&nbsp; There is a private RegisterServices method where you can bind local service implementations and load Ninject modules.</p>
<pre class="code"><span style="color:blue;">private static void </span>RegisterServices(<span style="color:#2b91af;">IKernel </span>kernel)
{
    <span style="color:green;">// Bind local services
    </span><strong>kernel.Bind&lt;<span style="color:#2b91af;"><font>IProductService</font></span>&gt;().To&lt;<span style="color:#2b91af;"><font>ProductService</font></span>&gt;();</strong>

    <span style="color:green;">// Add data and infrastructure modules
    </span><span style="color:blue;">var </span>modules = <span style="color:blue;">new </span><span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">INinjectModule</span>&gt;
        {
            <span style="color:blue;">new </span><span style="color:#2b91af;"><strong><font>RepositoryModule</font></strong></span>()
        };
    kernel.Load(modules);
}</pre>
<p>The RepositoryModule class resides in a separate DependencyResolution assembly, which references the Infrastructure.Data assembly and binds IProductRepository to ProductResository.&nbsp; The assembly containing the Ninject modules references the Data assembly, so that web client doesn’t have to, keeping the web client ignorant of the actual repository implementation.&nbsp; Once the bindings are set up, Ninject serves up the appropriate instance wherever the interface is used.</p>
<pre class="code">

<span style="color:blue;">public class </span><strong><span style="color:#2b91af;">RepositoryModule </span>: </strong><span style="color:#2b91af;"><strong>NinjectModule
</strong></span>{
    <span style="color:blue;">public override void </span>Load()
    {
        <span style="color:green;">// Get config service
</span>        <span style="color:blue;">var </span>configService = Kernel.Get&lt;<span style="color:#2b91af;">IConfigService</span>&gt;();

        <span style="color:green;">// Bind repositories
</span>        <strong>Bind&lt;<span style="color:#2b91af;"><font>IProductRepository</font></span>&gt;().To&lt;<span style="color:#2b91af;"><font>ProductRepository</font></span>&gt;()
</strong>            .WithConstructorArgument(<span style="color:#a31515;">"connectionString"</span>, 

            configService.NorthwindConnection);
    }
}
</pre>
<p>As you can see, dependency injection is the glue that holds everything together.&nbsp; An integration test, for example, would also use the DI container to get instances of interface implementations, without having to reference assemblies containing those classes.</p>
<pre class="code">[<span style="color:#2b91af;">TestFixture</span>]
<span style="color:blue;">public class </span><span style="color:#2b91af;">RepositoryTests
</span>{
    <span style="color:green;">// Ninject kernel
    </span><span style="color:blue;">private </span><span style="color:#2b91af;">IKernel </span>_ninjectKernel;

    <span style="color:blue;">public </span>RepositoryTests()
    {
        <span style="color:green;">// Init Ninject kernel
        </span>_ninjectKernel = <span style="color:blue;">new </span><span style="color:#2b91af;">StandardKernel</span>(<strong><font><span style="color:blue;">new </span><span style="color:#2b91af;">RepositoryModule</span>(), <span style="color:blue;">new </span><span style="color:#2b91af;">LoggingModule</span>()</font></strong>);
    }

    [<span style="color:#2b91af;">Test</span>]
    <span style="color:blue;">public void </span>Should_Get_All_Categories()
    {
        <span style="color:green;">// Arrange
        </span><strong><span style="color:blue;">var </span>categoriesRep = _ninjectKernel.Get&lt;<span style="color:#2b91af;"><font>ICategoryRepository</font></span>&gt;();
</strong>
        <span style="color:green;">// Act
        </span><span style="color:blue;">var </span>categories = categoriesRep.GetCategories();

        <span style="color:green;">// Assert
        </span><span style="color:#2b91af;">Assert</span>.That(categories != <span style="color:blue;">null</span>);
        <span style="color:#2b91af;">Assert</span>.That(categories.Count() &gt; 0);
    }
}</pre>
<p>Unit tests would likely combine DI with a mocking tool, such as <a href="http://code.google.com/p/moq/">Moq</a>, as shown here.</p>
<pre class="code">[<span style="color:#2b91af;">TestFixture</span>]
<span style="color:blue;">public class </span><span style="color:#2b91af;">RepositoryTests
</span>{
    <span style="color:green;">// Ninject kernel
    </span><span style="color:blue;">private </span><span style="color:#2b91af;">IKernel </span>_ninjectKernel;

    <span style="color:blue;">public </span>RepositoryTests()
    {
        <span style="color:green;">// Init Ninject kernel
        </span>_ninjectKernel = <span style="color:blue;">new </span><span style="color:#2b91af;">StandardKernel</span>();
    }

    [<span style="color:#2b91af;">TestFixtureSetUp</span>]
    <span style="color:blue;">public void </span>FixtureSetup()
    {
        <span style="color:green;">// Init categories
        </span><span style="color:blue;">var </span>categories = <span style="color:blue;">new </span><span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">Category</span>&gt;
        {
            <span style="color:blue;">new </span><span style="color:#2b91af;">Category </span>{ CategoryId = 1, CategoryName = <span style="color:#a31515;">"Beverages" </span>},
            <span style="color:blue;">new </span><span style="color:#2b91af;">Category </span>{ CategoryId = 2, CategoryName = <span style="color:#a31515;">"Condiments" </span>},
            <span style="color:blue;">new </span><span style="color:#2b91af;">Category </span>{ CategoryId = 1, CategoryName = <span style="color:#a31515;">"Confections" </span>}
        };

        <span style="color:green;">// Set up mock categories repository
<strong>        </strong></span><strong><span style="color:blue;">var </span>mockCategoriesRep = <span style="color:blue;">new </span><span style="color:#2b91af;">Mock</span>&lt;<span style="color:#2b91af;">ICategoryRepository</span>&gt;();
        mockCategoriesRep.Setup(m =&gt; m.GetCategories()).Returns(categories);
        _ninjectKernel.Bind&lt;<span style="color:#2b91af;"><font>ICategoryRepository</font></span>&gt;().ToConstant(<font>mockCategories.Object</font>);
</strong>    }

    [<span style="color:#2b91af;">Test</span>]
    <span style="color:blue;">public void </span>Should_Get_All_Categories()
    {
        <span style="color:green;">// Arrange
        </span><strong><span style="color:blue;">var </span>categoriesRep = _ninjectKernel.Get&lt;<span style="color:#2b91af;"><font>ICategoryRepository</font></span>&gt;();
</strong>
        <span style="color:green;">// Act
        </span><span style="color:blue;">var </span>categories = categoriesRep.GetCategories();

        <span style="color:green;">// Assert
        </span><span style="color:#2b91af;">Assert</span>.That(categories != <span style="color:blue;">null</span>);
        <span style="color:#2b91af;">Assert</span>.That(categories.Count() == 3);
    }
}</pre>
<p>Jeffrey summarizes the key tenets of the Onion Architecture as follows:</p>
<ul>
<ul>
<li>The application is built around an independent object model.
<li>Inner layers define interfaces; outer layers implement interfaces.
<li>Direction of coupling is toward the center.
<li>All application core code can be compiled and run separate from infrastructure.</li>
</ul>
</ul>
<p>The sample application (which you can download <a href="http://tonysneed.com/download/onion-arch.zip">here</a>) provides a reference architecture based on these principles.&nbsp; To use it you’ll need to download our good old friend, the <a href="http://www.microsoft.com/download/en/details.aspx?id=23654">Northwind</a> sample database.&nbsp; While the Onion Architecture does not propose anything new in terms of object-oriented and domain-driven design patterns, it provides guidance on how to decouple infrastructure from business and presentation logic, without introducing too much complexity or requiring redundant code. Enjoy.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tonysneed.wordpress.com/366/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tonysneed.wordpress.com/366/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tonysneed.wordpress.com/366/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tonysneed.wordpress.com/366/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tonysneed.wordpress.com/366/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tonysneed.wordpress.com/366/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tonysneed.wordpress.com/366/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tonysneed.wordpress.com/366/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tonysneed.wordpress.com/366/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tonysneed.wordpress.com/366/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tonysneed.wordpress.com/366/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tonysneed.wordpress.com/366/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tonysneed.wordpress.com/366/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tonysneed.wordpress.com/366/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&amp;blog=14038854&amp;post=366&amp;subd=tonysneed&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.tonysneed.com/2011/10/08/peeling-back-the-onion-architecture/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/878b354347e93c317b20a2a540f3ce04?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tonysneed</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/10/onion-arch.jpg" medium="image">
			<media:title type="html">onion-arch</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/10/onion-proj.jpg" medium="image">
			<media:title type="html">onion-proj</media:title>
		</media:content>
	</item>
		<item>
		<title>Build a Multi-Project Visual Studio Template</title>
		<link>http://blog.tonysneed.com/2011/09/14/build-a-multi-project-visual-studio-template/</link>
		<comments>http://blog.tonysneed.com/2011/09/14/build-a-multi-project-visual-studio-template/#comments</comments>
		<pubDate>Wed, 14 Sep 2011 13:36:24 +0000</pubDate>
		<dc:creator>Tony Sneed</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">https://tonysneed.wordpress.com/2011/09/14/build-a-multi-project-visual-studio-template/</guid>
		<description><![CDATA[Download the code for this article here. Earlier this year I authored an open-source toolkit, called Simple MVVM Toolkit, to help developers build Silverlight, WPF and Windows Phone applications based on the Model-View-ViewModel design pattern. To enhance developer productivity, the &#8230; <a href="http://blog.tonysneed.com/2011/09/14/build-a-multi-project-visual-studio-template/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&amp;blog=14038854&amp;post=362&amp;subd=tonysneed&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>Download the code for this article <a href="http://tonysneed.com/download/RestTemplate.zip">here</a>.</em></p>
<p>Earlier this year I authored an open-source toolkit, called <a href="http://simplemvvmtoolkit.codeplex.com">Simple MVVM Toolkit</a>, to help developers build Silverlight, WPF and Windows Phone applications based on the <a href="http://en.wikipedia.org/wiki/Model_View_ViewModel">Model-View-ViewModel</a> design pattern. To enhance developer productivity, the toolkit combines a set of helper classes with code and xml snippets, as well as Visual Studio item and project templates. After installing the toolkit, all a developer needs to do to <a href="http://simplemvvmtoolkit.codeplex.com/wikipage?title=Getting%20Started">get started</a> is open Visual Studio and create a new project by selecting one the project templates that appear under the Mvvm category.</p>
<p>&nbsp; <img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="smvvm-proj" border="0" alt="smvvm-proj" src="http://tonysneed.files.wordpress.com/2011/09/smvvm-proj.jpg?w=581&#038;h=375" width="581" height="375"></p>
<p>Visual Studio makes it extremely easy to create a single-project template. Simply select <strong>Export Template</strong> from the File menu and follow the prompts. This will produce a .zip file containing the contents of the project and a .vstemplate text file with xml describing the template content and properties.</p>
<p><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="exp-template" border="0" alt="exp-template" src="http://tonysneed.files.wordpress.com/2011/09/exp-template.jpg?w=277&#038;h=344" width="277" height="344"></p>
<p>There are times, however, when it you would like to create a template which generates multiple projects belonging to a single Visual Studio solution. A good example is the <strong>SimpleMvmRiaServices</strong> project template shown in the first screenshot, which generates a Visual Studio solution with three projects: an ASP.NET Web project, a Silverlight client project, and a Test project for unit tests.&nbsp; To create this template I first had to create individual templates for each of the three projects, then extract the contents of each zip file in order to combine them into a single multi-project Visual Studio template, with a .vstemplate file describing the contents.&nbsp; Here is an example of a VSTemplate file I created for a <a href="http://visualstudiogallery.msdn.microsoft.com/9272629c-74e2-423b-9841-f20b57f855fe">Multi-Project WCF REST Template</a> I recently did for a <a href="http://blog.tonysneed.com/2011/09/10/digging-into-wcf-rest/">talk</a> I gave at a <a href="http://www.ddnug.net">.NET developer group</a> (some of the content has been elided for clarity).</p>
<pre class="code"><span style="color:blue;">&lt;</span><span style="color:#a31515;">VSTemplate </span><span style="color:red;">Type</span><span style="color:blue;">=</span>"<span style="color:blue;">ProjectGroup</span>"<span style="color:blue;">&gt;
  &lt;</span><span style="color:#a31515;">TemplateData</span><span style="color:blue;">&gt;
    &lt;</span><span style="color:#a31515;">Name</span><span style="color:blue;">&gt;</span>WCF REST Service<span style="color:blue;">&lt;/</span><span style="color:#a31515;">Name</span><span style="color:blue;">&gt;
    &lt;</span><span style="color:#a31515;">Description</span><span style="color:blue;">&gt;</span>REST Service Template by Tony Sneed<span style="color:blue;">&lt;/</span><span style="color:#a31515;">Description</span><span style="color:blue;">&gt;
    &lt;</span><span style="color:#a31515;">ProjectType</span><span style="color:blue;">&gt;</span>CSharp<span style="color:blue;">&lt;/</span><span style="color:#a31515;">ProjectType</span><span style="color:blue;">&gt;
    &lt;</span><span style="color:#a31515;">TemplateGroupID</span><span style="color:blue;">&gt;</span>WCF<span style="color:blue;">&lt;/</span><span style="color:#a31515;">TemplateGroupID</span><span style="color:blue;">&gt;
    &lt;</span><span style="color:#a31515;">RequiredFrameworkVersion</span><span style="color:blue;">&gt;</span>4.0<span style="color:blue;">&lt;/</span><span style="color:#a31515;">RequiredFrameworkVersion</span><span style="color:blue;">&gt;
  &lt;/</span><span style="color:#a31515;">TemplateData</span><span style="color:blue;">&gt;
  &lt;</span><span style="color:#a31515;">TemplateContent</span><span style="color:blue;">&gt;
    &lt;</span><span style="color:#a31515;">ProjectCollection</span><span style="color:blue;">&gt;
      &lt;</span><span style="color:#a31515;">ProjectTemplateLink </span><span style="color:red;">ProjectName</span><span style="color:blue;">=</span>"<span style="color:blue;">$safeprojectname$.Client</span>"<span style="color:blue;">&gt;
        </span>Client\Client.vstemplate
      <span style="color:blue;">&lt;/</span><span style="color:#a31515;">ProjectTemplateLink</span><span style="color:blue;">&gt;
      &lt;</span><span style="color:#a31515;">ProjectTemplateLink </span><span style="color:red;">ProjectName</span><span style="color:blue;">=</span>"<span style="color:blue;">$safeprojectname$.Entities</span>"<span style="color:blue;">&gt;
        </span>Entities\Entities.vstemplate
      <span style="color:blue;">&lt;/</span><span style="color:#a31515;">ProjectTemplateLink</span><span style="color:blue;">&gt;
      &lt;</span><span style="color:#a31515;">ProjectTemplateLink </span><span style="color:red;">ProjectName</span><span style="color:blue;">=</span>"<span style="color:blue;">$safeprojectname$.Service</span>"<span style="color:blue;">&gt;
        </span>Service\Service.vstemplate
      <span style="color:blue;">&lt;/</span><span style="color:#a31515;">ProjectTemplateLink</span><span style="color:blue;">&gt;
      &lt;</span><span style="color:#a31515;">ProjectTemplateLink </span><span style="color:red;">ProjectName</span><span style="color:blue;">=</span>"<span style="color:blue;">$safeprojectname$.Web</span>"<span style="color:blue;">&gt;
        </span>Web\Web.vstemplate
      <span style="color:blue;">&lt;/</span><span style="color:#a31515;">ProjectTemplateLink</span><span style="color:blue;">&gt;
    &lt;/</span><span style="color:#a31515;">ProjectCollection</span><span style="color:blue;">&gt;
  &lt;/</span><span style="color:#a31515;">TemplateContent</span><span style="color:blue;">&gt;
  &lt;</span><span style="color:#a31515;">WizardExtension</span><span style="color:blue;">&gt;
    &lt;</span><span style="color:#a31515;">Assembly</span><span style="color:blue;">&gt;</span>RestTemplateWizard, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c9a76f51a8a9555f<span style="color:blue;">&lt;/</span><span style="color:#a31515;">Assembly</span><span style="color:blue;">&gt;
    &lt;</span><span style="color:#a31515;">FullClassName</span><span style="color:blue;">&gt;</span>RestTemplateWizard.RootWizard<span style="color:blue;">&lt;/</span><span style="color:#a31515;">FullClassName</span><span style="color:blue;">&gt;
  &lt;/</span><span style="color:#a31515;">WizardExtension</span><span style="color:blue;">&gt;
&lt;/</span><span style="color:#a31515;">VSTemplate</span><span style="color:blue;">&gt;</span></pre>
<p>The template encompasses four project templates: Client, Entities, Service and Web. Notice the variable, <strong>$safeprojectname$</strong>, which captures what the user entered for the project name in the New Project dialog. There is also a WizardExtension element, which references an <strong>IWizard</strong> implementation.&nbsp; <a href="http://tonysneed.com/download/RestTemplate.zip">IWizard</a> allows you to control the template creation process, for example, to allow projects to reference one another or to set project properties, such as the RIA Service project link required for my SimpleMvvmRiaServices template.</p>
<p>For my WCF REST template I wanted the Client and Service projects to both reference the Entities project, and for the Web project to reference the Service project. The problem here is that within each child template, $safeprojectname$ represents the current project name. There needs to be a way to pass in the root $safeprojectname$ from the parent template.&nbsp; This is where the IWizard project comes in.</p>
<p>Start by creating a class library project and referencing the assembly, Microsoft.VisualStudio.TemplateWizardInterface.dll.&nbsp; Create a RootWizard class that implements IWizard.&nbsp; In the RunStarted method you can capture $safeprojectname$ from replacementParameters and store it in a public static Dictionary&lt;string,string&gt; so that it can be captured by a ChildWizard class and stored as $saferootprojectname$ in replacementParameters.</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">RootWizard </span>: <span style="color:#2b91af;">IWizard
</span>{
    <span style="color:green;">// Use to communicate $saferootprojectname$ to ChildWizard
    </span><span style="color:blue;">public static </span><span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:blue;">string</span>, <span style="color:blue;">string</span>&gt; GlobalDictionary =
        <span style="color:blue;">new </span><span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:blue;">string</span>,<span style="color:blue;">string</span>&gt;();

    <span style="color:green;">// Add global replacement parameters
    </span><span style="color:blue;">public void </span>RunStarted(<span style="color:blue;">object </span>automationObject,
        <span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:blue;">string</span>, <span style="color:blue;">string</span>&gt; replacementsDictionary,
        <span style="color:#2b91af;">WizardRunKind </span>runKind, <span style="color:blue;">object</span>[] customParams)
    {
        <span style="color:green;">// Place "$saferootprojectname$ in the global dictionary.
        // Copy from $safeprojectname$ passed in my root vstemplate
        </span>GlobalDictionary[<span style="color:#a31515;">"$saferootprojectname$"</span>] = replacementsDictionary[<span style="color:#a31515;">"$safeprojectname$"</span>];
    }

    <span style="color:green;">// Other members elided for clarity
</span>}</pre>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">ChildWizard </span>: <span style="color:#2b91af;">IWizard
</span>{
    <span style="color:green;">// Retrieve global replacement parameters
    </span><span style="color:blue;">public void </span>RunStarted(<span style="color:blue;">object </span>automationObject,
        <span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:blue;">string</span>, <span style="color:blue;">string</span>&gt; replacementsDictionary,
        <span style="color:#2b91af;">WizardRunKind </span>runKind, <span style="color:blue;">object</span>[] customParams)
    {
        <span style="color:green;">// Add custom parameters.
        </span>replacementsDictionary.Add(<span style="color:#a31515;">"$saferootprojectname$"</span>,
            <span style="color:#2b91af;">RootWizard</span>.GlobalDictionary[<span style="color:#a31515;">"$saferootprojectname$"</span>]);
    }

    <span style="color:green;">// Other members elided for clarity
</span>}</pre>
<p>You can now edit project references in child project csproj files, as well as using directives in source code files, to include <strong>$saferootprojectname$</strong> where you want the user-entered project name to appear.</p>
<pre class="code"><span style="color:blue;">&lt;</span><span style="color:#a31515;">Project </span><span style="color:red;">ToolsVersion</span><span style="color:blue;">=</span>"<span style="color:blue;">4.0</span>" <span style="color:red;">DefaultTargets</span><span style="color:blue;">=</span>"<span style="color:blue;">Build</span>"<span style="color:blue;">&gt;
  &lt;</span><span style="color:#a31515;">ItemGroup</span><span style="color:blue;">&gt;
    &lt;</span><span style="color:#a31515;">ProjectReference </span><span style="color:red;">Include</span><span style="color:blue;">=</span>"<span style="color:blue;">..\$saferootprojectname$.Entities
          \$saferootprojectname$.Entities.csproj</span>"<span style="color:blue;">&gt;
      &lt;</span><span style="color:#a31515;">Project</span><span style="color:blue;">&gt;</span>{3EC4AE2B-892C-42FC-9814-D46EB06A22E4}<span style="color:blue;">&lt;/</span><span style="color:#a31515;">Project</span><span style="color:blue;">&gt;
      &lt;</span><span style="color:#a31515;">Name</span><span style="color:blue;">&gt;</span>Entities<span style="color:blue;">&lt;/</span><span style="color:#a31515;">Name</span><span style="color:blue;">&gt;
    &lt;/</span><span style="color:#a31515;">ProjectReference</span><span style="color:blue;">&gt;
  &lt;/</span><span style="color:#a31515;">ItemGroup</span><span style="color:blue;">&gt;
&lt;/</span><span style="color:#a31515;">Project</span><span style="color:blue;">&gt;</span></pre>
<pre class="code"><span style="color:blue;">using </span>System;
<span style="color:blue;">using </span>$saferootprojectname$.Entities;

<span style="color:blue;">namespace </span>$safeprojectname$
{
    <span style="color:blue;">class </span><span style="color:#2b91af;">Program
    </span>{
        <span style="color:blue;">static void </span>Main(<span style="color:blue;">string</span>[] args)
        {
            <span style="color:green;">// Client code goes here ...
        </span>}
    }
}</pre>
<p>Next, make sure to sign your wizard assembly, using a test certificate if you like, and then obtain the public key token by opening a Visual Studio command prompt at the location of your wizard dll and entering the command (replace WizardAssembly with your dll file name):<br /><strong>sn –T WizardAssembly.dll</strong></p>
<p><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="sn-pubkey" border="0" alt="sn-pubkey" src="http://tonysneed.files.wordpress.com/2011/09/sn-pubkey.jpg?w=621&#038;h=102" width="621" height="102"></p>
<p>Now that you’ve created a multi-project Visual Studio template, you need a way to deploy it.&nbsp; The best way is to create a VSIX project, which allows you easily publish your template to the <a href="http://visualstudiogallery.msdn.microsoft.com/">Visual Studio Extensions Gallery</a>, so that developers from around the world can install it by selecting Extension Manager from the Tools menu right from within Visual Studio! First you’ll need to install the <a href="http://www.microsoft.com/download/en/details.aspx?id=21835">Visual Studio 2010 SP1 SDK</a> (assuming you’ve first installed <a href="http://www.microsoft.com/download/en/details.aspx?id=23691">SP1 for VS 2010</a>). Then create a new VSIX project (in the Extensibility category that now appears in the New Project dialog).&nbsp; What you get is a nice designer for editing the .vsixmanifest file, where you can set properties and add content.</p>
<p><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="vsix-1" border="0" alt="vsix-1" src="http://tonysneed.files.wordpress.com/2011/09/vsix-1.jpg?w=624&#038;h=208" width="624" height="208"></p>
<p>There are two items you will want to add as content. One is the template wizard assembly you just created, and the other is a zip file containing the multi-project template contents, including both the parent .vstemplate file and icons, as well as a folder for each child project template containing the project contents and .vstemplate file.</p>
<p><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="vsix-2" border="0" alt="vsix-2" src="http://tonysneed.files.wordpress.com/2011/09/vsix-2.jpg?w=606&#038;h=137" width="606" height="137"></p>
<p>The important thing to note here is that the assembly for the IWizard implementation need not be installed into the Global Assembly Cache when it is packaged into the same VSIX project as the templates using it.&nbsp; Another thing you might want to do when adding the template zip file is specify the category under which you want your template to appear in the Visual Studio New Project dialog.&nbsp; In the the case of my WCF REST Template, I have indicated it should appear under the WCF category.</p>
<p><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="add-content" border="0" alt="add-content" src="http://tonysneed.files.wordpress.com/2011/09/add-content.jpg?w=401&#038;h=294" width="401" height="294"></p>
<p>When you build the extensibility project, you’ll get a .vsix file that you can upload to the <a href="http://visualstudiogallery.msdn.microsoft.com/">Visual Studio Extensions Gallery</a>, so that it will appear in the Online Gallery when developers select Extension Manager from the Tools menu.&nbsp; Enjoy.</p>
<p><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="ext-gallery" border="0" alt="ext-gallery" src="http://tonysneed.files.wordpress.com/2011/09/ext-gallery1.jpg?w=577&#038;h=354" width="577" height="354"></p>
<p><em>You can download the code for this article </em><a href="http://tonysneed.com/download/RestTemplate.zip"><em>here</em></a><em>.</em></p>
<p><a href="http://www.develop.com/technicalstaff#Anthony-Sneed">Tony Sneed</a><br /><a href="http://blog.tonysneed.com">http://blog.tonysneed.com</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tonysneed.wordpress.com/362/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tonysneed.wordpress.com/362/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tonysneed.wordpress.com/362/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tonysneed.wordpress.com/362/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tonysneed.wordpress.com/362/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tonysneed.wordpress.com/362/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tonysneed.wordpress.com/362/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tonysneed.wordpress.com/362/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tonysneed.wordpress.com/362/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tonysneed.wordpress.com/362/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tonysneed.wordpress.com/362/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tonysneed.wordpress.com/362/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tonysneed.wordpress.com/362/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tonysneed.wordpress.com/362/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&amp;blog=14038854&amp;post=362&amp;subd=tonysneed&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.tonysneed.com/2011/09/14/build-a-multi-project-visual-studio-template/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/878b354347e93c317b20a2a540f3ce04?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tonysneed</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/09/smvvm-proj.jpg" medium="image">
			<media:title type="html">smvvm-proj</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/09/exp-template.jpg" medium="image">
			<media:title type="html">exp-template</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/09/sn-pubkey.jpg" medium="image">
			<media:title type="html">sn-pubkey</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/09/vsix-1.jpg" medium="image">
			<media:title type="html">vsix-1</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/09/vsix-2.jpg" medium="image">
			<media:title type="html">vsix-2</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/09/add-content.jpg" medium="image">
			<media:title type="html">add-content</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/09/ext-gallery1.jpg" medium="image">
			<media:title type="html">ext-gallery</media:title>
		</media:content>
	</item>
		<item>
		<title>Digging into WCF REST</title>
		<link>http://blog.tonysneed.com/2011/09/10/digging-into-wcf-rest/</link>
		<comments>http://blog.tonysneed.com/2011/09/10/digging-into-wcf-rest/#comments</comments>
		<pubDate>Sun, 11 Sep 2011 04:06:18 +0000</pubDate>
		<dc:creator>Tony Sneed</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">https://tonysneed.wordpress.com/2011/09/10/digging-into-wcf-rest/</guid>
		<description><![CDATA[Update: The recording for this talk is now available. Last Thursday evening I presented a talk to the Dallas .NET User Group on support in WCF 4 for building REST-ful services. Here is a summary of the talk: To REST &#8230; <a href="http://blog.tonysneed.com/2011/09/10/digging-into-wcf-rest/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&amp;blog=14038854&amp;post=354&amp;subd=tonysneed&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Update: The <a href="http://usergroup.tv/videos/to-rest-or-not-to-rest-building-rest-ful-services-with-the-wcf-web-programming-model">recording</a> for this talk is now available.</p>
<p>Last Thursday evening I presented a talk to the <a href="http://ddnug.net/">Dallas .NET User Group</a> on support in WCF 4 for building REST-ful services. Here is a summary of the talk:</p>
<p><strong>To REST or Not To REST? – Building REST-ful Services with the WCF Web Programming Model<br />
</strong><em>REST is defined as an architectural style for building services that embrace the principles of the web. But what&#8217;s it good for? Tony will provide concrete examples of where it makes sense to implement REST-ful web services. He&#8217;ll also get down and dirty using the WCF Web Programming Model and show how WCF makes it easy to serve up POX or JSON, increasing the reach of your services to clients that don&#8217;t understand or care about SOAP. We&#8217;ll also look at API&#8217;s for syndicating content using RSS and ATOM.</em></p>
<p>Here are the <a href="http://tonysneed.com/download/ddnug-rest.zip">slides and code</a> for the talk, which highlighted improvements in WCF’s support for REST that arrived with .NET 4.0 and Visual Studio 2010, folding in features we first saw in the REST Starter Kit, which is now largely obsolete.</p>
<p>Here are some essential resources on WCF REST:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/netframework/cc950529">WCF REST Developer Center</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/dd203052.aspx">WCF 3.5 REST White Paper</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ee354381.aspx">WCF 4.0 Improvements White Paper</a></li>
</ul>
<p>One of the things I highlighted in the talk is a Visual Studio template, which you can download from the Visual Studio Extensions Gallery, that creates a WCF REST-based service.  However, after installing the template, I was somewhat disappointed.  It creates a Visual Studio solution with just a single web project.  The service contract is merged with the implementation (just a class with no separate interface), and there is no client project.</p>
<p>About an hour before the talk, I decided to create my <a href="http://visualstudiogallery.msdn.microsoft.com/9272629c-74e2-423b-9841-f20b57f855fe">own version</a> of the WCF REST Template, which creates a multi-project solution containing a web project with the service interface and class placed in a separate class library project and the entities in their own class library project.  I also threw in a console client project which consumes the WCF REST service and uses LINQ to XML to parse the results.  I was so pleased with the template, that I packaged it into a vsix project and uploaded it to the Visual Studio Extensions Gallery, so all you have to do is open up Visual Studio, go to Tools, Extension Manager, select Online Gallery and search for <strong>WCF REST Template</strong>.</p>
<p><a href="http://visualstudiogallery.msdn.microsoft.com/9272629c-74e2-423b-9841-f20b57f855fe"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="ext-gallery" src="http://tonysneed.files.wordpress.com/2011/09/ext-gallery.jpg?w=587&#038;h=350" alt="ext-gallery" width="587" height="350" border="0" /></a></p>
<p>After installing the template, simply create a new project in Visual Studio, select the WCF category, and choose “WCF REST Service” from the list of project templates.</p>
<p><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="new-project" src="http://tonysneed.files.wordpress.com/2011/09/new-project.jpg?w=586&#038;h=362" alt="new-project" width="586" height="362" border="0" /></p>
<p>This will give you a solution containing <span style="text-decoration:underline;">four projects</span>: An <strong>Entities</strong> project, containing a SampleItem class, a <strong>Service</strong> project, with an ISampleService interface implemented by a SampleService class, a <strong>Web</strong> project to host the service (which has a ReadMe file) and a <strong>Client</strong> project to consume the service.</p>
<p><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="sol-ex" src="http://tonysneed.files.wordpress.com/2011/09/sol-ex.jpg?w=248&#038;h=415" alt="sol-ex" width="248" height="415" border="0" /></p>
<p>All you have to do is set the Web project as the startup project for the solution and press Ctrl+F5 to launch the VS dev web server. Then set the Client project as the startup project and run it by pressing Ctrl+F5.  The client will issue an HTTP GET request to the service to retrieve XML representing a list of sample items. It uses LINQ to XML to parse the result into a list of items.</p>
<p>One of the things featured by the template is WCF 4’s simplified configuration model.  If you take a look at web.config, you’ll see that a default web http endpoint is configured to support a help page as well as automatic format selection (XML or JSON) based on the Content-Type and/or Accept HTTP headers.</p>
<p><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="rest-help" src="http://tonysneed.files.wordpress.com/2011/09/rest-help.jpg?w=599&#038;h=277" alt="rest-help" width="599" height="277" border="0" /></p>
<p>Typing the sample URI into the address of your browser will result in the following output:</p>
<p><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="get-collection" src="http://tonysneed.files.wordpress.com/2011/09/get-collection.jpg?w=498&#038;h=249" alt="get-collection" width="498" height="249" border="0" /></p>
<p>In addition, the template illustrates support in WCF 4 for using the ASP.NET url routing engine, in lieu of an .svc file.  You can see this in action if you take a peek at the code-behind for the global.asax file.</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">Global </span>: <span style="color:#2b91af;">HttpApplication </span>{
    <span style="color:blue;">void </span>Application_Start(<span style="color:blue;">object </span>sender, <span style="color:#2b91af;">EventArgs </span>e)
    {
        RegisterRoutes();
    }

    <span style="color:blue;">private void </span>RegisterRoutes()
    {
        <span style="color:green;">// Edit the base address replacing the "SampleService" string below </span><span style="color:#2b91af;">RouteTable</span>.Routes.Add(<span style="color:blue;">new </span><span style="color:#2b91af;">ServiceRoute</span>(<span style="color:#a31515;">"SampleService"</span>,
            <span style="color:blue;">new </span><span style="color:#2b91af;">WebServiceHostFactory</span>(), <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">SampleService</span>)));
    }
}</pre>
<p>When an HTTP request arrives with a base address of SampleService (which you can change), the WebServiceHostFactory spins up the SampleService and maps the request to an operation, depending on the remaining part of the uri and the HTTP verb used.</p>
<pre class="code"><span style="color:green;">// Start the service and browse to &lt;a href=&quot;http://:/SampleService/help[ServiceContract]public"&gt;http://&lt;machine_name&gt;:&lt;port&gt;/SampleService/help </a></span>[<span style="color:#2b91af;">ServiceContract</span>]
<span style="color:blue;">public interface </span><span style="color:#2b91af;">ISampleService </span>{
    [<span style="color:#2b91af;">WebGet</span>(UriTemplate = <span style="color:#a31515;">""</span>)]
    <span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">SampleItem</span>&gt; GetCollection();

    [<span style="color:#2b91af;">WebInvoke</span>(UriTemplate = <span style="color:#a31515;">""</span>, Method = <span style="color:#a31515;">"POST"</span>)]
    <span style="color:#2b91af;">SampleItem </span>Create(<span style="color:#2b91af;">SampleItem </span>instance);

    [<span style="color:#2b91af;">WebGet</span>(UriTemplate = <span style="color:#a31515;">"?id={id}"</span>)]
    <span style="color:#2b91af;">SampleItem </span>Get(<span style="color:blue;">int </span>id);

    [<span style="color:#2b91af;">WebInvoke</span>(UriTemplate = <span style="color:#a31515;">"?id={id}"</span>, Method = <span style="color:#a31515;">"PUT"</span>)]
    <span style="color:#2b91af;">SampleItem </span>Update(<span style="color:blue;">int </span>id, <span style="color:#2b91af;">SampleItem </span>instance);

    [<span style="color:#2b91af;">WebInvoke</span>(UriTemplate = <span style="color:#a31515;">"?id={id}"</span>, Method = <span style="color:#a31515;">"DELETE"</span>)]
    <span style="color:blue;">void </span>Delete(<span style="color:blue;">int </span>id);
}</pre>
<p>This pattern also illustrates the resource-centric nature of a REST-based services architecture that leverages HTTP verbs for CRUD operations.  This architectural style comes in handy when you want to increase the reach of your service to clients that may not understand or care about SOAP, such as AJAX or Silverlight, or when you want to simplify the contractual footprint of your service by leveraging the uniform interface of the web and taking advantage of the HTTP protocol for things like security and caching.</p>
<p>I hope my WCF REST Template helps you get a better handle on building REST services with WCF. Enjoy.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tonysneed.wordpress.com/354/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tonysneed.wordpress.com/354/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tonysneed.wordpress.com/354/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tonysneed.wordpress.com/354/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tonysneed.wordpress.com/354/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tonysneed.wordpress.com/354/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tonysneed.wordpress.com/354/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tonysneed.wordpress.com/354/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tonysneed.wordpress.com/354/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tonysneed.wordpress.com/354/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tonysneed.wordpress.com/354/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tonysneed.wordpress.com/354/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tonysneed.wordpress.com/354/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tonysneed.wordpress.com/354/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&amp;blog=14038854&amp;post=354&amp;subd=tonysneed&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.tonysneed.com/2011/09/10/digging-into-wcf-rest/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/878b354347e93c317b20a2a540f3ce04?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tonysneed</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/09/ext-gallery.jpg" medium="image">
			<media:title type="html">ext-gallery</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/09/new-project.jpg" medium="image">
			<media:title type="html">new-project</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/09/sol-ex.jpg" medium="image">
			<media:title type="html">sol-ex</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/09/rest-help.jpg" medium="image">
			<media:title type="html">rest-help</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/09/get-collection.jpg" medium="image">
			<media:title type="html">get-collection</media:title>
		</media:content>
	</item>
		<item>
		<title>Commands versus Event Triggers in MVVM</title>
		<link>http://blog.tonysneed.com/2011/07/22/commands-versus-event-triggers-in-mvvm/</link>
		<comments>http://blog.tonysneed.com/2011/07/22/commands-versus-event-triggers-in-mvvm/#comments</comments>
		<pubDate>Fri, 22 Jul 2011 18:18:04 +0000</pubDate>
		<dc:creator>Tony Sneed</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[MVVM]]></category>

		<guid isPermaLink="false">https://tonysneed.wordpress.com/2011/07/22/commands-versus-event-triggers-in-mvvm/</guid>
		<description><![CDATA[Recently I’ve received some questions from the Simple MVVM Toolkit’s discussion forum on when to use commands versus Blend-style event triggers. For several reasons I tend to favor event triggers over commands in most scenarios, especially for Silverlight applications. Download &#8230; <a href="http://blog.tonysneed.com/2011/07/22/commands-versus-event-triggers-in-mvvm/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&amp;blog=14038854&amp;post=347&amp;subd=tonysneed&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Recently I’ve received some <a href="http://simplemvvmtoolkit.codeplex.com/discussions/263122">questions</a> from the Simple MVVM Toolkit’s <a href="http://simplemvvmtoolkit.codeplex.com/discussions">discussion forum</a> on when to use commands versus Blend-style event triggers. For several reasons I tend to favor event triggers over commands in most scenarios, especially for Silverlight applications.</p>
<p><em>Download the code for this blog post <a href="http://tonysneed.com/simplemvvm/EventTriggers.zip">here</a>.</em></p>
<ol>
<li>One of the main benefits of commands lies in the CanExecute property of ICommand, so that you can enable and disable a control based on a condition.&nbsp; ICommand exposes a CanExecuteChanged event which when fired causes a binding to check the CanExecute property.&nbsp; Unfortunately Silverlight requires you to fire the CanExecuteChanged event manually, which is why implementations of ICommand (such as the DelegateCommand in Simple MVVM Toolkit) also expose a public RaiseCanExecute method.
<ul>
<li>You can easily achieve the same result as CanExecute simply by binding the IsEnabled property of a control to a boolean property on the ViewModel.&nbsp; Then call NotifyPropertyChanged, passing the property name with a lambda expression, whenever you want the binding to check the value of the boolean property.</li>
</ul>
<li>Currently commands can only be used by controls that derive from ButtonBase, such as a Button or HyperLink Button.&nbsp; And it can only be used to respond to the button’s Click event.&nbsp; Other toolkits have an EventToCommand behavior that allows you to invoke a command from events other than Click and with controls other than buttons.&nbsp; However, you can accomplish much the same thing with a Blend event trigger, without the need for all the extra code required in the ViewModel for a command.
<ul>
<li>You can use an event trigger from the Blend SDK with a CallMethodAction that allows you to invoke a parameterless method on the ViewModel from any event on any control.&nbsp; The question then arises on how to invoke methods that have input parameters.&nbsp; You can usually bypass this need because the method in the ViewModel has access to properties on the ViewModel that are bound to controls in the View.&nbsp; For example, I could have a method called ShowCustomer.&nbsp; Instead of adding a customer parameter to the method, I can simply reference a SelectedCustomer property on the ViewModel, which can be bound to the SelectedItem property of a combo box in the View.</li>
</ul>
<li>There is one scenario where I would want to use commands, which is to call a method in the ViewModel that accepts a parameter with a value that cannot be obtained from a property on the ViewModel.
<ul>
<li>A good example of this would be buttons on a calculator.&nbsp; In this case you would want to pass in arbitrary values to an Add method, which is wired up to an AddCommand.&nbsp; The CommandParameter property of the button is your friend here.&nbsp; Simply specify a number corresponding to the relevant button.&nbsp; The generic DelegateCommand in Simple MVVM Toolkit is implemented in a way that dynamically calls a Parse method on the generic type argument.</li>
</ul>
</li>
</ol>
<p>Here is what an event trigger would look like, wiring up the SelectionChanged event of a combo box to a ShowCustomer method on the ViewModel. Simple MVVM Toolkit comes with an XML snippet you can use to insert an event trigger / call method action.&nbsp; To use it you need to open up a view by right-clicking on it in the Solution Explorer and choosing “Open With …” and selecting XML Editor.&nbsp; Then you should make sure to add a end element for the combo box control (&lt;/ComboBox&gt; instead of /&gt;).&nbsp; Right-click in the empty content of the ComboBox element and select Insert Snippet from the context menu. Then open “My XML Snippets” and drill down until you find the “mvvmtrigger” snippet. Type “SelectionChanged” for the event name and “ShowCustomer” for the method name.</p>
<pre class="code"><span style="color:blue;">&lt;</span><span style="color:#a31515;">ComboBox </span><span style="color:red;">Height</span><span style="color:blue;">=</span>"<span style="color:blue;">23</span>" <span style="color:red;">ItemsSource</span><span style="color:blue;">=</span>"<span style="color:blue;">{Binding Customers}</span>" <span style="color:red;">SelectedItem</span><span style="color:blue;">=</span>"<span style="color:blue;">{Binding Path=SelectedCustomer, Mode=TwoWay}</span>"
          <span style="color:red;">HorizontalAlignment</span><span style="color:blue;">=</span>"<span style="color:blue;">Center</span>" <span style="color:red;">VerticalAlignment</span><span style="color:blue;">=</span>"<span style="color:blue;">Center</span>" <span style="color:red;">Width</span><span style="color:blue;">=</span>"<span style="color:blue;">120</span>" <span style="color:red;">Grid.ColumnSpan</span><span style="color:blue;">=</span>"<span style="color:blue;">2</span>" <span style="color:red;">DisplayMemberPath</span><span style="color:blue;">=</span>"<span style="color:blue;">CustomerName</span>"<span style="color:blue;">&gt;
  &lt;!-- </span><span style="color:green;">Add reference to Microsoft.Expression.Interactions.dll, System.Windows.Interactivity.dll </span><span style="color:blue;">--&gt;
  &lt;!-- </span><span style="color:green;">Use mvvmxmlns snippet to add i and ei namespace prefixes </span><span style="color:blue;">--&gt;
  &lt;</span><span style="color:#a31515;">i:Interaction.Triggers</span><span style="color:blue;">&gt;
    &lt;</span><span style="color:#a31515;">i:EventTrigger </span><span style="color:red;">EventName</span><span style="color:blue;">=</span>"<span style="color:blue;">SelectionChanged</span>"<span style="color:blue;">&gt;
      &lt;</span><span style="color:#a31515;">ei:CallMethodAction
              </span><span style="color:red;">TargetObject</span><span style="color:blue;">=</span>"<span style="color:blue;">{Binding}</span>"
              <span style="color:red;">MethodName</span><span style="color:blue;">=</span>"<span style="color:blue;">ShowCustomer</span>"<span style="color:blue;">/&gt;
    &lt;/</span><span style="color:#a31515;">i:EventTrigger</span><span style="color:blue;">&gt;
  &lt;/</span><span style="color:#a31515;">i:Interaction.Triggers</span><span style="color:blue;">&gt;
&lt;/</span><span style="color:#a31515;">ComboBox</span><span style="color:blue;">&gt;</span></pre>
<p>The ShowCustomer method in the ViewModel looks like this.</p>
<pre class="code"><span style="color:blue;">public void </span>ShowCustomer()
{
    <span style="color:blue;">if </span>(SelectedCustomer != <span style="color:blue;">null</span>)
    {
        <span style="color:#2b91af;">MessageBox</span>.Show(SelectedCustomer.CustomerName);
    }
}</pre>
<p>Let’s take this example a bit further by adding a “Show Customer” button to the View that is only enabled when a customer has been selected.&nbsp; We start by adding a CanShowCustomer boolean property to the ViewModel, so that we can bind the IsEnabled property of the button to it.</p>
<pre class="code"><span style="color:blue;">public bool </span>CanShowCustomer
{
    <span style="color:blue;">get
    </span>{
        <span style="color:blue;">return </span>SelectedCustomer != <span style="color:blue;">null </span>&amp;&amp; SelectedCustomer.CustomerId &gt; 0;
    }
}</pre>
<p>Using the mvvmtrigger XML snippet we can add a trigger for the Click event that executes the ShowCustomer method on the ViewModel.&nbsp; The button will be disabled when CanShowCustomer returns false.</p>
<pre class="code"><span style="color:blue;">&lt;</span><span style="color:#a31515;">Button </span><span style="color:red;">Content</span><span style="color:blue;">=</span>"<span style="color:blue;">Show Customer</span>" <span style="color:red;">Grid.Column</span><span style="color:blue;">=</span>"<span style="color:blue;">1</span>" <span style="color:red;">Height</span><span style="color:blue;">=</span>"<span style="color:blue;">23</span>" <span style="color:red;">Width</span><span style="color:blue;">=</span>"<span style="color:blue;">100</span>"
        <span style="color:red;">IsEnabled</span><span style="color:blue;">=</span>"<span style="color:blue;">{Binding CanShowCustomer}</span>"<span style="color:blue;">&gt;
  &lt;</span><span style="color:#a31515;">i:Interaction.Triggers</span><span style="color:blue;">&gt;
    &lt;</span><span style="color:#a31515;">i:EventTrigger </span><span style="color:red;">EventName</span><span style="color:blue;">=</span>"<span style="color:blue;">Click</span>"<span style="color:blue;">&gt;
      &lt;</span><span style="color:#a31515;">ei:CallMethodAction
              </span><span style="color:red;">TargetObject</span><span style="color:blue;">=</span>"<span style="color:blue;">{Binding}</span>"
              <span style="color:red;">MethodName</span><span style="color:blue;">=</span>"<span style="color:blue;">ShowCustomer</span>"<span style="color:blue;">/&gt;
    &lt;/</span><span style="color:#a31515;">i:EventTrigger</span><span style="color:blue;">&gt;
  &lt;/</span><span style="color:#a31515;">i:Interaction.Triggers</span><span style="color:blue;">&gt;
&lt;/</span><span style="color:#a31515;">Button</span><span style="color:blue;">&gt;</span></pre>
<p>The last thing we need to do is fire NotifyPropertyChanged for CanShowCustomer in the setter for the&nbsp; SelectedCustomer property.</p>
<pre class="code"><span style="color:blue;">private </span><span style="color:#2b91af;">Customer </span>selectedCustomer;
<span style="color:blue;">public </span><span style="color:#2b91af;">Customer </span>SelectedCustomer
{
    <span style="color:blue;">get </span>{ <span style="color:blue;">return </span>selectedCustomer; }
    <span style="color:blue;">set
    </span>{
        selectedCustomer = <span style="color:blue;">value</span>;
        NotifyPropertyChanged(m =&gt; m.SelectedCustomer);

        <span style="color:green;">// Update bindings for CanShowCustomer
        </span>NotifyPropertyChanged(m =&gt; m.CanShowCustomer);
    }
}</pre>
<p>These examples illustrate how to wire up View events to ViewModel methods without using commands or the need for an EventToCommand behavior.&nbsp; It works with all events on all controls and can be used to call parameterless methods on the ViewModel. I would only use commands in the case where you want to add a parameter to the ViewModel method with a hard-coded value passed in from the View via a CommandParameter.&nbsp; For an example of this approach, take a look at my <a href="http://blog.tonysneed.com/2011/03/03/climb-onboard-on-the-mvvm-message-bus">blog post</a> on ViewModel-driven navigation, where I pass in the name of a page to a Navigate method on the ViewModel.</p>
<p>Enjoy,<br />Tony</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tonysneed.wordpress.com/347/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tonysneed.wordpress.com/347/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tonysneed.wordpress.com/347/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tonysneed.wordpress.com/347/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tonysneed.wordpress.com/347/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tonysneed.wordpress.com/347/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tonysneed.wordpress.com/347/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tonysneed.wordpress.com/347/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tonysneed.wordpress.com/347/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tonysneed.wordpress.com/347/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tonysneed.wordpress.com/347/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tonysneed.wordpress.com/347/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tonysneed.wordpress.com/347/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tonysneed.wordpress.com/347/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&amp;blog=14038854&amp;post=347&amp;subd=tonysneed&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.tonysneed.com/2011/07/22/commands-versus-event-triggers-in-mvvm/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/878b354347e93c317b20a2a540f3ce04?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tonysneed</media:title>
		</media:content>
	</item>
		<item>
		<title>Validation with Simple MVVM Toolkit</title>
		<link>http://blog.tonysneed.com/2011/07/10/validation-with-simple-mvvm-toolkit/</link>
		<comments>http://blog.tonysneed.com/2011/07/10/validation-with-simple-mvvm-toolkit/#comments</comments>
		<pubDate>Mon, 11 Jul 2011 00:23:48 +0000</pubDate>
		<dc:creator>Tony Sneed</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[MVVM]]></category>

		<guid isPermaLink="false">https://tonysneed.wordpress.com/2011/07/10/validation-with-simple-mvvm-toolkit/</guid>
		<description><![CDATA[In version 2.1 of Simple MVVM Toolkit I added support for validation with INotifyDataErrorInfo. This interface obsolesces IDataErrorInfo because it does everything that interface did but enables additional functionality: Multiple validation errors per property Entity-level validation Asynchronous server-side validation INotifyDataErrorInfo &#8230; <a href="http://blog.tonysneed.com/2011/07/10/validation-with-simple-mvvm-toolkit/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&amp;blog=14038854&amp;post=346&amp;subd=tonysneed&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In version 2.1 of Simple MVVM Toolkit I added support for validation with <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifydataerrorinfo%28VS.95%29.aspx">INotifyDataErrorInfo</a>. This interface obsolesces IDataErrorInfo because it does everything that interface did but enables <a href="http://www.silverlight.net/learn/whitepapers/introducing-new-inotifydataerrorinfo-interface">additional functionality</a>:</p>
<ul>
<li>Multiple validation errors per property
<li>Entity-level validation
<li>Asynchronous server-side validation</li>
</ul>
<p>INotifyDataErrorInfo is supported by Silverlight 4, but it is not supported by WPF and will only have limited support in Windows Phone 7.1. The interface is defined as follows:</p>
<pre class="code"><span style="color:blue;">public interface </span><span style="color:#2b91af;">INotifyDataErrorInfo
</span>{
<span style="color:green;">    </span><span style="color:blue;">bool </span>HasErrors { <span style="color:blue;">get</span>; }
<span style="color:green;">    </span><span style="color:blue;">event </span><span style="color:#2b91af;">EventHandler</span>&lt;<span style="color:#2b91af;">DataErrorsChangedEventArgs</span>&gt; ErrorsChanged;
<span style="color:green;">    </span><span style="color:#2b91af;">IEnumerable </span>GetErrors(<span style="color:blue;">string </span>propertyName);
}</pre>
<p>I believe the best place to implement this interface is at the <em>model-level</em>.&nbsp; In WCF RIA Services, for example, the <font face="Courier New">Entity</font> class, which is the base class for client-side entities, implements INotifyDataErrorInfo.&nbsp; Similarly, the <font face="Courier New">ModelBase</font> class in the <font face="Courier New">SimpleMvvmToolkit</font> namespace, implements this interface, for scenarios in which you are not using WCF RIA Services.</p>
<p>In the <font face="Courier New">ViewModelDetailBase </font>class, which accepts a TModel type argument, supports validation with an IsValid property.&nbsp; It checks to see if the model implements INotifyDataErrorInfo and, if so, returns true if the HasErrors property is true.&nbsp; When a PropertyChanged event fires on the model, ViewModelDetailBase calls NotifyPropertyChanged for the IsValid property.&nbsp; You might, for example, bind the IsEnabled property of a Save button to the IsValid property of the ViewModel.&nbsp; When properties are changed on the Model, the Save button would be disabled if there were any validation errors.</p>
<p>Performing validation with INotifyDataErrorInfo is very powerful.&nbsp; It integrates well with DataAnnotations, so that you can apply attributes to class properties to enforce validation.&nbsp; By default, the Binding markup extension supports INotifyDataErrorInfo and will transition to a validation visual state when the ErrorsChanged event fires.&nbsp; Here is an example of requiring a non-blank value with a maximum string length of 50 characters for the Name property of the Item entity</p>
<pre class="code"><span style="color:blue;">class </span><span style="color:#2b91af;">Item
</span>{
    [<span style="color:#2b91af;">Required</span>()]
    [<span style="color:#2b91af;">StringLength</span>(50)]
    <span style="color:blue;">public string </span>Name
    {
        <span style="color:blue;">get
        </span>{
            <span style="color:blue;">return this</span>._name;
        }
        <span style="color:blue;">set
        </span>{
            <span style="color:blue;">if </span>((<span style="color:blue;">this</span>._name != <span style="color:blue;">value</span>))
            {
                <span style="color:blue;">this</span>.ValidateProperty(<span style="color:#a31515;">"Name"</span>, <span style="color:blue;">value</span>);
                <span style="color:blue;">this</span>._name = <span style="color:blue;">value</span>;
                <span style="color:blue;">this</span>.RaiseDataMemberChanged(<span style="color:#a31515;">"Name"</span>);
            }
        }
    }
}</pre>
<p>While you could write this code yourself, deriving the Item entity from ModelBase, there’s no need if you are using WCF RIA Services, which automatically inserts the [Required] and [StringLength] attributes based on the database column attributes. The ValidateProperty method calls Validator.TryValidateProperty under the covers, which uses reflection to inspect the data annotation attributes and populate the errors collection for that property. (For more information on entity-level and async validation, see my <a href="http://blog.tonysneed.com/2011/04/20/wcf-ria-services-webinar">webinar</a> on WCF RIA Services.)&nbsp; When there are one or more validation errors, you’ll see a red outline around the offending textbox with a label showing the error message.</p>
<p><a href="http://tonysneed.files.wordpress.com/2011/07/item_validation.png"><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="item_validation" border="0" alt="item_validation" src="http://tonysneed.files.wordpress.com/2011/07/item_validation_thumb.png?w=564&#038;h=219" width="564" height="219"></a></p>
<p>Notice that the OK button is disabled while there are validation errors.&nbsp; That is accomplished simply by binding IsEnabled on the button to IsValid on the ViewModel.</p>
<pre class="code"><span style="color:blue;">&lt;</span><span style="color:#a31515;">Button </span><span style="color:red;">Content</span><span style="color:blue;">="OK" </span><span style="color:red;">Click</span><span style="color:blue;">="OKButton_Click"
    </span><span style="color:red;">IsEnabled</span><span style="color:blue;">="{</span><span style="color:#a31515;">Binding </span><span style="color:red;">Path</span><span style="color:blue;">=IsValid, </span><span style="color:red;">Mode</span><span style="color:blue;">=TwoWay}"/&gt;</span></pre>
<p>This example uses a handler in the View code-behind, but more likely you would use either an event trigger (with the Blend SDK installed) or a command with a CanExecute method. (I’ll elaborate on triggers versus commands, and when to use each, in a future post.)</p>
<p>While we’re on the topic of validation, it seems appropriate to discuss another feature added to version 2.1 of the toolkit, which is <em>dirty-checking</em>.&nbsp; ViewModelDetailBase now sports an IsDirty property.&nbsp; IsDirty calls an extension method called AreSame, which compares an entity with the clone that is created when BeginEdit is called.&nbsp; This method simply or’s together the hash codes of each property on the objects and compares them.&nbsp; Complex objects can override GetHashCode to implement custom comparisons.</p>
<p>One thing I’d like to mention that that, when it comes to validation and dirty-checking, there are certain properties you might want to exclude.&nbsp; For example, entities in RIA Services have all kinds of properties that you would want to exclude from dirty-checking (EntityState, EntityConflict, EntityActions, etc). ViewModelDetailBase therefore has ModelMetadataProperties property with a list of property names excluded from both validation and dirty-checking.&nbsp; It is defined as virtual so you can replace it if you wish.</p>
<p>To see validation in action, simply <a href="http://simplemvvmtoolkit.codeplex.com/releases/view/69754">download</a> and install the Simple MVVM Toolkit, then open up the SimpleMvvm-RiaValidation sample application and look at the ItemListViewModel class.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tonysneed.wordpress.com/346/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tonysneed.wordpress.com/346/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tonysneed.wordpress.com/346/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tonysneed.wordpress.com/346/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tonysneed.wordpress.com/346/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tonysneed.wordpress.com/346/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tonysneed.wordpress.com/346/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tonysneed.wordpress.com/346/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tonysneed.wordpress.com/346/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tonysneed.wordpress.com/346/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tonysneed.wordpress.com/346/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tonysneed.wordpress.com/346/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tonysneed.wordpress.com/346/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tonysneed.wordpress.com/346/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&amp;blog=14038854&amp;post=346&amp;subd=tonysneed&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.tonysneed.com/2011/07/10/validation-with-simple-mvvm-toolkit/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/878b354347e93c317b20a2a540f3ce04?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tonysneed</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/07/item_validation_thumb.png" medium="image">
			<media:title type="html">item_validation</media:title>
		</media:content>
	</item>
	</channel>
</rss>
