<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Tallan&#039;s Technology Blog &#187; .net</title>
	<atom:link href="http://blog.tallan.com/tag/net/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.tallan.com</link>
	<description>Tallan&#039;s Top Technologists Share Their Thoughts on Today&#039;s Technology Challenges</description>
	<lastBuildDate>Fri, 03 Feb 2012 17:23:33 +0000</lastBuildDate>
	
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Automatically log errors with Elmah in Script0Service-WebService calls</title>
		<link>http://blog.tallan.com/2012/02/03/automatically-log-errors-with-elmah-in-script0service-webservice-calls/</link>
		<comments>http://blog.tallan.com/2012/02/03/automatically-log-errors-with-elmah-in-script0service-webservice-calls/#comments</comments>
		<pubDate>Fri, 03 Feb 2012 17:23:33 +0000</pubDate>
		<dc:creator>Karl Schwirz</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[.net]]></category>

		<guid isPermaLink="false">http://blog.tallan.com/2012/02/03/automatically-log-errors-with-elmah-in-script0service-webservice-calls/</guid>
		<description><![CDATA[If you’ve used Elmah logging in the past then you know it’s a very useful and easy to set up tool in your web applications.&#160; However, when we encounter errors in web services we sometimes do not get the desired logging into the xml file or database, depending on how you have Elmah configured.&#160; This [...]]]></description>
			<content:encoded><![CDATA[<p>If you’ve used Elmah logging in the past then you know it’s a very useful and easy to set up tool in your web applications.&#160; However, when we encounter errors in web services we sometimes do not get the desired logging into the xml file or database, depending on how you have Elmah configured.&#160; This is because when a error occurs in a script service enabled web service, the errors get serialized into JSON and returned to the ajax caller which is then take by the javascript to handle the exception.&#160; The application is left unaware of the exception occurrence. </p>
<p>There is a way however, to intercept the message before it is returned to the front-end and log the error automatically the way we are used to with Elmah.</p>
<p>First we set up an ErrorHandlerFilter class which will override the default error stream message ( {“Message”:”There was an error processing the request.”, “StackTrace”:””, “ExceptionType”:””})} with a more meaningful error message with details.</p>
<div>
<div>
<pre><span style="color: #606060">   1:</span> <span style="color: #0000ff">using</span> System;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   2:</span> <span style="color: #0000ff">using</span> System.Collections.Generic;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   3:</span> <span style="color: #0000ff">using</span> System.IO;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   4:</span> <span style="color: #0000ff">using</span> System.Linq;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   5:</span> <span style="color: #0000ff">using</span> System.Text;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   6:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   7:</span> <span style="color: #0000ff">namespace</span> Namespace.ElmahExtension</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   8:</span> {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   9:</span>     <span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> ErrorHandlerFilter : Stream</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  10:</span>     {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  11:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  12:</span>         <span style="color: #0000ff">private</span> <span style="color: #0000ff">readonly</span> Stream _responseFilter;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  13:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  14:</span>         <span style="color: #0000ff">public</span> List&lt;<span style="color: #0000ff">byte</span>&gt; OriginalBytesWritten { get; <span style="color: #0000ff">private</span> set; }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  15:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  16:</span>         <span style="color: #0000ff">private</span> <span style="color: #0000ff">const</span> <span style="color: #0000ff">string</span> Content =</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  17:</span>           <span style="color: #006080">&quot;{\&quot;Message\&quot;:\&quot;There was an error processing the request.\&quot;&quot;</span> +</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  18:</span>           <span style="color: #006080">&quot;,\&quot;StackTrace\&quot;:\&quot;\&quot;,\&quot;ExceptionType\&quot;:\&quot;\&quot;}&quot;</span>;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  19:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  20:</span>         <span style="color: #0000ff">public</span> ErrorHandlerFilter(Stream responseFilter)</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  21:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  22:</span>             _responseFilter = responseFilter;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  23:</span>             OriginalBytesWritten = <span style="color: #0000ff">new</span> List&lt;<span style="color: #0000ff">byte</span>&gt;();</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  24:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  25:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  26:</span>         <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">void</span> Flush()</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  27:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  28:</span>             <span style="color: #0000ff">byte</span>[] bytes = Encoding.UTF8.GetBytes(Content);</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  29:</span>             _responseFilter.Write(bytes, 0, bytes.Length);</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  30:</span>             _responseFilter.Flush();</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  31:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  32:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  33:</span>         <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">long</span> Seek(<span style="color: #0000ff">long</span> offset, SeekOrigin origin)</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  34:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  35:</span>             <span style="color: #0000ff">return</span> _responseFilter.Seek(offset, origin);</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  36:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  37:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  38:</span>         <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">void</span> SetLength(<span style="color: #0000ff">long</span> <span style="color: #0000ff">value</span>)</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  39:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  40:</span>             _responseFilter.SetLength(<span style="color: #0000ff">value</span>);</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  41:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  42:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  43:</span>         <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">int</span> Read(<span style="color: #0000ff">byte</span>[] buffer, <span style="color: #0000ff">int</span> offset, <span style="color: #0000ff">int</span> count)</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  44:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  45:</span>             <span style="color: #0000ff">return</span> _responseFilter.Read(buffer, offset, count);</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  46:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  47:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  48:</span>         <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">void</span> Write(<span style="color: #0000ff">byte</span>[] buffer, <span style="color: #0000ff">int</span> offset, <span style="color: #0000ff">int</span> count)</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  49:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  50:</span>             <span style="color: #0000ff">for</span> (<span style="color: #0000ff">int</span> i = offset; i &lt; offset + count; i++)</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  51:</span>             {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  52:</span>                 OriginalBytesWritten.Add(buffer[i]);</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  53:</span>             }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  54:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  55:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  56:</span>         <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">bool</span> CanRead</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  57:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  58:</span>             get { <span style="color: #0000ff">return</span> _responseFilter.CanRead; }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  59:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  60:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  61:</span>         <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">bool</span> CanSeek</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  62:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  63:</span>             get { <span style="color: #0000ff">return</span> _responseFilter.CanSeek; }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  64:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  65:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  66:</span>         <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">bool</span> CanWrite</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  67:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  68:</span>             get { <span style="color: #0000ff">return</span> _responseFilter.CanWrite; }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  69:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  70:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  71:</span>         <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">long</span> Length</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  72:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  73:</span>             get { <span style="color: #0000ff">return</span> _responseFilter.Length; }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  74:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  75:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  76:</span>         <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">long</span> Position</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  77:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  78:</span>             get { <span style="color: #0000ff">return</span> _responseFilter.Position; }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  79:</span>             set { _responseFilter.Position = <span style="color: #0000ff">value</span>; }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  80:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  81:</span>     }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  82:</span> }</pre>
<p><!--CRLF--></div>
</div>
<p>Now, we’re going to need to set up a class that implements I<em>HttpModule.&#160; </em>which we’ll use to intercept the message being passed after the <em>Request </em>and <em>EndRequest</em> handlers execute.</p>
<div>
<div>
<pre><span style="color: #606060">   1:</span> <span style="color: #0000ff">using</span> System;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   2:</span> <span style="color: #0000ff">using</span> System.Diagnostics;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   3:</span> <span style="color: #0000ff">using</span> System.IO;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   4:</span> <span style="color: #0000ff">using</span> System.Text;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   5:</span> <span style="color: #0000ff">using</span> System.Web;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   6:</span> <span style="color: #0000ff">using</span> System.Web.Services.Protocols;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   7:</span> <span style="color: #0000ff">using</span> Elmah;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   8:</span>  </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   9:</span> <span style="color: #0000ff">namespace</span> Namespace.ElmahExtension</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  10:</span> {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  11:</span>     <span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> ElmahExtension : IHttpModule</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  12:</span>     {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  13:</span>         <span style="color: #0000ff">private</span> HttpApplication _application;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  14:</span>  </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  15:</span>         <span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Dispose()</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  16:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  17:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  18:</span>  </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  19:</span>         <span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Init(HttpApplication context)</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  20:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  21:</span>             _application = context;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  22:</span>             _application.PostRequestHandlerExecute += OnPostRequestHandlerExecute;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  23:</span>             _application.EndRequest += OnEndRequest;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  24:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  25:</span>  </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  26:</span>         <span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> OnPostRequestHandlerExecute(<span style="color: #0000ff">object</span> sender, EventArgs e)</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  27:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  28:</span>             var context = sender <span style="color: #0000ff">as</span> HttpApplication;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  29:</span>             <span style="color: #0000ff">if</span>(context != <span style="color: #0000ff">null</span> &amp;&amp; (context.Request.Path.Contains(<span style="color: #006080">&quot;.asmx&quot;</span>) &amp;&amp; (context.Response.StatusCode &gt;= 400 &amp;&amp; context.Response.StatusCode &lt; 600)))</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  30:</span>             {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  31:</span>                 context.Response.Filter = <span style="color: #0000ff">new</span> ErrorHandlerFilter(context.Response.Filter);</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  32:</span>             }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  33:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  34:</span>  </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  35:</span>         <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> OnEndRequest(<span style="color: #0000ff">object</span> sender, EventArgs e) </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  36:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  37:</span>             var context = (HttpApplication)sender;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  38:</span>             var errorHandlerFilter = context.Response.Filter <span style="color: #0000ff">as</span> ErrorHandlerFilter;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  39:</span>  </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  40:</span>             <span style="color: #0000ff">if</span> (errorHandlerFilter == <span style="color: #0000ff">null</span>)</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  41:</span>             {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  42:</span>                 <span style="color: #0000ff">return</span>;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  43:</span>             }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  44:</span>  </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  45:</span>             var originalContent = Encoding.UTF8.GetString(errorHandlerFilter.OriginalBytesWritten.ToArray());</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  46:</span>             ErrorLog.GetDefault(context.Context).Log(<span style="color: #0000ff">new</span> Error(<span style="color: #0000ff">new</span> Exception(originalContent)));</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  47:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  48:</span>     }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  49:</span>  </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  50:</span> }</pre>
<p><!--CRLF--></div>
</div>
<p>Notice in the <em>OnPostRequestHandlerExecute </em>function we’re intercepting any request that comes from a Webservice (.asmx page) and has a status code of greater than 400 (All error code types).&#160; At his point we want to set the ErrorHandelerFilter to the current Response.Filter value.</p>
<p>Now in the OnEndRequest function we want to get the current context and set the error handler based on the filter which should now be persisting the values we set in the previous function.&#160; Once we have the error values all we have to do is call the Elmah manual logging API and log the exception. </p>
<p>The final piece you have to do is set up the webConfig to recognize and use your I<em>HttpModule </em>code. n In your config file navigate down to System.Web &gt;&gt; HttpModules and fill in the attribute accordingly.</p>
<div>
<div>
<pre><span style="color: #606060">   1:</span> <span style="color: #0000ff">&lt;</span><span style="color: #800000">system.web</span><span style="color: #0000ff">&gt;</span></pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   2:</span>     <span style="color: #0000ff">&lt;</span><span style="color: #800000">httpModules</span><span style="color: #0000ff">&gt;</span>    </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   3:</span>       <span style="color: #0000ff">&lt;</span><span style="color: #800000">add</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;ElmahExtension&quot;</span> <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;Namespace.ElmahExtension.ElmahExtension&quot;</span><span style="color: #0000ff">/&gt;</span></pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   4:</span>     <span style="color: #0000ff">&lt;/</span><span style="color: #800000">httpModules</span><span style="color: #0000ff">&gt;</span></pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   5:</span> <span style="color: #0000ff">&lt;/</span><span style="color: #800000">system.web</span><span style="color: #0000ff">&gt;</span></pre>
<p><!--CRLF--></div>
</div>
<p>Once you compile and run, any errors encountered in your web services should now be logged by Elmah just like any others.</p>
<p>&#160;</p>
<p>Thanks to Reddy Kadasani, Mike Gerety and Dylan Barrett for their contributions to this solution.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tallan.com/2012/02/03/automatically-log-errors-with-elmah-in-script0service-webservice-calls/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Calling an ASP.Net web service using jQuery and JSON.</title>
		<link>http://blog.tallan.com/2012/01/29/calling-an-asp-net-web-service-using-jquery-and-json/</link>
		<comments>http://blog.tallan.com/2012/01/29/calling-an-asp-net-web-service-using-jquery-and-json/#comments</comments>
		<pubDate>Sun, 29 Jan 2012 19:09:27 +0000</pubDate>
		<dc:creator>Karl Schwirz</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Ajax]]></category>
		<category><![CDATA[Enterprise .NET]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://blog.tallan.com/2012/01/29/calling-an-asp-net-web-service-using-jquery-and-json/</guid>
		<description><![CDATA[Let’s say you have a webpage where you need to call a service but cannot perform a post back.&#160; Recently I was on a client engagement where we needed to improve page performance by dynamically loading a navigation tree with a potential for several thousand links.&#160; We implemented a solution that would load each branch [...]]]></description>
			<content:encoded><![CDATA[<p>Let’s say you have a webpage where you need to call a service but cannot perform a post back.&#160; Recently I was on a client engagement where we needed to improve page performance by dynamically loading a navigation tree with a potential for several thousand links.&#160; We implemented a solution that would load each branch as the user clicked on the expanding icon by calling a web service via ajax and passing the required links back to the page and render them client side.&#160; This saved immensely on the load time for the page and improved the user experience </p>
<p>This kind of solution can be applied to several situations such as complex data processing, dynamic loading, or combining them all into a seamless form submission process that would clear the form on post backs. </p>
<p>We can accomplish this process simply by grabbing an event, such as a button click, and collecting all the required information using jQuery.&#160; Next using a JSON call, we can pass all the parameters to the web service and execute our code from there.</p>
<p>Here, I’ll start with a simple .aspx page with jquery, a textbox, and link that will be used to call the web service.</p>
<div>
<div>
<pre><span style="color: #606060">   1:</span> <span style="background-color: #ffff00">&lt;%@ Master Language=&quot;C#&quot; MasterPageFile=&quot;~/Site.Master&quot; AutoEventWireup=&quot;true&quot; CodeBehind=&quot;ThisPage.cs&quot; Inherits=&quot;ThisSolution.ThisProject.ThisFolder&quot; %&gt;</span></pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   2:</span>  </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   3:</span> <span style="color: #0000ff">&lt;</span><span style="color: #800000">asp:Content</span> <span style="color: #ff0000">ID</span><span style="color: #0000ff">=&quot;Content1&quot;</span> <span style="color: #ff0000">ContentPlaceHolderID</span><span style="color: #0000ff">=&quot;HeadContent&quot;</span> <span style="color: #ff0000">runat</span><span style="color: #0000ff">=&quot;server&quot;</span><span style="color: #0000ff">&gt;</span></pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   4:</span>     <span style="color: #0000ff">&lt;</span><span style="color: #800000">script</span> <span style="color: #ff0000">src</span><span style="color: #0000ff">=&quot;/Scripts/jquery-1.4.1.min.js&quot;</span> <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;text/javascript&quot;</span><span style="color: #0000ff">/&gt;</span></pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   5:</span> <span style="color: #0000ff">&lt;/</span><span style="color: #800000">asp:Content</span><span style="color: #0000ff">&gt;</span></pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   6:</span>  </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   7:</span> <span style="color: #0000ff">&lt;</span><span style="color: #800000">asp:Content</span> <span style="color: #ff0000">ID</span><span style="color: #0000ff">=&quot;Content2&quot;</span> <span style="color: #ff0000">ContentPlaceHolderID</span><span style="color: #0000ff">=&quot;MainContent&quot;</span> <span style="color: #ff0000">runat</span><span style="color: #0000ff">=&quot;server&quot;</span><span style="color: #0000ff">&gt;</span></pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   8:</span>     <span style="color: #0000ff">&lt;</span><span style="color: #800000">asp:TextBox</span> <font color="#ff0000">ID</font>=”<font color="#0000ff">textBox</font>” <span style="color: #ff0000">TextMode</span><span style="color: #0000ff">=&quot;MultiLine&quot;</span> <span style="color: #ff0000">runat</span><span style="color: #0000ff">=&quot;server&quot;</span><span style="color: #0000ff">&gt;&lt;/</span><span style="color: #800000">asp:TextBox</span><span style="color: #0000ff">&gt;</span></pre>
<p><!--CRLF--></p>
<pre>

<span style="color: #606060">   9:</span>     <span style="color: #0000ff">&lt;</span><span style="color: #800000">a</span> <span style="color: #ff0000">href</span><span style="color: #0000ff">=&quot;#&quot;</span> <span style="color: #ff0000">class</span><span style="color: #0000ff">=&quot;buttonClass&quot;</span><span style="color: #0000ff">&gt;</span> Save <span style="color: #0000ff">&lt;/</span><span style="color: #800000">a</span><span style="color: #0000ff">&gt;</span>

<span style="color: #0000ff">  <font color="#a5a5a5">10</font>:     <span style="color: #0000ff">&lt;</span><span style="color: #800000">asp:Label</span> <font color="#ff0000">ID</font>=”<font color="#0000ff">successLabel</font>” <span style="color: #ff0000">runat</span><span style="color: #0000ff">=&quot;server&quot;</span><span style="color: #0000ff">&gt;&lt;/</span><span style="color: #800000">asp:Label</span><span style="color: #0000ff">&gt;</span></span>
</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  11:</span> <span style="color: #0000ff">&lt;/</span><span style="color: #800000">asp:Content</span><span style="color: #0000ff">&gt;</span></pre>
<p><!--CRLF--></div>
</div>
<p>Next, you will need to establish your web service and create an .asmx file.&#160; There are a couple of important things to note here. Line 5 will be by default commented out.&#160; So in order for us to make our JSON call we’re going to need this <em>uncommented</em>.&#160; Also, notice I’m returning a string.&#160; For the purposes of this demo I am going to return a string to the UI and display a message, but you can return any kind of object that can be serialized down to a primitive data type.</p>
<div>
<div>
<pre><span style="color: #606060">   1:</span> [WebService(Namespace = <span style="color: #006080">&quot;http://tempuri.org/&quot;</span>)]</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   2:</span> [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   3:</span> [System.ComponentModel.ToolboxItem(<span style="color: #0000ff">false</span>)]</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   4:</span> <span style="color: #008000">// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. </span></pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   5:</span> [System.Web.Script.Services.ScriptService]</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   6:</span> <span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> wService : System.Web.Services.WebService</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   7:</span> {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   8:</span>     [WebMethod()]</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   9:</span>     [ScriptMethod(UseHttpGet = <span style="color: #0000ff">false</span>, ResponseFormat = ResponseFormat.Json)]</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  10:</span>     <span style="color: #0000ff">public</span> <span style="color: #0000ff">string</span> UpdateComment(<span style="color: #0000ff">string</span> textBoxText)</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  11:</span>     {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  12:</span>         var success = Service.CallToDb(textBoxText);</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  13:</span>  </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  14:</span>         <span style="color: #0000ff">if</span>(success)</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  15:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  16:</span>             <span style="color: #0000ff">return</span> <span style="color: #006080">&quot;Call to Database using text was successful&quot;</span>;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  17:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  18:</span>         <span style="color: #0000ff">else</span> </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  19:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  20:</span>             <span style="color: #0000ff">return</span> <span style="color: #006080">&quot;Call to Database using text was not successful&quot;</span>;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  21:</span>         }    </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  22:</span>     }           </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  23:</span> }</pre>
<p><!--CRLF--></div>
</div>
<p>I use a jQuery selector to pick up on the mouse click of the link and gather our data into an javascript object.&#160; Note that when passing parameters through this object you have to name them the same way as you do in the parameter declaration of the web service.</p>
<p>When setting up the call to the service you’re going to want to remember to call the “JSON.stringify” function on your data object so that it serializes properly and that your contentType as well as dataType are configured properly as well.</p>
<div>
<div>
<pre><span style="color: #606060">   1:</span> &lt;script type=<span style="color: #006080">'text/javascript&gt;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   2:</span>     $('</span>.buttonClass<span style="color: #006080">').live('</span>click<span style="color: #006080">', function(){</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   3:</span>         var text = $('</span>#textBox<span style="color: #006080">').text();</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   4:</span>         var data = new Object();</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   5:</span>         data.textBoxText = text;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   6:</span>  </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   7:</span>         $.ajax({</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   8:</span>             type: &quot;POST&quot;,</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   9:</span>             url: &quot;/Ajax/WbServcie.asmx/UpdateComment&quot;,</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  10:</span>             data: JSON.stringify(data),</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  11:</span>             contentType: &quot;application/json; charset=utf-8&quot;,</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  12:</span>             dataType: &quot;json&quot;,</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  13:</span>             success: function(msg){</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  14:</span>                 $('</span>#successLabel<span style="color: #006080">').val(msg);</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  15:</span>             },</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  16:</span>             error: function(msg){</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  17:</span>                 alert('</span>Something, somewhere, has gone terribly wrong');</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  18:</span>                 <span style="color: #0000ff">return</span> <span style="color: #0000ff">false</span>;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  19:</span>             }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  20:</span>         });    </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  21:</span> &lt;/script&gt;</pre>
<p><!--CRLF--></div>
</div>
<p>Once you get a response from the service, you can set any of your data that is returned.&#160; In this case, we’re returning a string indicating the call to the database was successful and will set a label on the page to show that.</p>
<p>And that’s it.&#160; With just a few simple configurations we have a quick call back to the server without having to run an expensive post back. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tallan.com/2012/01/29/calling-an-asp-net-web-service-using-jquery-and-json/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mobile Site Development becoming as important as Desktop.</title>
		<link>http://blog.tallan.com/2012/01/25/mobile-site-development-becoming-as-important-as-desktop/</link>
		<comments>http://blog.tallan.com/2012/01/25/mobile-site-development-becoming-as-important-as-desktop/#comments</comments>
		<pubDate>Wed, 25 Jan 2012 22:12:39 +0000</pubDate>
		<dc:creator>Karl Schwirz</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://blog.tallan.com/2012/01/25/mobile-site-development-becoming-as-important-as-desktop/</guid>
		<description><![CDATA[In recent years, the boom in mobile devices has caused more and more users to abandon their desktop internet browsers and opt for the ones sitting in their pocket. As a result, nearly 10% of 2011’s internet traffic was attributed to mobile device browsers. As more people are browsing the internet in this manner, it [...]]]></description>
			<content:encoded><![CDATA[<p>In recent years, the boom in mobile devices has caused more and more users to abandon their desktop internet browsers and opt for the ones sitting in their pocket. As a result, nearly 10% of 2011’s internet traffic was attributed to mobile device browsers. As more people are browsing the internet in this manner, it is important that currently standing websites, as well as newly developed ones, also include mobile friendly pages in their site.</p>
<p>Many companies have followed models put forth by sites such as <a href="http://www.amazon.com">www.amazon.com</a>, with their widely known desktop interface for purchasing products. When the mobile markets started to pick up they developed a mobile site that operates in much the same way, but offers a friendlier user experience for those viewing it on a smartphone screen. This move to a mobile intuitive platform can generate an increase in traffic and user engagement with the site by up to 85%.</p>
<p><a href="http://blog.tallan.com/wp-content/uploads/2012/01/clip_image001.png"><img style="border-bottom: 0px;border-left: 0px;margin: 0px 0px 18px;padding-left: 0px;padding-right: 0px;border-top: 0px;border-right: 0px;padding-top: 0px" border="0" alt="clip_image001" src="http://blog.tallan.com/wp-content/uploads/2012/01/clip_image001_thumb.png" width="536" height="273" /></a></p>
<p>A push to a mobile platform such as this doesn’t have to be expensive either. On a recent client engagement, I developed a mobile version of their desktop website that was established prior to my arrival. While building the mobile pages I was able to reuse a lot of the code behind, but with some simple device detection logic I finished the project a lot sooner and cheaper than if I had to develop a new site form square one.</p>
<p>Currently, 1 in 4 mobile devices are smartphones, and with the relatively low incremental development cost, and the prospect that mobile device users will overtake the number of desktop casual browsers by 2014, the importance of developing mobile friendly sites in tandem with their desktop versions will increase and will be a great benefit to any client with public facing websites. </p>
<p>Mobile usage statistics courtesy of <a href="http://blog.kissmetrics.com/mobile-mania/">KissMetrics</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tallan.com/2012/01/25/mobile-site-development-becoming-as-important-as-desktop/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>.NET File Compression in Memory</title>
		<link>http://blog.tallan.com/2011/02/22/net-file-compression-in-memory/</link>
		<comments>http://blog.tallan.com/2011/02/22/net-file-compression-in-memory/#comments</comments>
		<pubDate>Tue, 22 Feb 2011 19:39:52 +0000</pubDate>
		<dc:creator>Karl Schwirz</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Enterprise .NET]]></category>
		<category><![CDATA[User Groups]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[file compression]]></category>
		<category><![CDATA[SMTP]]></category>

		<guid isPermaLink="false">http://blog.tallan.com/?p=1026</guid>
		<description><![CDATA[File compression is nothing new to .NET.&#160; However, in many solutions it requires the developer to establish a file folder which they will write the compressed file to and later read from. 
This solution cannot work if you want to compress and use the file in memory without writing to disk.&#160; An example of this [...]]]></description>
			<content:encoded><![CDATA[<p>File compression is nothing new to .NET.&#160; However, in many solutions it requires the developer to establish a file folder which they will write the compressed file to and later read from. </p>
<p>This solution cannot work if you want to compress and use the file in memory without writing to disk.&#160; An example of this could be on a server where you don&#8217;t particularly want to have random processes writing to and reading files.&#160; </p>
<p>Listed below is a solution we came up with for compressing a file in memory. We used an open source library SharpZipLib from <a href="http://blog.tallan.com/wp-admin/www.sharpdevelop.net/OpenSource/SharpZipLib/">sharpDevelop.net</a>.&#160; There are other good options out there that could also be used.&#160; We found that using this library offered the most intuitive solution to creating the archive file. </p>
<p>The result will be a Stream which can be used to send the compressed data to an FTP Site, attach and send in an email, or if you don&#8217;t have any restrictions, write to a local folder. </p>
<p>First we will declare a method that reads in a string of data, initialize a MemoryStream and ZipOutputStram.</p>
<pre><span style="color: blue"></span></pre>
<pre><span style="color: blue">using <font color="#000000">ICSharpZipCode.SharpZipLib.Zip;</font></span></pre>
<pre><span style="color: blue"><font color="#000000">…</font></span></pre>
<pre><span style="color: blue">public static byte</span>[] CompressFile(<span style="color: blue">string </span>fileContents)
        {
            <span style="color: green">//Initialize memory stream the compressed data will be written to
            </span><span style="color: blue">using </span>(<span style="color: teal">MemoryStream </span>outMs = <span style="color: blue">new </span><span style="color: teal">MemoryStream</span>())
            {
                <span style="color: blue">using </span>(<span style="color: teal">ZipOutputStream </span>zipOut = <span style="color: blue">new </span><span style="color: teal">ZipOutputStream</span>(outMs))
                {
                    <span style="color: teal">ZipEntry </span>ze = <span style="color: blue">new </span><span style="color: teal">ZipEntry</span>(<span style="color: maroon">&quot;OriginalMessage.txt&quot;</span>);
                    ze.CompressionMethod = <span style="color: teal">CompressionMethod</span>.Deflated;
                    zipOut.PutNextEntry(ze);

                    <span style="color: green">//Write the string to the to buffer that will be fed into the ZipStream
                    </span><span style="color: blue">byte</span>[] byteArray = <span style="color: blue">new byte</span>[fileContents.Length];
                    <span style="color: blue">int </span>index = 0;
                    <span style="color: blue">foreach </span>(<span style="color: blue">char </span>fileChar <span style="color: blue">in </span>fileContents)
                    {
                        byteArray[index] = (<span style="color: blue">byte</span>)fileChar;
                        index++;
                    }

                    <span style="color: green">//Write the compressed data to the outMs memory stream
                    </span>zipOut.Write(byteArray, 0, byteArray.Length);
                    zipOut.Finish();
                }
                <span style="color: blue">return </span>outMs.ToArray();
            }
        }</pre>
<p>This isn&#8217;t much different from other methods out there.&#160; Notice the data is written to a byte array and given to the ZipOutputStream&#8217;s compression call which in turn writes the compressed data to a memory stream.&#160; The difference here is when we return an array of the MemoryStream. </p>
<p>The reason we return the array and not the memory stream is because once we exit the scope of the method we will lose the Memory Stream and the data contents. </p>
<p>Once this compression has been done the calling class should then use some sort of stream to finish the desired functionality.&#160; Below is an example of this by attaching the compressed data to an email.</p>
<pre><span style="color: blue">public static void </span>SendTestEmailWithAttachment(<span style="color: blue">byte</span>[] message)
       {
           <span style="color: blue">try
           </span>{
              <span style="color: blue">var </span>emailClient = <span style="color: blue">new </span><span style="color: #2b91af">SmtpClient</span>(<span style="color: #a31515">&quot;mail.client.com&quot;</span>, 25)
                                 {
                                     Credentials = <span style="color: blue">new </span><span style="color: #2b91af">NetworkCredential</span>(<span style="color: #a31515">&quot;relay.client.com&quot;</span>, <span style="color: #a31515">&quot;&quot;</span>)
                                 };

              <span style="color: blue">var </span>sendFrom = <span style="color: blue">new </span><span style="color: #2b91af">MailAddress</span>(<span style="color: #a31515">&quot;karl.schwirz@tallan.com&quot;</span>);
              <span style="color: blue">var </span>sendTo = <span style="color: blue">new </span><span style="color: #2b91af">MailAddress</span>(<span style="color: #a31515">&quot;karl.schwirz@tallan.com&quot;</span>);

              <span style="color: blue">var </span>myMessage = <span style="color: blue">new </span><span style="color: #2b91af">MailMessage</span>(sendFrom, sendTo)
                               {
                                   Subject = <span style="color: #a31515">&quot;Test Email for compression&quot;</span>,
                                   Body = <span style="color: #a31515">&quot;Test Email for compression&quot;
                               </span>};

              <span style="color: blue">var </span>ct = <span style="color: blue">new </span><span style="color: #2b91af">ContentType</span>() {MediaType = <span style="color: #2b91af">MediaTypeNames</span>.<span style="color: #2b91af">Application</span>.Zip, Name = <span style="color: #a31515">&quot;Sample.zip&quot;</span>};

              <span style="color: blue">var </span>attachfile = <span style="color: blue">new </span><span style="color: #2b91af">Attachment</span>(<span style="color: blue">new </span><span style="color: #2b91af">MemoryStream</span>(message), ct);
              myMessage.Attachments.Add(attachfile);

              emailClient.Send(myMessage);
           }
           <span style="color: blue">catch </span>(<span style="color: #2b91af">Exception </span>ex)
           {
               ex.ToString();
               <span style="color: blue">throw</span>;
           }
       }</pre>
<p>Here we have a simple SMTP client that takes in the byte array we get from the compression method we developed earlier.&#160; Notice in the attachment we use a MemoryStream to add the compressed data into the email. </p>
<p>While this is a small alteration to most solutions out there, returning the compressed data this way offers the benefit of eliminating overhead associated with writing the data to a folder first, then moving it to its destination by keeping the compression completely in memory.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tallan.com/2011/02/22/net-file-compression-in-memory/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Display NuGet Console Results in a new Window</title>
		<link>http://blog.tallan.com/2010/12/15/display-nuget-console-results-in-a-new-window/</link>
		<comments>http://blog.tallan.com/2010/12/15/display-nuget-console-results-in-a-new-window/#comments</comments>
		<pubDate>Wed, 15 Dec 2010 14:31:25 +0000</pubDate>
		<dc:creator>Michael Gerety</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Enterprise .NET]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[MVC 3]]></category>
		<category><![CDATA[NuGet]]></category>

		<guid isPermaLink="false">http://blog.tallan.com/2010/12/15/display-nuget-console-results-in-a-new-window/</guid>
		<description><![CDATA[I caught a pretty awesome tip over Twitter today.
One of the annoying things about using the “Package Manager Console” in NuGet is that you’re constantly scrolling up and down the list of results.&#160; If you’re like me, and you keep your console in the lower panel in VS2010, it’s not exactly easy to see a [...]]]></description>
			<content:encoded><![CDATA[<p>I caught a pretty awesome tip over Twitter today.</p>
<p>One of the annoying things about using the “Package Manager Console” in NuGet is that you’re constantly scrolling up and down the list of results.&#160; If you’re like me, and you keep your console in the lower panel in VS2010, it’s not exactly easy to see a whole lot at once.</p>
<p><a href="http://blog.tallan.com/wp-content/uploads/2010/12/image3.png"><img style="border-bottom: 0px;border-left: 0px;margin: 0px 0px 18px;padding-left: 0px;padding-right: 0px;border-top: 0px;border-right: 0px;padding-top: 0px" border="0" alt="image" src="http://blog.tallan.com/wp-content/uploads/2010/12/image_thumb3.png" width="517" height="115" /></a></p>
<p>You can, however, output the results from your NuGet commands into a popup window by piping it out to “<strong><font face="Courier New">Out-GridView</font></strong>”.</p>
<h2>Example</h2>
<p>Execute the following command in the Package Manager Console:</p>
<p><font face="Courier New"><strong>List-Package –online | Out-GridView</strong></font></p>
<p>This time, you’ll get your results in a nice pop-up window:</p>
<p><a href="http://blog.tallan.com/wp-content/uploads/2010/12/image4.png"><img style="border-bottom: 0px;border-left: 0px;margin: 0px 0px 18px;padding-left: 0px;padding-right: 0px;border-top: 0px;border-right: 0px;padding-top: 0px" border="0" alt="image" src="http://blog.tallan.com/wp-content/uploads/2010/12/image_thumb4.png" width="512" height="192" /></a></p>
<h2>Multiple Commands?</h2>
<p>Another weird thing I didn’t know, the following command is the equivalent to the one above in NuGet.</p>
<p><font face="Courier New"><strong>Get-Package –remote | Out-Gridview</strong></font></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tallan.com/2010/12/15/display-nuget-console-results-in-a-new-window/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What&#8217;s New in ASP.NET MVC 3</title>
		<link>http://blog.tallan.com/2010/12/01/whats-new-in-asp-net-mvc-3/</link>
		<comments>http://blog.tallan.com/2010/12/01/whats-new-in-asp-net-mvc-3/#comments</comments>
		<pubDate>Wed, 01 Dec 2010 18:26:00 +0000</pubDate>
		<dc:creator>Michael Gerety</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Presentations]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[MVC 3]]></category>
		<category><![CDATA[Tech Talk]]></category>

		<guid isPermaLink="false">http://blog.tallan.com/2010/12/01/whats-new-in-asp-net-mvc-3/</guid>
		<description><![CDATA[I did a tech talk (an internal presentation for Tallan) on 11/30 with the intent to do a quick demonstration of the new features of ASP.NET MVC3.&#160; Unfortunately (or fortunately, depending on how you look at it), there’s are just too many new features to cover in a 45 minute presentation.
I’m writing a series of [...]]]></description>
			<content:encoded><![CDATA[<p>I did a tech talk (an internal presentation for Tallan) on 11/30 with the intent to do a quick demonstration of the new features of ASP.NET MVC3.&#160; Unfortunately (or fortunately, depending on how you look at it), there’s are just too many new features to cover in a 45 minute presentation.</p>
<p>I’m writing a series of blog posts to get a bit more in-depth on the new features of MVC 3.&#160; I’m going to divide this topic into a number of posts to allow you to pick and choose what to learn about, and to attempt to keep your attention.&#160; All of this in one blog post would be very lengthy and could get boring rather quickly.</p>
<p>In this post, I’ll keep it to a quick summary of the new features and a quick description of each.&#160; We’ll get into more depth in future posts.</p>
<h1>Overview of MVC 3 </h1>
<p>ASP.NET MVC is a wildly popular framework for web application development on the .NET platform, and MVC 3 is the latest iteration (currently in Release Candidate status as of the publication of this article.)</p>
<p>For those of you unfamiliar with the framework, I encourage you to visit the <a href="http://www.asp.net/mvc">Official Microsoft ASP.NET MVC</a> site and take a look.&#160; Anyone who’s been frustrated with web development on the .NET platform up until now will likely find MVC to be a refreshing and exciting change to web development.&#160; ASP.NET MVC truly feels like how web development <em>should have been all along<strong>.&#160; (For those new to MVC or interested in learning MVC in depth, watch this blog for a 10-part screencast series on ASP.NET MVC development, to be completed no later than 12/31/2010).</strong></em></p>
<h2>Some notes on MVC3:</h2>
<ul>
<li>MVC 3 can be installed via the Web Platform Installer or via the Following Link: <a href="http://go.microsoft.com/fwlink/?LinkID=191797">http://go.microsoft.com/fwlink/?LinkID=191797</a> </li>
<li>MVC3 is compatible with MVC2
<ul>
<li>There should be little to no upgrade path for MVC2 apps to work on the framework </li>
<li>Any MVC2 skills and knowledge can be applied to MVC3 development </li>
</ul>
</li>
<li>MVC3 can be installed side-by-side with MVC2 </li>
<li><strong>Important Note: </strong>Unlike previous version the framework, MVC3 <strong><em>requires Visual Studio 2010 and .NET 4.0</em></strong> </li>
</ul>
<h2>What’s New: Feature List</h2>
<p>Below is a categorized list of new features in the MVC3 Framework.&#160; Stay tuned to the <a href="http://blog.tallan.com">Tallan Enterprise Blog</a> for a 4-part screencast series covering all of the enhancements listed here.</p>
<h3>Framework and Tools</h3>
<ul>
<li>Multiple View Engine Support </li>
<li>“Razor” View Engine
<ul>
<li>New Default View Engine </li>
<li>Cleaner/More Concise than Web Forms </li>
<li>Less “ASP” Feel </li>
</ul>
</li>
<li>NuGet Package Management
<ul>
<li>Unix-Like package and dependency management </li>
</ul>
</li>
<li>Common Service Locator library
<ul>
<li>Simplifies Dependency Injection </li>
<li>Adds flexibility to DI and Dependency Resolution </li>
</ul>
</li>
</ul>
<h3>View Enhancements</h3>
<ul>
<li>New Web Helpers
<ul>
<li>Chart Helper </li>
<li>WebGrid Helper </li>
</ul>
</li>
<li>Unobtrusive Javascript and HTML 5
<ul>
<li>jQuery based client-side validation </li>
<li>jQuery based AJAX form and input </li>
</ul>
</li>
</ul>
<h4></h4>
<h3>Controller Enhancements</h3>
<ul>
<li>Global Action Filters </li>
<li>Dynamic ViewModel object </li>
<li>New Action Results
<ul>
<li>HttpNotFoundResult </li>
<li>HttpStatusCodeResult </li>
</ul>
</li>
<li>New Permanent Redirects (HTTP Status Code 301)
<ul>
<li>RedirectPermanent </li>
<li>RedirectToRoutePermanent </li>
<li>RedirectToActionPermanent </li>
</ul>
</li>
<li>Built in JSON Binding Support
<ul>
<li>Action methods support full model-binding from JSON based AJAX requests. </li>
</ul>
</li>
</ul>
<h3>Model Validation Enhancements</h3>
<ul>
<li>New .NET 4 Data Annotations </li>
<li>Improvements to validation attributes
<ul>
<li>Allows for validation based on dependent properties </li>
</ul>
</li>
<li>IValidatableObject interface
<ul>
<li>Model-Level validation </li>
<li>Error-messages related to overall Model State </li>
</ul>
</li>
</ul>
<h4></h4>
<p>&#160;</p>
<p>As each screencast is completed, I will update this post with links to each section.</p>
<p>Stay Tuned!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tallan.com/2010/12/01/whats-new-in-asp-net-mvc-3/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
<enclosure url="http://blog.gerety.net/Files/MVC3%20-%20New%20Features%20-%20Part1.mp4" length="86754146" type="video/mp4" />
		</item>
		<item>
		<title>Multi Tenant Architecture via Dependency Injection: Part 3</title>
		<link>http://blog.tallan.com/2010/07/21/multi-tenant-architecture-via-dependency-injection-part-3/</link>
		<comments>http://blog.tallan.com/2010/07/21/multi-tenant-architecture-via-dependency-injection-part-3/#comments</comments>
		<pubDate>Wed, 21 Jul 2010 13:56:01 +0000</pubDate>
		<dc:creator>Nathaniel Engelsen</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Enterprise .NET]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[IoC]]></category>

		<guid isPermaLink="false">http://blog.tallan.com/?p=606</guid>
		<description><![CDATA[Using Ninject and Dependency Injection to enhance your ASP.Net MVC application's Multi-Tenant Application.]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://blog.tallan.com/2010/07/11/multi-tenant-architecture-via-dependency-injection-part-1/">Part 1</a> we discussed web application Multi Tenant Architecture, and briefly discussed how dependency injection can allow us to manage our client customizations.  In <a href="http://blog.tallan.com/2010/07/16/multi-tenant-architecture-via-dependency-injection-part-2/">Part 2</a>, we explored how to wire up Ninject to our ASP.Net MVC application and begin to use its dependency injection features.</p>
<p>In Part 3 we will look at how to utilize Ninject&#8217;s features within our application, along with what kind of functionality can be delivered.  At this point, let&#8217;s revisit our goals from Part #1:</p>
<ol>
<li>dynamically set which service object(s) we are using to perform our application logic</li>
<li>dynamically set which view we are returning</li>
<li>dynamically set which partial views we are using</li>
</ol>
<p>Hypothetically, let our application be a standard transactional system, with header records at the top level and child records below it. Furthermore, let it be an order entry system, so we will need to know about quantities, prices, have subtotals, etc.  Our standard interface can be for Work Orders, and look something like the following:</p>
<p>WorkOrders.aspx:<br />
<img src="http://blog.tallan.com/wp-content/uploads/2010/07/work-orders.png" alt="Sample Work Orders Screenshot" /><br />
We have some header information (Work Order #, etc.) and child records, and the ability to interact with the application to modify child records and add new ones.  At this point, a large customer likes what you&#8217;ve done so far and wants to use your application to manage their shop.  But instead of work orders, they need to use Purchase Orders.  You need to make some major modifications without affecting your existing functionality, so you create a new page and use Ninject to inject the right functionality into the application.  Because we implemented Goal #2 in Part 2, we merely need to modify our source repository to provide the PurchaseOrders.aspx page instead of WorkOrders.aspx.</p>
<p>From CompanyConfigProvider.cs:</p>
<pre class="brush: csharp;">
                // construct our list of Views to be used throughout the application
                // for Goals #2 and #3
                foreach (KeyValuePair&lt;string, string&gt; item in r.getViews())
                {
                    cc.Views.Add(item.Key, item.Value);
                }
</pre>
<p>In addition, because these Purchase Orders are between your client and their own customers and not intra-company Work Orders, there are potential tax implications &#8212; as such, you will need to introduce a method of keeping track of tax when necessary.  It will utilize the existing Purchase Orders functionality, but will need to augment it &#8212; the perfect usage of partial views.</p>
<p>TotalNoTax.ascx:</p>
<pre class="brush: csharp;">
&lt;%@ Control Language=&quot;C#&quot; Inherits=&quot;System.Web.Mvc.ViewUserControl&quot; %&gt;
&lt;p&gt;Non-Profit Tax Code: &lt;input type=&quot;text&quot; name=&quot;taxinfo&quot; /&gt;&lt;/p&gt;
</pre>
<p>TotalWithTax.ascx:</p>
<pre class="brush: csharp;">
&lt;%@ Control Language=&quot;C#&quot; Inherits=&quot;System.Web.Mvc.ViewUserControl&quot; %&gt;
&lt;p&gt;Tax Amount: &lt;input type=&quot;text&quot; id=&quot;taxinfo&quot; name=&quot;taxinfo&quot; /&gt;&lt;/p&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
    function updateTax() {
        var qty = parseFloat($(&quot;#quantity&quot;).val());
        $(&quot;#taxinfo&quot;).val(qty * 150 * .06);
    }

    $(document).ready(function() {
        $(&quot;#quantity&quot;).blur(updateTax);
        $(&quot;#itemType&quot;).change(updateTax);
    });
&lt;/script&gt;
</pre>
<p>Very simply, we will use jQuery to manage a new form element that will include tax when necessary.  Let&#8217;s start putting it all together.  First, let&#8217;s take a look at our controller:</p>
<p>From OrdersController.cs:</p>
<pre class="brush: csharp;">
using {etc}

namespace MultiTenantNinject.Controllers
{
    [HandleError]
    [ProvideCompanyConfig]
    public class OrdersController : Controller
    {
</pre>
<p>As you can see, we inherit from Controller like normal and utilize our ProvideCompanyConfig attribute so that we can be assured we have access to our company config upon rendering.  Let&#8217;s take a look at an Action:</p>
<pre class="brush: csharp;">
        public ActionResult Index()
        {
            ViewResult v = View(_companyConfig.Views[&quot;Order Management&quot;]);

			// add view data items for the header and children;

			// add item to be used for determining if it's a taxable or non-taxable transaction:
			v.ViewData.add(&quot;taxState&quot;,repository.TaxState);

            return v;

        }
</pre>
<p>The first step in rendering the View to the user is ensuring we have an &#8220;Order Management&#8221; entry in our Views collection that establishes what type of major functionality to use.  Our repository would load the config file with a text entry like &#8220;WorkOrders&#8221; or &#8220;PurchaseOrders&#8221; to correspond with &#8220;WorkOrders.aspx&#8221; or &#8220;PurchaseOrders.aspx&#8221;, respectively.  We can set our ViewData at this point, perhaps using a service object (which we will explore soon) and then return the view.  At this point, we have a solid understanding of achieving Goal #2, so let&#8217;s take a look at the few lines necessary to achieve Goal #3:</p>
<p>From PurchaseOrders.aspx:</p>
<pre class="brush: csharp;">
    &lt;% var configSettings = (MultiTenantNinject.Models.ICompanyConfig)ViewData[&quot;companyConfigSettings&quot;];  %&gt;
	&lt;h3&gt;Purchase Orders&lt;/h3&gt;
	... etc ...
    &lt;p&gt;&lt;% Html.RenderPartial(configSettings.Views[string.Format(&quot;Taxes_{0}&quot;,ViewData[&quot;taxState&quot;])]); %&gt;
</pre>
<p>By utilzing the correct entry in our repository for the user&#8217;s state, we can provide the correct tax functionality.  If the company&#8217;s location was in Florida, the repository could provide &#8220;TotalWithTax&#8221; for the &#8220;Taxes_FL&#8221; binding, and &#8220;TotalNoTax&#8221; for the other states.  Obviously we can take it up a level of abstraction and determine whether or not this transaction is taxable in the controller or service object, but this serves as an adequate example of Goal #3.  Lastly, let&#8217;s take a look at our solution for Goal #1 &#8212; it&#8217;s all well and good when we can provide custom front-end functionality for our users, but at some point we will need to implement logic and manipulate data.  Let&#8217;s revisit the module where we inject our services:</p>
<p>From OrderModule.cs:</p>
<pre class="brush: csharp;">
        public override void Load()
        {
            // use reflection to bind a list of types (from our Config's &quot;Bindings&quot; collection)
            // to be used when called upon during injection
            string serviceLocationPrefix = &quot;MultiTenantNinject.Services.&quot;;
            foreach (KeyValuePair&lt;string,string&gt; item in _config.Bindings)
            {
                Bind(Type.GetType(serviceLocationPrefix + item.Key)).To(Type.GetType(serviceLocationPrefix + item.Value));
            }
        }
</pre>
<p>We will need to provide an interface and an implementation for our service(s).  Firstly, the interface:</p>
<pre class="brush: csharp;">
IOrderService.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Web.Mvc;

namespace MultiTenantNinject.Services
{
    public interface IOrderService
    {
        string Process(ViewDataDictionary viewdata);
        DataTable Orders { get; set; }
    }
}
</pre>
<p>and one of the implementations:</p>
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.Mvc;

namespace MultiTenantNinject.Services
{
    public class VideoCardOrderService: IOrderService
    {

        #region IService Members

        public string Process(ViewDataDictionary viewdata)
        {
            // here we do transactions pertaining to video cards
            return &quot;Thanks for buying a video card!&quot;;
        }

        #region Orders
        private DataTable _Orders;
        public DataTable Orders
        {
            get
            {
                return _Orders;
            }
            set
            {
                if (_Orders == value) return;
                _Orders = value;
            }
        }
        #endregion

        #endregion

    }
}
</pre>
<p>Service objects can perform most of the functionality of your application, and do not need to be gone over in great detail, as they are as varied as anything else can be.  Suffice it to say that it&#8217;s a standard interface/implementation pattern of development.  Ninject allows you to set it up for injection, as we did in Part 2, so that whenever you call a particular interface for this user a particular implementation is used.  &#8220;VideoCardOrderService&#8221; could easily be &#8220;MotherboardOrderService&#8221; or &#8220;CarOrderService&#8221;:</p>
<p>From OrdersController.cs:</p>
<pre class="brush: csharp;">
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Save()
        {
            _orderService.Process(ViewData);
            return new RedirectResult(&quot;Index&quot;);
        }
</pre>
<p>Our controller, in the end, is completely agnostic of our major functionality, our minor (partial view) functionality, and our domain logic:</p>
<p>OrdersController.cs:</p>
<pre class="brush: csharp;">
using {etc}
using Ninject;

namespace MultiTenantNinject.Controllers
{
    [HandleError]
    [ProvideCompanyConfig]
    public class OrdersController : Controller
    {
        ICompanyConfig _companyConfig;
        IOrderService _orderService;

        public OrdersController(ICompanyConfig pCompanyConfig, IOrderService pOrderService)
        {
            _companyConfig = pCompanyConfig;
            _orderService = pOrderService;
        }

        public OrdersController()
        {
        }

        public ActionResult Index()
        {
            ViewResult v = View(_companyConfig.Views[&quot;Order Management&quot;]);

			// add view data items for the header and children;

			// add item to be used for determining if it's a taxable or non-taxable transaction:
			v.ViewData.add(&quot;taxState&quot;,repository.TaxState);

            return v;
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Save()
        {
            _orderService.Process(ViewData);
            return new RedirectResult(&quot;Index&quot;);
        }
    }
}
</pre>
<p>Thus, the conclusion to our series about utilizing dependency injection within ASP.Net MVC to enhance a Multi-Tenant Architecture.  We can provide service objects without our controller (or anything else) performing logic switches, we can provide major changes to functionality without creating a new codebase, and we can provide in-place customizations truly in-place.  In addition, we&#8217;ve created our application such that we can utilize any kind of data layer or repository and we can utilize testing frameworks to test our code without having to rewrite anything.  And lastly, although it&#8217;s taken a moderate level of effort to get to this point, we can be secure in the knowledge that additional changes can be implemented without affecting existing functionality, and we can easily swap out functionality when the situation arises with very little additional effort.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tallan.com/2010/07/21/multi-tenant-architecture-via-dependency-injection-part-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Multi Tenant Architecture via Dependency Injection: Part 2</title>
		<link>http://blog.tallan.com/2010/07/16/multi-tenant-architecture-via-dependency-injection-part-2/</link>
		<comments>http://blog.tallan.com/2010/07/16/multi-tenant-architecture-via-dependency-injection-part-2/#comments</comments>
		<pubDate>Fri, 16 Jul 2010 12:37:17 +0000</pubDate>
		<dc:creator>Nathaniel Engelsen</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Enterprise .NET]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[IoC]]></category>

		<guid isPermaLink="false">http://blog.tallan.com/?p=570</guid>
		<description><![CDATA[Using Ninject and Dependency Injection to enhance your ASP.Net MVC application's Multi-Tenant Application.]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://blog.tallan.com/2010/07/11/multi-tenant-architecture-via-dependency-injection-part-1/">Part 1</a> we discussed Multi Tenant Architecture as it pertains to web development, along with how dependency injection (specifically with Ninject) can allow us to manage our necessary customizations a bit cleaner.</p>
<p>To start off with, let&#8217;s talk about using Ninject with ASP.Net MVC.  You&#8217;ll need to download the appropriate Ninject version for your .NET framework.  Our example will use Ninject 2.0 with ASP.Net MVC 1.  Download Ninject from the homepage at <a href="http://ninject.org/">http://ninject.org/</a> and visit the <a href="http://ninject.org/learn">dojo</a> and <a href="http://wiki.github.com/ninject/ninject/">github</a> to learn the basics. Ninject will manage our controllers for us (it needs to, so it can monitor for injection points) and so will need to be tightly integrated into our application.  For starters, we&#8217;re going to need to change our global.asax.cs file.  Take a look:</p>
<p>Global.asax.cs:</p>
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Ninject.Web.Mvc;
using Ninject;
using Ninject.Modules;
using MultiTenantNinject.Controllers.Components;
using MultiTenantNinject.Models;

namespace MultiTenantNinject
{
  // Inherit from NinjectHttpApplication instead of HttpApplication
  public class MvcApplication : NinjectHttpApplication
  {
    public static void RegisterRoutes(RouteCollection routes)
    {
      routes.IgnoreRoute(&quot;{resource}.axd/{*pathInfo}&quot;);

      // hack for visual studio's web server
      routes.IgnoreRoute(&quot;{*favicon}&quot;, new { favicon = @&quot;(.*/)?favicon.ico(/.*)?&quot; });

      routes.MapRoute(
        &quot;Default&quot;, // Route name
        &quot;{controller}/{action}/{id}&quot;, // URL with parameters
        new { controller = &quot;Home&quot;, action = &quot;Index&quot;, id = &quot;&quot; } // Parameter defaults
      );

    }

    // we use OnApplicationStarted, because Ninject is using Application_Started
    protected override void OnApplicationStarted()
    {
      // no big surprise here -- register our routes.
      RegisterRoutes(RouteTable.Routes);
      // register every controller in our application for injection
      RegisterAllControllersIn(Assembly.GetExecutingAssembly());
    }

    // this is called automatically from within the Ninject framework
    protected override IKernel CreateKernel()
    {
      // create a Kernel to manage injections.
      // have the Kernel process our &quot;SetupModule&quot; class
      IKernel k = new StandardKernel(new SetupModule());
      // have the Kernel process our &quot;ConfigModule&quot; class
      k.Load(new ConfigModule());
      // have the Kernel process our &quot;OrderModule class
      // pass an instance of our company config that our ConfigModule calls for
      k.Load(new OrderModule(k.Get&lt;ICompanyConfig&gt;()));
      return k;
    }
  }
}
</pre>
<p>You can see how the CreateKernel() method loads a number of Modules to manage our Dependency Injection.  Let&#8217;s take a look at these modules. The first module to investigate will provide bindings for our .NET MVC dependencies.</p>
<p>SetupModule.cs:</p>
<pre class="brush: csharp;">
using {etc}
using Ninject;
using Ninject.Modules;
using Ninject.Web.Mvc;

namespace MultiTenantNinject.Controllers.Components
{
    // inherit from NinjectModule
    public class SetupModule : NinjectModule
    {
        // NinjectModule is an implementation of the Strategy design pattern and must implement &quot;Load()&quot;
        public override void Load()
        {
            // Let's inject .NET MVC framework dependencies, wow!
            Bind&lt;IFormsAuthentication&gt;()
                .To&lt;FormsAuthenticationService&gt;();
            Bind&lt;IMembershipService&gt;()
                .To&lt;AccountMembershipService&gt;();
            Bind&lt;MembershipProvider&gt;()
                .ToMethod(ctx =&gt; Membership.Provider);
        }
    }
}
</pre>
<p>Our next module will bind the heart of our Multi Tenant Architecture, the &#8220;Company Config&#8221;. This configuration object will be lightweight, cached server-side (ideally once for each company) and will be available during most operations of the page lifecycle.</p>
<p>ICompanyConfig.cs:</p>
<pre class="brush: csharp;">
using {etc}

namespace MultiTenantNinject.Models
{
    public interface ICompanyConfig
    {
        // Task #1 -- provide service objects
        Dictionary&lt;string, string&gt; Bindings { get; set; }
        // Task #2 &amp; #3 -- provide views and partial views
        Dictionary&lt;string, string&gt; Views { get; set; }

        String CompanyName { get; set; }

    }
}
</pre>
<p>ConfigModule.cs:</p>
<pre class="brush: csharp;">
using {etc}

namespace MultiTenantNinject.Controllers.Components
{
    public class ConfigModule : NinjectModule
    {
        public override void Load()
        {
            // Ninject.Activation.Provider is a factory object.
            CompanyConfigProvider Provider = new CompanyConfigProvider(WebConfigurationManager.AppSettings);

            // Bind our service (ICompanyConfig) to its implementation using the
            // aforementioned Provider.  Bind it so that each request uses the same
            // instance of the service.
            Bind&lt;ICompanyConfig&gt;()
                .ToProvider(Provider)
                .InRequestScope();

        }
    }
}
</pre>
<p>Our next module will control the functionality for our example customizations revolving around Purchase Orders.  In practice we could have multiple modules, perhaps one for each functional area of our application, but our single module will serve our purposes here:</p>
<p>OrderModule.cs:</p>
<pre class="brush: csharp;">
using {etc}

namespace MultiTenantNinject.Controllers.Components
{
    public class OrderModule : NinjectModule
    {
        private readonly ICompanyConfig _config;

        // We see our first &quot;Inject&quot; attribute.
        // Here we will take an instance of our company config
        // and later use it to bind our application services
        [Inject]
        public OrderModule(ICompanyConfig companyConfig)
        {
            _config = companyConfig;
        }

        public override void Load()
        {
            // use reflection to bind a list of types (from our Config's &quot;Bindings&quot; collection)
            // to be used when called upon during injection
            string serviceLocationPrefix = &quot;MultiTenantNinject.Services.&quot;;
            foreach (KeyValuePair&lt;string,string&gt; item in _config.Bindings)
            {
                Bind(Type.GetType(serviceLocationPrefix + item.Key)).To(Type.GetType(serviceLocationPrefix + item.Value));
            }
        }
    }
}
</pre>
<p>Let&#8217;s briefly revisit our goals from Part #1:</p>
<ol>
<li>dynamically set which service object(s) we are using to perform our application logic</li>
<li>dynamically set which view we are returning</li>
<li>dynamically set which partial views we are using</li>
</ol>
<p>At this point we can see the pattern unfolding.  We use our Modules to dictate to the Kernel what strategies to use when binding implementations to our services.  We can use reflection, we can use strings and types, and we can use Providers inside of our Modules during binding.  We will be coming back to OrderModule.cs, as that is part of our implementation for Goal #1.  Let us take a look now at our Provider from our ConfigModule:</p>
<p>CompanyConfigProvider.cs:</p>
<pre class="brush: csharp;">
using {etc}
using Ninject.Activation;

namespace MultiTenantNinject.Models
{
    // inherit from Ninject.Activation.Provider
    public class CompanyConfigProvider: Provider&lt;CompanyConfig&gt;
    {
        // these settings are provided by our web.config in this example
        public CompanyConfigProvider(NameValueCollection settings)
        {
            Settings = settings;
        }

        protected NameValueCollection Settings { get; set; }

        // build and return an instance of our CompanyConfig using the specific context
        // IProvider is a Factory that will have its CreateInstance() method called
        // the first time that a CompanyConfig is injected
        protected override CompanyConfig CreateInstance(IContext context)
        {
            // use a caching mechanism to store our company config.  we cannot
            // cache in the Application cache because we have a Multi Tenant Application.
            // we can use Session in a pinch, although depending on your application's traffic,
            // you might need to use something else
            System.Web.SessionState.HttpSessionState Session = HttpContext.Current.Session;
            CompanyConfig cc = null;

            // if we don't have a cached company config:
            if (Session == null || Session[&quot;cc&quot;] == null)
            {
                cc = new CompanyConfig();
                // our repository is extremely unsophisticated, but you should
                // get the idea of how this works.  it may very well be passed in
                // via constructor injection
                MultiTenantNinject.Models.Repository r = new Repository();

                // construct our list of Views to be used throughout the application
                // for Goals #2 and #3
                foreach (KeyValuePair&lt;string, string&gt; item in r.getViews())
                {
                    cc.Views.Add(item.Key, item.Value);
                }
                // construct our list of service bindings to be used throughout the application
                // for Goal #1 (previously seen in OrderModule.cs
                foreach (KeyValuePair&lt;string, string&gt; item in r.getBindings())
                {
                    cc.Bindings.Add(item.Key, item.Value);
                }
                // if we can cache our company config:
                if (Session != null &amp;&amp; Session[&quot;cc&quot;] == null)
                {
                    Session[&quot;cc&quot;] = cc;
                }
                // set company name (normally would be from the repository)
                cc.CompanyName = &quot;Widgets, Inc.&quot;;
            }
            else  // we have a previously cached company config
            {
                cc = (CompanyConfig)Session[&quot;cc&quot;];
            }

            return cc;
        }
    }
}
</pre>
<p>To make our lives a little easier and yet more structured, let&#8217;s create an ActionFilterAttribute to inject our CompanyConfig into our Views:</p>
<p>From ProvideCompanyConfigAttribute:</p>
<pre class="brush: csharp;">
    public class ProvideCompanyConfigAttribute : ActionFilterAttribute
    {
        [Inject]
        public ICompanyConfig Settings { get; set; }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            filterContext.Controller.ViewData.Add(&quot;companyConfigSettings&quot;, Settings);
        }
    }
</pre>
<p>We use Ninject&#8217;s &#8220;Inject&#8221; attribute to provide the CompanyConfig to our Attribute, and then inject the config into the controller as a matter of course.</p>
<p>At this point we&#8217;ve seen how Ninject positions itself within our application (a controller factory and application superclass) and how we can use Ninject&#8217;s modularity to manage our bindings.  We&#8217;ve touched upon Goals #1, 2, and 3, and can see it taking shape before us.  We have a company configuration that encapsulates the customizations for the currently logged in user and provides the customized bindings and views for that logged in user.  We have basically everything we need to begin working with our customized functionality.</p>
<p>To get this far we have made the following assumptions:</p>
<ol>
<li>Your repository works.</li>
<li>You have an ASP.Net MVC application in otherwise working order.</li>
<li>You have downloaded and referenced the Ninject libraries.</li>
</ol>
<p>In Part 3 we will look at our application controllers and views, and then explore what we can do to provide customized functionality to our users.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tallan.com/2010/07/16/multi-tenant-architecture-via-dependency-injection-part-2/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Multi Tenant Architecture via Dependency Injection: Part 1</title>
		<link>http://blog.tallan.com/2010/07/11/multi-tenant-architecture-via-dependency-injection-part-1/</link>
		<comments>http://blog.tallan.com/2010/07/11/multi-tenant-architecture-via-dependency-injection-part-1/#comments</comments>
		<pubDate>Sun, 11 Jul 2010 20:51:34 +0000</pubDate>
		<dc:creator>Nathaniel Engelsen</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Enterprise .NET]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[IoC]]></category>

		<guid isPermaLink="false">http://blog.tallan.com/?p=421</guid>
		<description><![CDATA[Discover how to use Inversion of Control and Dependency Injection to enhance your web application's Multi-Tenant Application.]]></description>
			<content:encoded><![CDATA[<p>Chances are, if you&#8217;ve been developing web applications for a number of years, you&#8217;ve noticed a few ways of provisioning your application for your users.</p>
<ol>
<li>Your users all log into a single codebase.  It might be load balanced, cached, the whole nine yards, but everybody is on the same build and accesses the same data.</li>
<li>Your users log into multiple codebases and/or multiple databases.  Perhaps you have some high-powered customers who want custom functionality, and so you forked your codebase and created them their own functionality.   Most likely, you can update your customer&#8217;s builds independently of one another.</li>
<li>Your users all log into a single codebase, but you use flags, connection strings, config files, etc., to logically separate out your users from one another.  Your high-powered customers see their custom functionality, but it&#8217;s part of the main codebase and you are able to update your application in one fell swoop.</li>
</ol>
<p>We&#8217;re going to talk more about option #3 &#8212; the Multi-Tenant Architecture.  There is <a href="http://lmgtfy.com/?q=multi+tenant+architecture">PLENTY of reading material</a> out there for you to learn more about multi-tenancy.  Suffice it to say that it allows you to satisfy multiple sets of requirements for your multiple customers via one codebase, and your customers, most likely, are logically separate in the database(i.e. they use one schema and one top-level data store) instead of physically separate.</p>
<p>In the past, (and present, for novice developers), it was a usual practice to utililze config files, database flags, etc., to turn on and off functionality. Your code may have looked something like:</p>
<pre class="brush: csharp;">
&lt;% if (showThisFunctionality) %&gt;
&lt;-- this widget is shown --&gt;;
&lt;% else %&gt;;
&lt;-- this other widget is shown --&gt;
&lt;% end if %&gt;
</pre>
<p><strong>Fig 1: Classic ASP</strong></code></p>
<p>By utilizing a dependency injection framework you can provide features to your users, based on configuration and setup, without having to use logic switches inside of your application.  This is above and beyond the existing benefits of using a dependency injection framework, which is not the scope of this essay but can be enumerated <a href="http://misko.hevery.com/2009/01/14/when-to-use-dependency-injection/">here</a>, for instance.  Our example will use <a href="http://ninject.org/">Ninject</a> and ASP.NET MVC, although you could use any DI and application frameworks.</p>
<p>Our challenge for this example will be to:</p>
<ol>
<li>dynamically set which service object(s) we are using to perform our application logic</li>
<li>dynamically set which view we are returning</li>
<li>dynamically set which partial views we are using</li>
</ol>
<p>Our example will utilize dependency injection to provide order fulfillment functionality for our customers.  For goal #1, we will use Ninject's MVC integration to provide service objects for our controllers.  Once Ninject is wired up, we can have our service objects perform our application logic against our Model, and as a matter of fact, Behavioral design patterns are a good fit here.  Goal #2 is achievable fairly easily with ASP.Net MVC.  Setting which view you're returning via any MVC framework is often a very simple operation and comes down to returning a string variable which represents the view in question.  For ASP.NET MVC we can '<code><span style="color: #0000ff">return</span><span>View(</span><span style="color: #a31515">"viewName"</span><span>)'</span></code> where "viewName" is the name of the view we wish to return.  There is also the obvious <code>"<span style="color: #0000ff">return </span><span>View(viewNameVariable)</span>"</code> override.  Our example will use a configuration object to set which view is being called.  Accomplishing goal #3 can be thought of as an extension of #2, but "finer grained". Where you have general and reusable functionality within your view, your partial views allow you to have specific customizations exposed to your user in a consistent fashion.</p>
<p>In Part 2 we will investigate both integrating Ninject with ASP.Net MVC as well as what shape our framework will take.  In Part 3 we will finish up our framework architecture and explore how to use it to provide features to our users.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tallan.com/2010/07/11/multi-tenant-architecture-via-dependency-injection-part-1/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>S#arp Architecture</title>
		<link>http://blog.tallan.com/2010/06/20/sarp-architecture/</link>
		<comments>http://blog.tallan.com/2010/06/20/sarp-architecture/#comments</comments>
		<pubDate>Sun, 20 Jun 2010 05:32:13 +0000</pubDate>
		<dc:creator>Lee Rodgers</dc:creator>
				<category><![CDATA[Enterprise .NET]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[nHibernate]]></category>

		<guid isPermaLink="false">http://blog.tallan.com/2010/06/20/sarp-architecture/</guid>
		<description><![CDATA[I have been doing some work and research with ASP.NET MVC 2.0.  My first interest was to try to figure out how to get Dependency Injection working with ASP.NET.  I started doing investigating how to link in Springframework.net.  This direction led me down a track that required some manual configuration.  This is when i found [...]]]></description>
			<content:encoded><![CDATA[<p>I have been doing some work and research with <a href="http://www.asp.net/mvc" target="_blank">ASP.NET MVC 2.0</a>.  My first interest was to try to figure out how to get <a href="http://en.wikipedia.org/wiki/Dependency_injection" target="_blank">Dependency Injection</a> working with ASP.NET.  I started doing investigating how to link in <a href="http://springframework.net" target="_blank">Springframework.net</a>.  This direction led me down a track that required some manual configuration.  This is when i found <a href="http://sharparchitecture.net/" target="_blank">S#arp Architecture</a>, which I found very interesting since it gave you the benefits without the configuration up front.</p>
<p><a href="http://sharparchitecture.net/" target="_blank">S#arp Architecture</a> is a project template for Visual Studio that will set you up with a ASP.NET MVC application that is already wired up for Dependency Injection and using <a href="http://community.jboss.org/wiki/NHibernateforNET" target="_blank">nHibernate</a> for data access.  more information can be found on the S#arp Architecture website and wiki.</p>
<p>My findings so far have been very positive.  Within about 45 minutes I had a web application with some basic CRUD functionality.  This functionality included unit testing at every layer.  It seems like a great way to start a project and easily promote best practices like dependency injection and test driven development.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tallan.com/2010/06/20/sarp-architecture/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

