<?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>Dot Scrap Book</title>
	<atom:link href="http://dotscrapbook.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://dotscrapbook.wordpress.com</link>
	<description>A record of our daily brawl in the cyber saloon</description>
	<lastBuildDate>Sun, 22 Jan 2012 12:55:19 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='dotscrapbook.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Dot Scrap Book</title>
		<link>http://dotscrapbook.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://dotscrapbook.wordpress.com/osd.xml" title="Dot Scrap Book" />
	<atom:link rel='hub' href='http://dotscrapbook.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Using web.config application settings in nUnit</title>
		<link>http://dotscrapbook.wordpress.com/2012/01/20/using-web-config-application-settings-in-nunit/</link>
		<comments>http://dotscrapbook.wordpress.com/2012/01/20/using-web-config-application-settings-in-nunit/#comments</comments>
		<pubDate>Fri, 20 Jan 2012 10:27:04 +0000</pubDate>
		<dc:creator>Andrew Jerrison</dc:creator>
				<category><![CDATA[Configuration]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Sharp Architecture]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[application settings testing]]></category>
		<category><![CDATA[nUnit]]></category>
		<category><![CDATA[sharp architecture]]></category>
		<category><![CDATA[web.config]]></category>

		<guid isPermaLink="false">http://dotscrapbook.wordpress.com/?p=194</guid>
		<description><![CDATA[If the piece of code that you are testing refers to an appsetting value in the web.config file then nUnit will fall over &#8211; basically because nUnit itself does not use the web.config file. This is a fairly common thing to come up against, and the easy solution is on the web, but it doesn&#8217;t [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotscrapbook.wordpress.com&amp;blog=18475170&amp;post=194&amp;subd=dotscrapbook&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>If the piece of code that you are testing refers to an appsetting value in the web.config file then nUnit will fall over &#8211; basically because nUnit itself does not use the web.config file.</p>
<p>This is a fairly common thing to come up against, and the easy solution is on the web, but it doesn&#8217;t appear to be in the nUnit help so I thought I&#8217;d put it here too, and make it specific to the dependency injection/Sharp Architecture web projects that my team use.</p>
<p>There are two things that you can do. The quick thing to do is to find your tests dll file. In a Sharp Architecture 1.6 project this will be in something like <strong>[project root]/tests/[namespace].Tests/bin/Debug</strong>.  The dll file will be called (unsurprisingly) <strong>[namespace].Tests.dll</strong>. </p>
<p>You will see that nUnit has also created a <strong>[namespace].Tests.dll.config</strong> file. This is where you should put your application settings. When you open it up you can see that it looks similar to the web.config file &#8211; there is already an appsettings section. Simply copy your web.config settings to here.</p>
<p>That is all very well, but what if you want to mock different values of this app setting when you are testing? If you are using a dependency injection development pattern you might also want to consider having a separate class and interface that just handles the retrieval of application settings, e.g.</p>
<p><pre class="brush: csharp;">
public class AppSettingsService: IAppSettingsService
{
        public string ManagerRole
        {
            get { 
              if (ConfigurationManager.ConnectionStrings[&quot;ManagerRole&quot;] == null)
                 return &quot;&quot;;
              else
                 return ConfigurationManager.ConnectionStrings[&quot;ManagerRole&quot;].ToString();  
            } 
        }
}
</pre> </p>
<p>You can then inject this service class into the class that you are testing, use the methods on this service class to retrieve your appsettings, and mock them to your heart&#8217;s content.</p>
<p>Note: I am assuming you know what dependency injection, mocking, interfaces etc are. If not I suggest searching the net &#8211; they are a very good way of developing!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotscrapbook.wordpress.com/194/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotscrapbook.wordpress.com/194/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotscrapbook.wordpress.com/194/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotscrapbook.wordpress.com/194/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotscrapbook.wordpress.com/194/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotscrapbook.wordpress.com/194/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotscrapbook.wordpress.com/194/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotscrapbook.wordpress.com/194/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotscrapbook.wordpress.com/194/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotscrapbook.wordpress.com/194/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotscrapbook.wordpress.com/194/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotscrapbook.wordpress.com/194/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotscrapbook.wordpress.com/194/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotscrapbook.wordpress.com/194/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotscrapbook.wordpress.com&amp;blog=18475170&amp;post=194&amp;subd=dotscrapbook&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://dotscrapbook.wordpress.com/2012/01/20/using-web-config-application-settings-in-nunit/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cec23b7b22395d8cdc18267dedad0b0f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ajerrison</media:title>
		</media:content>
	</item>
		<item>
		<title>Using both OpenID and CAS authentication within the same MVC site</title>
		<link>http://dotscrapbook.wordpress.com/2011/11/15/using-both-openid-and-cas-authentication-within-the-same-mvc-site/</link>
		<comments>http://dotscrapbook.wordpress.com/2011/11/15/using-both-openid-and-cas-authentication-within-the-same-mvc-site/#comments</comments>
		<pubDate>Tue, 15 Nov 2011 11:27:35 +0000</pubDate>
		<dc:creator>Andrew Jerrison</dc:creator>
				<category><![CDATA[MVC]]></category>
		<category><![CDATA[Sharp Architecture]]></category>
		<category><![CDATA[CAS]]></category>
		<category><![CDATA[multiple authentication]]></category>
		<category><![CDATA[OpenID]]></category>
		<category><![CDATA[sharp architecture]]></category>

		<guid isPermaLink="false">http://dotscrapbook.wordpress.com/?p=184</guid>
		<description><![CDATA[My employer uses CAS as the authentication tool for internal users, but does not allow accounts for external users. However sometimes we need to let external users on! So instead I added an additional authentication mechanism to login with an OpenID too. This article just shows the quick and (some might say) unrefined way of [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotscrapbook.wordpress.com&amp;blog=18475170&amp;post=184&amp;subd=dotscrapbook&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>My employer uses CAS as the authentication tool for internal users, but does not allow accounts for external users. However sometimes we need to let external users on! So instead I added an additional authentication mechanism to login with an OpenID too. This article just shows the quick and (some might say) unrefined way of getting it working in ASP.NET MVC2 with SharpArchitecture 1.6. Some of this is based on <a href="http://weblogs.asp.net/haithamkhedre/archive/2011/03/13/openid-authentication-with-asp-net-mvc3-dotnetopenauth-and-openid-selector.aspx" target="_blank">this great article</a> about getting OpenID to work with MVC3.</p>
<p>To start with download the <a href="http://www.dotnetopenauth.net/" target="_blank">DotNetOpenAuth</a> .Net library, put it in your solution&#8217;s main lib directory, and then add a reference to it in your Controllers project. </p>
<p>Then download the <a href="http://code.google.com/p/openid-selector/" target="_blank">OpenId-Selector</a> javascript library and add the script, css and images to your Web project.</p>
<p>Next copy the <a href="https://wiki.jasig.org/display/CASC/CASP+Adds+CAS+Logic+to+an+ASP.NET+App" target="_blank">CASP class from JaSig&#8217;s site</a> and put it in your ApplicationServices project with a class name of &#8216;CASService&#8217;. This class was written for Webforms rather than MVC, and as it stands is not really unit testable, but it gives a good start, I&#8217;ll leave it up to you if you want to refactor it, but I didn&#8217;t bother for this proof-of-concept. The only changes you need to make are to first remove the currentPage property and replace any references to it with HttpContext.Current. Replace the currentPage parameter in the constructor and Authenticate methods with &#8216;string ReturnURL&#8217; instead. The main constructor should now look like this:</p>
<p><pre class="brush: csharp;">
    public CASP(string baseCasUrl, string ReturnURL, bool alwaysRenew)
        {
            //if (currentPage == null)
            //    throw new ArgumentNullException(&quot;currentPage cannot be null&quot;);
            if (baseCasUrl == null)
                throw new ArgumentNullException(&quot;baseCasUrl cannot be null&quot;);

            this.baseCasUrl = baseCasUrl;
            //this.currentPage = currentPage;
            this.AlwaysRenew = alwaysRenew;
            ServiceUrl = HttpUtility.UrlEncode(HttpContext.Current.Request.Url.AbsoluteUri.Split('?')[0]+ &quot;?ReturnUrl=&quot; + ReturnURL);
        }
</pre>   </p>
<p>The authentication mode in web.config should be set to Forms, e.g.<br />
<pre class="brush: xml;">
&lt;authentication mode=&quot;Forms&quot;&gt;
        &lt;forms loginUrl=&quot;~/Security/LogOn&quot;  name=&quot;AuthCookie&quot; timeout=&quot;60&quot;/&gt;
&lt;/authentication&gt;
</pre>  </p>
<p>The first login page is basically just a method of selecting which authentication provider you want to use (note I&#8217;ve not styled this at all, just in case you were wondering <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> ). I&#8217;m assuming here that you have developed your own master page and simple controller method to display this.</p>
<p>The master page should include these lines:<br />
<pre class="brush: xml;">
link href=&quot;&lt;%= Url.Content(&quot;~/Content/openid-shadow.css&quot;) %&gt;&quot;
     rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
    &lt;link href=&quot;&lt;%= Url.Content(&quot;~/Content/openid.css&quot;)%&gt;&quot; 
     rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
    &lt;script src=&quot;&lt;%= Url.Content(&quot;~/Scripts/openid-en.js&quot;)%&gt;&quot; 
     type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;&lt;%=Url.Content(&quot;~/Scripts/openid-jquery.js&quot;)%&gt;&quot; 
     type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
        $(document).ready(function () {
            openid.init('openid_identifier');
        });
    &lt;/script&gt;
</pre></p>
<p>And this is the login page:</p>
<p><pre class="brush: xml;">
&lt;%@ Page Title=&quot;&quot; Language=&quot;C#&quot; MasterPageFile=&quot;~/Views/Shared/OpenId.Master&quot; Inherits=&quot;System.Web.Mvc.ViewPage&lt;IdeaFactory.ApplicationServices.ViewModels.LogOnViewModel&gt;&quot; %&gt;

&lt;asp:Content ID=&quot;Content1&quot; ContentPlaceHolderID=&quot;MainContent&quot; runat=&quot;server&quot;&gt;
  &lt;form action=
&quot;CASAuthenticate?ReturnUrl=&lt;%= HttpUtility.UrlEncode(Request.QueryString[&quot;ReturnUrl&quot;]) %&gt;&quot;
 method=&quot;post&quot; id=&quot;cas_form&quot;&gt;

&lt;div&gt;
    
        &lt;legend&gt;Login using  CAS&lt;/legend&gt;
        
        &lt;div id=&quot;Div2&quot;&gt;
            &lt;img src='&lt;%= Url.Content(&quot;~/Content/Images/cas.gif&quot;)%&gt;' /&gt;
            &lt;input type=&quot;submit&quot; value=&quot;Log On&quot; /&gt;
        &lt;/div&gt;
       
        &lt;div&gt;
           
        &lt;/div&gt;
   
&lt;/div&gt;
&lt;/form&gt;

&lt;br /&gt;&lt;br /&gt;

    &lt;form action=
&quot;Authenticate?ReturnUrl=&lt;%= HttpUtility.UrlEncode(Request.QueryString[&quot;ReturnUrl&quot;]) %&gt;&quot;
 method=&quot;post&quot; id=&quot;openid_form&quot;&gt;
&lt;input type=&quot;hidden&quot; name=&quot;action&quot; value=&quot;verify&quot; /&gt;
&lt;div&gt;
    
        &lt;legend&gt;Or login using OpenID&lt;/legend&gt;
        &lt;div class=&quot;openid_choice&quot;&gt;
            &lt;p&gt;
                Please click your account provider:&lt;/p&gt;
            &lt;div id=&quot;openid_btns&quot;&gt;
            &lt;/div&gt;
        &lt;/div&gt;
        &lt;div id=&quot;openid_input_area&quot;&gt;
            &lt;%= Html.TextBox(&quot;openid_identifier&quot;) %&gt;
            &lt;input type=&quot;submit&quot; value=&quot;Log On&quot; /&gt;
        &lt;/div&gt;
        &lt;noscript&gt;
            &lt;p&gt;
                OpenID is service that allows you to log-on to many different websites 
                using a single indentity. Find out &lt;a href=&quot;http://openid.net/what/&quot;&gt;
                 more about OpenID&lt;/a&gt;and &lt;a href=&quot;http://openid.net/get/&quot;&gt;
                 how to get an OpenID enabled account&lt;/a&gt;.&lt;/p&gt;
        &lt;/noscript&gt;
        &lt;div&gt;
           
        &lt;/div&gt;
   
&lt;/div&gt;
&lt;/form&gt;
&lt;br /&gt;

&lt;/asp:Content&gt;
</pre></p>
<p>The LogInViewModel is simple, just enough to hold the OpenID returned by the javascript library:</p>
<p><pre class="brush: csharp;">
 public class LogOnViewModel
    {
        public string openid_identifier { get; set; }
    }
</pre></p>
<p>Below are the raltively simple controller methods for authentication. Note that these have to be available as both HttpPost and HttpGet. </p>
<p><pre class="brush: csharp;">
// Include these namespaces in your controller
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;

       public ActionResult CASAuthenticate(LogOnViewModel model, string ReturnUrl)
        {
            
           

            // Simple call to authenticate CAS.
            string username = CASP.Authenticate(&quot;https://login.casserver.com/cas/&quot;, ReturnUrl, false, false);
           
            try
            {
                if (username != null)
                {
                    _formsService.SignIn(username, false);



                    return Redirect(ReturnUrl);
                }
            }
            catch (Exception ex)
            {
              
            }

            return View(&quot;LogOn&quot;);
        }

        // Largely copied from http://weblogs.asp.net/haithamkhedre/archive/2011/03/13/openid-authentication-with-asp-net-mvc3-dotnetopenauth-and-openid-selector.aspx
        public ActionResult Authenticate(LogOnViewModel model, string returnUrl)
        {
            var response = openid.GetResponse();
            if (response == null)
            {
                //Let us submit the request to OpenID provider
                Identifier id;
                if (Identifier.TryParse(model.openid_identifier, out id))
                {
                    try
                    {
                        var request = openid.CreateRequest(
                                             model.openid_identifier);
                        return request.RedirectingResponse.AsActionResult();
                    }
                    catch (ProtocolException ex)
                    {
                     
                        return View(&quot;LogOn&quot;);
                    }
                }

              
                return View(&quot;LogOn&quot;);
            }

            //Let us check the response
            switch (response.Status)
            {

                case AuthenticationStatus.Authenticated:
                    LogOnViewModel lm = new LogOnViewModel();
                    lm.openid_identifier = response.ClaimedIdentifier;
                   
                    _formsService.SignIn(lm.openid_identifier, false);


                    return Redirect(returnUrl);

                case AuthenticationStatus.Canceled:
                    
                    return View(&quot;LogOn&quot;);
                case AuthenticationStatus.Failed:
                  
                    return View(&quot;LogOn&quot;);
            }

            return new EmptyResult();
        }
</pre></p>
<p>The _formsService class is what actually creates the login cookie:<br />
<pre class="brush: csharp;">
public class FormsAuthenticationService:IFormsAuthenticationService
    {
        public void SignIn(string userName, bool createPersistentCookie)
        {
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException(&quot;Value cannot be null or empty.&quot;, &quot;userName&quot;);
            
            FormsAuthenticationTicket tkt;
            string cookiestr;
            HttpCookie ck;
            tkt = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(30), false, &quot;&quot;);
            cookiestr = FormsAuthentication.Encrypt(tkt);
            ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
            ck.HttpOnly = true;
            ck.Path = FormsAuthentication.FormsCookiePath;
            HttpContext.Current.Response.Cookies.Add(ck);
            
        }


        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }
    }
</pre></p>
<p>And then if you want to set the Identity with the app then you can just go to Global.asax and add/edit the OnAuthenticationRequest method:</p>
<p><pre class="brush: csharp;">
      protected void Application_OnAuthenticateRequest(object sernder, EventArgs e)
        {
          
                    // Extract the forms authentication cookie
                    string cookieName = FormsAuthentication.FormsCookieName;
                    HttpCookie authCookie = Context.Request.Cookies[cookieName];

                    if(null == authCookie)
                    {
                      // There is no authentication cookie.
                      return;
                    } 


                    FormsAuthenticationTicket authTicket = null;
                    try
                    {
                      authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                    }
                    catch(Exception ex)
                    {
                      // Log exception details (omitted for simplicity)
                      return;
                    }

                    if (null == authTicket)
                    {
                      // Cookie failed to decrypt.
                      return; 
                    } 


                    // When the ticket was created, the UserData property was assigned a
                    // pipe delimited string of role names.
                    string[] roles = authTicket.UserData.Split(new char[]{'|'});


                    // Create an Identity object
                    FormsIdentity id = new FormsIdentity( authTicket ); 

                    // This principal will flow throughout the request.
                    GenericPrincipal principal = new GenericPrincipal(id, roles);
                    // Attach the new principal object to the current HttpContext object
                    Context.User = principal;


              
        }
</pre></p>
<p>Remember that when a user logs out of your site, they are not necessarily logged out of your identification provider, so you may want to provide a message that informs them of this.</p>
<p>So nothing particularly original, but as I couldn&#8217;t find anything specifically on this topic, and some of the information comes from some pretty hard-to-find places, I thought I&#8217;d post here to save others the time in searching.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotscrapbook.wordpress.com/184/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotscrapbook.wordpress.com/184/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotscrapbook.wordpress.com/184/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotscrapbook.wordpress.com/184/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotscrapbook.wordpress.com/184/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotscrapbook.wordpress.com/184/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotscrapbook.wordpress.com/184/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotscrapbook.wordpress.com/184/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotscrapbook.wordpress.com/184/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotscrapbook.wordpress.com/184/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotscrapbook.wordpress.com/184/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotscrapbook.wordpress.com/184/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotscrapbook.wordpress.com/184/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotscrapbook.wordpress.com/184/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotscrapbook.wordpress.com&amp;blog=18475170&amp;post=184&amp;subd=dotscrapbook&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://dotscrapbook.wordpress.com/2011/11/15/using-both-openid-and-cas-authentication-within-the-same-mvc-site/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cec23b7b22395d8cdc18267dedad0b0f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ajerrison</media:title>
		</media:content>
	</item>
		<item>
		<title>Automatic saving when updating records with SharpArchitecture</title>
		<link>http://dotscrapbook.wordpress.com/2011/10/11/automatic-saving-when-updating-records-with-sharparchitecture/</link>
		<comments>http://dotscrapbook.wordpress.com/2011/10/11/automatic-saving-when-updating-records-with-sharparchitecture/#comments</comments>
		<pubDate>Tue, 11 Oct 2011 16:14:19 +0000</pubDate>
		<dc:creator>Andrew Jerrison</dc:creator>
				<category><![CDATA[MVC]]></category>
		<category><![CDATA[nHibernate]]></category>
		<category><![CDATA[Sharp Architecture]]></category>
		<category><![CDATA[nHibernate transactions using Sharp Architecture]]></category>
		<category><![CDATA[sharp architecture]]></category>

		<guid isPermaLink="false">http://dotscrapbook.wordpress.com/?p=179</guid>
		<description><![CDATA[Another gotcha for newbie MVC/Sharp programmers (I include myself this time!). As mentioned in a previous post, with SharpArchitecture you need to decorate the method with the [Transaction] attribute in order to save the record you are creating. So far so good. What we hadn&#8217;t realised is that you don&#8217;t actually need to call the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotscrapbook.wordpress.com&amp;blog=18475170&amp;post=179&amp;subd=dotscrapbook&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Another gotcha for newbie MVC/Sharp programmers (I include myself this time!). As mentioned in a previous post, with SharpArchitecture you need to decorate the method with the [Transaction] attribute in order to save the record you are creating. So far so good. What we hadn&#8217;t realised is that you don&#8217;t actually need to call the Repository&#8217;s SaveOrUpdate() method in order to update an existing record!</p>
<p>If you have a method such as the following in your controller (I am assuming you have created the relevant entity and repository), then this is actually enough to update your &#8216;RecordType&#8217; database record! Presumably this happens because the transaction is committed once the method is returned. You still need to called SaveOrUpdate() to create new records. </p>
<p>I personally don&#8217;t like this feature (I don&#8217;t know if it is Sharp or nHibernate) because it is too easy to accidentally update something that shouldn&#8217;t be, but once you know it exists then you can look out for it.<br />
<pre class="brush: csharp;">
[AcceptVerbs(HttpVerbs.Post)]
[Transaction]
public ActionResult Update(MyViewModel model)
{
     RecordType record = _myRepository.GetById(model.Id);
     if (record != null)
     {
           record.Description = model.Description;
      }
}
</pre> </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotscrapbook.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotscrapbook.wordpress.com/179/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotscrapbook.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotscrapbook.wordpress.com/179/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotscrapbook.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotscrapbook.wordpress.com/179/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotscrapbook.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotscrapbook.wordpress.com/179/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotscrapbook.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotscrapbook.wordpress.com/179/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotscrapbook.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotscrapbook.wordpress.com/179/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotscrapbook.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotscrapbook.wordpress.com/179/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotscrapbook.wordpress.com&amp;blog=18475170&amp;post=179&amp;subd=dotscrapbook&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://dotscrapbook.wordpress.com/2011/10/11/automatic-saving-when-updating-records-with-sharparchitecture/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cec23b7b22395d8cdc18267dedad0b0f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ajerrison</media:title>
		</media:content>
	</item>
		<item>
		<title>MVC: storing URL parameter value in ViewModel</title>
		<link>http://dotscrapbook.wordpress.com/2011/10/11/mvc-storing-url-parameter-value-in-viewmodel/</link>
		<comments>http://dotscrapbook.wordpress.com/2011/10/11/mvc-storing-url-parameter-value-in-viewmodel/#comments</comments>
		<pubDate>Tue, 11 Oct 2011 15:53:47 +0000</pubDate>
		<dc:creator>Andrew Jerrison</dc:creator>
				<category><![CDATA[MVC]]></category>
		<category><![CDATA[route parameter]]></category>
		<category><![CDATA[URL parameter]]></category>
		<category><![CDATA[ViewModel]]></category>

		<guid isPermaLink="false">http://dotscrapbook.wordpress.com/?p=174</guid>
		<description><![CDATA[Bit of a gotcha for newbie MVC programmers. If a name of a route parameter on your page is the same as a name of a property on your ViewModel then the value of the route parameter will be copied to your ViewModel property. This can actually be very useful, but causes an awful lot [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotscrapbook.wordpress.com&amp;blog=18475170&amp;post=174&amp;subd=dotscrapbook&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Bit of a gotcha for newbie MVC programmers. If a name of a route parameter on your page is the same as a name of a property on your ViewModel then the value of the route parameter will be copied to your ViewModel property. This can actually be very useful, but causes an awful lot of head-scratching to start with if you were unaware of it!</p>
<p>For example, take the following route in your registry:<br />
<pre class="brush: csharp;">
routes.MapRoute(
                &quot;MyRoute&quot;,
                &quot;ShowMe/{qid}&quot;,
                new { controller = &quot;Show&quot;, action = &quot;Me&quot; }
                );
</pre>   </p>
<p>and then the View returned by the &#8216;Me&#8217; controller method uses the following ViewModel:<br />
<pre class="brush: csharp;">
public class ShowMeViewModel
{
      public string qid {get;set;}
}
</pre>  </p>
<p>Then when the page is called with the URL of <strong>ShowMe/TheWorld</strong> the &#8216;qid&#8217; property of the ViewModel will become automatically set to &#8216;TheWorld&#8217;, regardless of what you try to set it to within the &#8216;Me&#8217; controller method. </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotscrapbook.wordpress.com/174/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotscrapbook.wordpress.com/174/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotscrapbook.wordpress.com/174/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotscrapbook.wordpress.com/174/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotscrapbook.wordpress.com/174/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotscrapbook.wordpress.com/174/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotscrapbook.wordpress.com/174/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotscrapbook.wordpress.com/174/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotscrapbook.wordpress.com/174/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotscrapbook.wordpress.com/174/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotscrapbook.wordpress.com/174/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotscrapbook.wordpress.com/174/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotscrapbook.wordpress.com/174/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotscrapbook.wordpress.com/174/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotscrapbook.wordpress.com&amp;blog=18475170&amp;post=174&amp;subd=dotscrapbook&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://dotscrapbook.wordpress.com/2011/10/11/mvc-storing-url-parameter-value-in-viewmodel/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cec23b7b22395d8cdc18267dedad0b0f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ajerrison</media:title>
		</media:content>
	</item>
		<item>
		<title>Sharp Architecture 1.6 Template Installation in Visual Studio 2008</title>
		<link>http://dotscrapbook.wordpress.com/2011/09/13/sharp-architecture-1-6-template-installation-in-visual-studio-2008/</link>
		<comments>http://dotscrapbook.wordpress.com/2011/09/13/sharp-architecture-1-6-template-installation-in-visual-studio-2008/#comments</comments>
		<pubDate>Tue, 13 Sep 2011 15:15:54 +0000</pubDate>
		<dc:creator>Andrew Jerrison</dc:creator>
				<category><![CDATA[MVC]]></category>
		<category><![CDATA[Sharp Architecture]]></category>
		<category><![CDATA[install template]]></category>
		<category><![CDATA[sharp architecture]]></category>
		<category><![CDATA[visual studio 2008]]></category>

		<guid isPermaLink="false">http://dotscrapbook.wordpress.com/?p=164</guid>
		<description><![CDATA[An innovative new approach to customer service from the team who create Sharp Architecture has seen them remove the documentation for installing on Visual Studio 2008. In fact they seem to have removed any useful documentation – even from the page history. The usual wiki just seems to consist of a few obscure FAQs now. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotscrapbook.wordpress.com&amp;blog=18475170&amp;post=164&amp;subd=dotscrapbook&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>An innovative new approach to customer service from the team who create Sharp Architecture has seen them remove the documentation for installing on Visual Studio 2008. In fact they seem to have removed <strong>any</strong> useful documentation – even from the page history. The usual wiki just seems to consist of a few obscure FAQs now. This is apparently so they can focus on development for Visual Studio 2010 and not do boring stuff like telling us how to use their software; which is fine for <em>them</em>, but the rest of us without deep pockets and time to upgrade (also not documented) are left in difficulty when a new member of staff comes along. </p>
<p>So after a frustrating couple of days I have finally figured out how to do it and the steps are below. Skip steps 2-5 if you have MVC 2 already installed. If I have learnt anything from this it is to make notes of everything when using Open Source software.</p>
<ol>
<li>Close down all instances of Visual Studio.</li>
<li>Rename folder C:\Program Files\Microsoft Web Designer Tools\VWD to C:\Program Files\Microsoft Web Designer Tools\Wibble</li>
<li>Install Visual Studio 2008 Service Pack 1 from here: <a href="http://www.microsoft.com/download/en/details.aspx?id=10986">http://www.microsoft.com/download/en/details.aspx?id=10986</a></li>
<li>Rename folder C:\Program Files\Microsoft Web Designer Tools\Wibble to C:\Program Files\Microsoft Web Designer Tools\VWD</li>
<li>Install ASP.NET MVC 2 from here: <a href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=22079">http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=22079</a></li>
<li>Download the file SharpArchApplicationTemplate_1_6_VS2008.zip from here: <a href="https://github.com/sharparchitecture/Sharp-Architecture/downloads">https://github.com/sharparchitecture/Sharp-Architecture/downloads</a></li>
<li>Rename the file downloaded in <strong>6</strong> to SharpArchApplicationTemplate.zip, then copy it to the Visual Studio 2008\Templates\ProjectTemplates\Visual C#\Web folder in your ‘My Documents’ area. Obviously create that folder if it doesn’t already exist. See note <strong>a)</strong> below.</li>
<li>Download the file SharpArchitecture_1_6_FullSourceAndTemplates.zip from the same place as in <strong>6</strong>. </li>
<li>From the zip file downloaded in <strong>8</strong> extract the SharpArchApplicationWizard.dll file from the VisualStudioTemplate folder. Put it in C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE.</li>
<li>Open a command line prompt (in XP,  Start button-&gt;Run-&gt;type <strong>cmd</strong>). Change directory to the folder in <strong>9</strong> by typing <strong>cd “C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE”</strong>.</li>
<li>Run the following command &#8211; <strong>.\devenv /installvstemplates</strong> (the first dot is important). This should take about 30-60 seconds to complete depending on how many other templates you have installed.</li>
<li>Start Visual Studio 2008. You should now be able to see the Sharp template in the template window when you create a new project (under Visual C#/Web).</li>
</ol>
<p>a)	(Additional note for step <strong>7</strong>) This zip file seems to cause problems when creating a new project for some people, in which case you can also extract it from the zip file downloaded in 8 (VisualStudioTemplate directory), which so far seems OK.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotscrapbook.wordpress.com/164/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotscrapbook.wordpress.com/164/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotscrapbook.wordpress.com/164/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotscrapbook.wordpress.com/164/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotscrapbook.wordpress.com/164/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotscrapbook.wordpress.com/164/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotscrapbook.wordpress.com/164/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotscrapbook.wordpress.com/164/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotscrapbook.wordpress.com/164/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotscrapbook.wordpress.com/164/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotscrapbook.wordpress.com/164/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotscrapbook.wordpress.com/164/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotscrapbook.wordpress.com/164/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotscrapbook.wordpress.com/164/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotscrapbook.wordpress.com&amp;blog=18475170&amp;post=164&amp;subd=dotscrapbook&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://dotscrapbook.wordpress.com/2011/09/13/sharp-architecture-1-6-template-installation-in-visual-studio-2008/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cec23b7b22395d8cdc18267dedad0b0f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ajerrison</media:title>
		</media:content>
	</item>
		<item>
		<title>ASP.NET MVC Input button not submitting in Internet Explorer</title>
		<link>http://dotscrapbook.wordpress.com/2011/09/06/asp-net-mvc-input-button-not-submitting-in-internet-explorer/</link>
		<comments>http://dotscrapbook.wordpress.com/2011/09/06/asp-net-mvc-input-button-not-submitting-in-internet-explorer/#comments</comments>
		<pubDate>Tue, 06 Sep 2011 12:21:44 +0000</pubDate>
		<dc:creator>Andrew Jerrison</dc:creator>
				<category><![CDATA[JS/JQuery]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[internet explorer]]></category>
		<category><![CDATA[submit button]]></category>
		<category><![CDATA[submit not working]]></category>

		<guid isPermaLink="false">http://dotscrapbook.wordpress.com/?p=159</guid>
		<description><![CDATA[If you have a piece of code that disables your submit button when you click it, such as the following: Then you will find in MVC that this does not submit when the user is using IE. Internet Explorer does not seem to like the fact that you have disabled the button (this is the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotscrapbook.wordpress.com&amp;blog=18475170&amp;post=159&amp;subd=dotscrapbook&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>If you have a piece of code that disables your submit button when you click it, such as the following:</p>
<p><pre class="brush: xml;">
   &lt;script type=&quot;text/javascript&quot;&gt;

        function delCheck() {
            if (confirm(&quot;Are you sure you want to delete?&quot;) == true) {

                
                $('#btnSubmit').attr(&quot;disabled&quot;, &quot;disabled&quot;);
                return true;
            }
            else
                return false;
        }
    &lt;/script&gt;

&lt;% using (Html.BeginForm(&quot;Delete&quot;, &quot;MyController&quot;))
   { %&gt;
           &lt;input type=&quot;submit&quot; value=&quot;Submit&quot; title=&quot;Submit&quot; name=&quot;btnSubmit&quot; id=&quot;btnSubmit&quot; onclick=&quot;return delCheck()&quot; /&gt; 
  
&lt;%} %&gt;
</pre></p>
<p>Then you will find in MVC that this does not submit when the user is using IE. Internet Explorer does not seem to like the fact that you have disabled the button (this is the case up to IE8, I&#8217;ve not checked IE9). All other browsers are OK.</p>
<p>If you need to prevent the user pressing it again then try making it invisible instead, which seems to work OK.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotscrapbook.wordpress.com/159/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotscrapbook.wordpress.com/159/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotscrapbook.wordpress.com/159/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotscrapbook.wordpress.com/159/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotscrapbook.wordpress.com/159/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotscrapbook.wordpress.com/159/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotscrapbook.wordpress.com/159/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotscrapbook.wordpress.com/159/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotscrapbook.wordpress.com/159/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotscrapbook.wordpress.com/159/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotscrapbook.wordpress.com/159/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotscrapbook.wordpress.com/159/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotscrapbook.wordpress.com/159/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotscrapbook.wordpress.com/159/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotscrapbook.wordpress.com&amp;blog=18475170&amp;post=159&amp;subd=dotscrapbook&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://dotscrapbook.wordpress.com/2011/09/06/asp-net-mvc-input-button-not-submitting-in-internet-explorer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cec23b7b22395d8cdc18267dedad0b0f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ajerrison</media:title>
		</media:content>
	</item>
		<item>
		<title>Creating and streaming an OpenXML Spreadsheet using the .Net SDK and ASP.NET MVC</title>
		<link>http://dotscrapbook.wordpress.com/2011/08/26/creating-and-streaming-an-openxml-spreadsheet-using-the-net-sdk-and-asp-net-mvc/</link>
		<comments>http://dotscrapbook.wordpress.com/2011/08/26/creating-and-streaming-an-openxml-spreadsheet-using-the-net-sdk-and-asp-net-mvc/#comments</comments>
		<pubDate>Fri, 26 Aug 2011 10:15:07 +0000</pubDate>
		<dc:creator>Andrew Jerrison</dc:creator>
				<category><![CDATA[MVC]]></category>
		<category><![CDATA[Sharp Architecture]]></category>
		<category><![CDATA[OpenXML SDK]]></category>
		<category><![CDATA[sharp architecture]]></category>
		<category><![CDATA[streaming spreadsheet ASP.NET]]></category>

		<guid isPermaLink="false">http://dotscrapbook.wordpress.com/?p=150</guid>
		<description><![CDATA[I wanted to use the OpenXML SDK to create an Excel 2007 spreadsheet on the fly and stream it directly without having to save it to a physical file first. As usual documentation on the Net was pretty sketchy, and the bits that I did find usually frustratingly left a crucial point out. (As an [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotscrapbook.wordpress.com&amp;blog=18475170&amp;post=150&amp;subd=dotscrapbook&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I wanted to use the <a href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=5124" title="Open XML SDK" target="_blank">OpenXML SDK</a> to create an Excel 2007 spreadsheet on the fly and stream it directly without having to save it to a physical file first. As usual documentation on the Net was pretty sketchy, and the bits that I did find usually frustratingly left a crucial point out. (As an aside, if developers really want their products to be used then perhaps they should actually <strong>tell</strong> us how to use them &#8211; not everyone has all day to fiddle!). </p>
<p>Anyway, below is my solution for a very simple spreadsheet generator service and ActionResult. This just allowed me to create a single worksheet table of data, which was all I required. Hopefully it is a good start point if you want anything more complex. I dare say some points are done clunkily but I didn&#8217;t have the time to figure out anything else! Some parts I grabbed from other sites on the Net, but most was added myself.</p>
<p><strong>Note:</strong> The OpenXML SDK dll is installed direct to the GAC. So when you publish the website it will not get copied to your apps&#8217;s bin directory as Visual Studio seems to assume that as it is in your GAC it will also be on the server. So you need to either install it on your server too, or manually copy it to your app&#8217;s bin directory.</p>
<p>Here is the code along with some explanation in the comments &#8211; note I am assuming you are using S#arp Architecture.</p>
<p>First the custom ActionResult, which should hopefully be self-explanatory:<br />
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.IO;
using SharpArch.Core;

namespace MyProject.Web.Controllers.CustomActionResults
{
    public class OpenSpreadsheetResult : ActionResult
    {
        private MemoryStream _spreadStream;
        private string _fileName;

        public OpenSpreadsheetResult(MemoryStream spreadsheetStream, string fileName)
        {
            Check.Require(spreadsheetStream != null, &quot;Spreadsheet stream cannot be null&quot;);
            _spreadStream = spreadsheetStream;

            if (String.IsNullOrEmpty(fileName) == true)
                _fileName = &quot;Default.xlsx&quot;;
            else
                _fileName = fileName;
        }

        public override void ExecuteResult(ControllerContext context)
        {

            context.HttpContext.Response.Clear();
            context.HttpContext.Response.AddHeader(&quot;content-disposition&quot;,
              String.Format(&quot;attachment;filename={0}&quot;, _fileName));
            context.HttpContext.Response.ContentType = &quot;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&quot;;
            _spreadStream.WriteTo(context.HttpContext.Response.OutputStream);
            _spreadStream.Close();
            context.HttpContext.Response.End(); 
                    
        } 
    }
}

</pre>  </p>
<p>Create the basic spreadsheet generator service, and also an interface to it if you are using the Castle Windsor part of S#arp:<br />
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

namespace MyProject.ApplicationServices.ReportsServices
{
    public class SpreadsheetService: ISpreadsheetService
    {
        public MemoryStream SpreadsheetStream { get; set; } // The stream that the spreadsheet gets returned on
        private Worksheet currentWorkSheet { get { return spreadSheet.WorkbookPart.WorksheetParts.First().Worksheet; } }
        private SpreadsheetDocument spreadSheet;
        private Columns _cols;

        /// &lt;summary&gt;
        /// Create a basic spreadsheet template 
        /// The structure of OpenXML spreadsheet is something like this from what I can tell:
        ///                        Spreadsheet
        ///                              |         
        ///                         WorkbookPart    
        ///                   /         |             \
        ///           Workbook WorkbookStylesPart WorksheetPart
        ///                 |          |               |
        ///            Sheets     StyleSheet        Worksheet
        ///                |                        /        \       
        ///          (refers to               SheetData        Columns  
        ///           Worksheetparts)            |   
        ///                                     Rows 
        /// 
        /// Obviously this only covers the bits in this class!
        /// &lt;/summary&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public bool CreateSpreadsheet()
        {
            try
            {
                SpreadsheetStream = new MemoryStream();

                // Create the spreadsheet on the MemoryStream
                spreadSheet =
                         SpreadsheetDocument.Create(SpreadsheetStream, SpreadsheetDocumentType.Workbook);

                WorkbookPart wbp = spreadSheet.AddWorkbookPart();   // Add workbook part
                WorksheetPart wsp = wbp.AddNewPart&lt;WorksheetPart&gt;(); // Add worksheet part
                Workbook wb = new Workbook(); // Workbook
                FileVersion fv = new FileVersion();
                fv.ApplicationName = &quot;App Name&quot;;
                Worksheet ws = new Worksheet(); // Worksheet
                SheetData sd = new SheetData(); // Data on worksheet

                // Add stylesheet
                WorkbookStylesPart stylesPart = spreadSheet.WorkbookPart.AddNewPart&lt;WorkbookStylesPart&gt;();
                stylesPart.Stylesheet = GenerateStyleSheet();
                stylesPart.Stylesheet.Save();

              
                _cols = new Columns(); // Created to allow bespoke width columns
               
                ws.Append(sd); // Add sheet data to worksheet
                wsp.Worksheet = ws; // Add the worksheet to the worksheet part
                wsp.Worksheet.Save();
                // Define the sheets that the workbooks has in it.
                
                Sheets sheets = new Sheets();
                Sheet sheet = new Sheet();
                sheet.Name = &quot;StudentData&quot;;
                sheet.SheetId = 1; // Only one sheet per spreadsheet in this class so call it sheet 1
                sheet.Id = wbp.GetIdOfPart(wsp); // ID of sheet comes from worksheet part
                sheets.Append(sheet);
                wb.Append(fv);
                wb.Append(sheets); // Append sheets to workbook

                spreadSheet.WorkbookPart.Workbook = wb;
                spreadSheet.WorkbookPart.Workbook.Save();
               
            }
            catch
            {
                return false;
            }

            return true;
        }


        /// &lt;summary&gt;
        /// add the bespoke columns for the list spreadsheet
        /// &lt;/summary&gt;
        public void CreateColumnWidth(uint startIndex, uint endIndex, double width)
        {
            // Find the columns in the worksheet and remove them all
            if (currentWorkSheet.Where(x =&gt; x.LocalName == &quot;cols&quot;).Count() &gt; 0)
                currentWorkSheet.RemoveChild&lt;Columns&gt;(_cols);

            // Create the column
            Column column = new Column();
            column.Min = startIndex;
            column.Max = endIndex;
            column.Width = width;
            column.CustomWidth = true;
            _cols.Append(column); // Add it to the list of columns

            // Make sure that the column info is inserted *before* the sheetdata
            currentWorkSheet.InsertBefore&lt;Columns&gt;(_cols, currentWorkSheet.Where(x =&gt; x.LocalName == &quot;sheetData&quot;).First());
            currentWorkSheet.Save();
            spreadSheet.WorkbookPart.Workbook.Save();

        }

        /// &lt;summary&gt;
        /// Close the spreadsheet
        /// &lt;/summary&gt;
        public void CloseSpreadsheet()
        {
            spreadSheet.Close();
        }

        /// &lt;summary&gt;
        /// Pass a list of column headings to create the header row
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;headers&quot;&gt;&lt;/param&gt;
        public void AddHeader(List&lt;string&gt; headers)
        {
            // Find the sheetdata of the worksheet
            SheetData sd = (SheetData)currentWorkSheet.Where(x =&gt; x.LocalName == &quot;sheetData&quot;).First();
            Row header = new Row();
            // increment the row index to the next row
            header.RowIndex = Convert.ToUInt32(sd.ChildElements.Count()) + 1; 
            sd.Append(header); // Add the header row

            foreach (string heading in headers)
            {
                AppendCell(header, header.RowIndex, heading, 1);
  
            }

            // save worksheet
            currentWorkSheet.Save();
           
        }


        /// &lt;summary&gt;
        /// Pass a list of data items to create a data row
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;dataItems&quot;&gt;&lt;/param&gt;
        public void AddRow(List&lt;string&gt; dataItems)
        {
            // Find the sheetdata of the worksheet
            SheetData sd = (SheetData)currentWorkSheet.Where(x =&gt; x.LocalName == &quot;sheetData&quot;).First();
            Row header = new Row();
            // increment the row index to the next row
            header.RowIndex = Convert.ToUInt32(sd.ChildElements.Count()) + 1;

            
            sd.Append(header);

            foreach (string item in dataItems)
            {
                AppendCell(header, header.RowIndex, item, 0);

            }

            // save worksheet
            currentWorkSheet.Save();
        }

        /// &lt;summary&gt;
        /// Add cell into the passed row.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;row&quot;&gt;&lt;/param&gt;
        /// &lt;param name=&quot;rowIndex&quot;&gt;&lt;/param&gt;
        /// &lt;param name=&quot;value&quot;&gt;&lt;/param&gt;
        /// &lt;param name=&quot;styleIndex&quot;&gt;&lt;/param&gt;
        private void AppendCell(Row row,  uint rowIndex, string value, uint styleIndex)
        {
            Cell cell = new Cell();
            cell.DataType = CellValues.InlineString;
            cell.StyleIndex = styleIndex;  // Style index comes from stylesheet generated in GenerateStyleSheet()
            Text t = new Text();
            t.Text = value;

            // Append Text to InlineString object
            InlineString inlineString = new InlineString();
            inlineString.AppendChild(t);

            // Append InlineString to Cell
            cell.AppendChild(inlineString);

            // Get the last cell's column
            string nextCol = &quot;A&quot;;
            Cell c = (Cell)row.LastChild;
            if (c != null) // if there are some cells already there...
            {
                int numIndex = c.CellReference.ToString().IndexOfAny(new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9' });

                // Get the last column reference
                string lastCol = c.CellReference.ToString().Substring(0, numIndex);
                // Increment
                nextCol = IncrementColRef(lastCol);
            }

            cell.CellReference = nextCol + rowIndex;

            row.AppendChild(cell);
        }

        // Increment the column reference in an Excel fashion, i.e. A, B, C...Z, AA, AB etc.
        // Partly stolen from somewhere on the Net and modified for my use.
        private string IncrementColRef(string lastRef)
        {
            char[] characters = lastRef.ToUpperInvariant().ToCharArray();
            int sum = 0;
            for (int i = 0; i &lt; characters.Length; i++)
            {
                sum *= 26;
                sum += (characters[i] - 'A' + 1);
            }

            sum++;

            string columnName = String.Empty;
            int modulo;

            while (sum &gt; 0)
            {
                modulo = (sum - 1) % 26;
                columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
                sum = (int)((sum - modulo) / 26);
            }

            return columnName;


        }

        /// &lt;summary&gt;
        /// Return a stylesheet. Completely stolen from somewhere, possibly this guy's blog,
        /// although I can't find it on there:
        /// http://polymathprogrammer.com/. Thanks whoever it was, it would have been a 
        /// nightmare trying to figure this one out!
        /// &lt;/summary&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        private Stylesheet GenerateStyleSheet()
        {
            return new Stylesheet(
                new Fonts(
                    new Font(                                                               // Index 0 - The default font.
                        new FontSize() { Val = 11 },
                        new Color() { Rgb = new HexBinaryValue() { Value = &quot;000000&quot; } },
                        new FontName() { Val = &quot;Calibri&quot; }),
                    new Font(                                                               // Index 1 - The bold font.
                        new Bold(),
                        new FontSize() { Val = 11 },
                        new Color() { Rgb = new HexBinaryValue() { Value = &quot;000000&quot; } },
                        new FontName() { Val = &quot;Calibri&quot; }),
                    new Font(                                                               // Index 2 - The Italic font.
                        new Italic(),
                        new FontSize() { Val = 11 },
                        new Color() { Rgb = new HexBinaryValue() { Value = &quot;000000&quot; } },
                        new FontName() { Val = &quot;Calibri&quot; }),
                    new Font(                                                               // Index 2 - The Times Roman font. with 16 size
                        new FontSize() { Val = 16 },
                        new Color() { Rgb = new HexBinaryValue() { Value = &quot;000000&quot; } },
                        new FontName() { Val = &quot;Times New Roman&quot; })
                ),
                new Fills(
                    new Fill(                                                           // Index 0 - The default fill.
                        new PatternFill() { PatternType = PatternValues.None }),
                    new Fill(                                                           // Index 1 - The default fill of gray 125 (required)
                        new PatternFill() { PatternType = PatternValues.Gray125 }),
                    new Fill(                                                           // Index 2 - The yellow fill.
                        new PatternFill(
                            new ForegroundColor() { Rgb = new HexBinaryValue() { Value = &quot;FFFFFF00&quot; } }
                        ) { PatternType = PatternValues.Solid })
                ),
                new Borders(
                    new Border(                                                         // Index 0 - The default border.
                        new LeftBorder(),
                        new RightBorder(),
                        new TopBorder(),
                        new BottomBorder(),
                        new DiagonalBorder()),
                    new Border(                                                         // Index 1 - Applies a Left, Right, Top, Bottom border to a cell
                        new LeftBorder(
                            new Color() { Auto = true }
                        ) { Style = BorderStyleValues.Thin },
                        new RightBorder(
                            new Color() { Auto = true }
                        ) { Style = BorderStyleValues.Thin },
                        new TopBorder(
                            new Color() { Auto = true }
                        ) { Style = BorderStyleValues.Thin },
                        new BottomBorder(
                            new Color() { Auto = true }
                        ) { Style = BorderStyleValues.Thin },
                        new DiagonalBorder())
                ),
                new CellFormats(
                    new CellFormat() { FontId = 0, FillId = 0, BorderId = 0 },                          // Index 0 - The default cell style.  If a cell does not have a style index applied it will use this style combination instead
                    new CellFormat() { FontId = 1, FillId = 0, BorderId = 0, ApplyFont = true },       // Index 1 - Bold 
                    new CellFormat() { FontId = 2, FillId = 0, BorderId = 0, ApplyFont = true },       // Index 2 - Italic
                    new CellFormat() { FontId = 3, FillId = 0, BorderId = 0, ApplyFont = true },       // Index 3 - Times Roman
                    new CellFormat() { FontId = 0, FillId = 2, BorderId = 0, ApplyFill = true },       // Index 4 - Yellow Fill
                    new CellFormat(                                                                   // Index 5 - Alignment
                        new Alignment() { Horizontal = HorizontalAlignmentValues.Center, Vertical = VerticalAlignmentValues.Center }
                    ) { FontId = 0, FillId = 0, BorderId = 0, ApplyAlignment = true },
                    new CellFormat() { FontId = 0, FillId = 0, BorderId = 1, ApplyBorder = true }      // Index 6 - Border
                )
            ); // return
        }

    }
}

</pre></p>
<p>This is how your would call the methods of the above class. I put this method in a separate &#8216;reportManager&#8217; class, but I guess you could just put it in the controller as a quicky:</p>
<p><pre class="brush: csharp;">
        // These private variables are instantiated by injection into the constructor
        private IMyRepo _myRepo;
        private ISpreadsheetService _spreadsheetService;
      public MemoryStream GenerateExcelList(// any parameters to your report here)
        {
            if (_spreadsheetService.CreateSpreadsheet() == true)
            {
                // Create a few columns
                _spreadsheetService.CreateColumnWidth(1, 1, 15);
                _spreadsheetService.CreateColumnWidth(2, 3, 20);
                _spreadsheetService.CreateColumnWidth(4, 4, 40);
                _spreadsheetService.CreateColumnWidth(5, 5, 15);
                _spreadsheetService.CreateColumnWidth(6, 7, 50);
                _spreadsheetService.CreateColumnWidth(8, 8, 25);
                _spreadsheetService.CreateColumnWidth(9, 11, 15);

                // Add column headers
                _spreadsheetService.AddHeader(new List&lt;string&gt;() { &quot;ID&quot;, &quot;Col1&quot;, &quot;Col2&quot;, &quot;Col3&quot;, &quot;Col4&quot;, &quot;Col5&quot;, &quot;col6&quot;, &quot;Col7&quot;, &quot;Col8&quot;, &quot;Col9&quot;, &quot;Col10&quot;, &quot;Total&quot;});

                // Get your data from the database here...
                List&lt;Mydata&gt; MyDataRows = _myRepo.GetAll();

                foreach (MyDataRow instance in MyDataRows)
                {
                   
                    _spreadsheetService.AddRow(new List&lt;string&gt;() { instance.ID, instance.Col1, instance.Col2, instance.Col3, instance.Col4, instance.Col5, instance.Col6, instance.Col7, instance.Col8, instance.Col9, instance.Col10, instance.Total});
                 
                }
                
                // Very important to close it!
                _spreadsheetService.CloseSpreadsheet();
            }
        
            return _spreadsheetService.SpreadsheetStream;
}
</pre></p>
<p>Finally in your controller:</p>
<p><pre class="brush: csharp;">
public ActionResult GetListReport(// any parameters to report here)
        {
            if (ModelState.IsValid)
            {

             
                try
                {
                   
                    MemoryStream reportStream = _reportsManager.GenerateExcelList(// any parameters here);


                    return new OpenSpreadsheetResult(reportStream, &quot;MyName.xlsx&quot;);
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError(&quot;MyField&quot;, &quot;Error creating report: &quot; +ex.StackTrace);
                    return View(&quot;MyReportView&quot;, model);
                }


            }
            else
            {
                return View(&quot;MyReportView&quot;, model);
            }
        }


</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotscrapbook.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotscrapbook.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotscrapbook.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotscrapbook.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotscrapbook.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotscrapbook.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotscrapbook.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotscrapbook.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotscrapbook.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotscrapbook.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotscrapbook.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotscrapbook.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotscrapbook.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotscrapbook.wordpress.com/150/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotscrapbook.wordpress.com&amp;blog=18475170&amp;post=150&amp;subd=dotscrapbook&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://dotscrapbook.wordpress.com/2011/08/26/creating-and-streaming-an-openxml-spreadsheet-using-the-net-sdk-and-asp-net-mvc/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cec23b7b22395d8cdc18267dedad0b0f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ajerrison</media:title>
		</media:content>
	</item>
		<item>
		<title>Reading tables with nHibernate that have SQL keywords as names</title>
		<link>http://dotscrapbook.wordpress.com/2011/06/08/reading-tables-with-nhibernate-that-have-sql-keywords-as-names/</link>
		<comments>http://dotscrapbook.wordpress.com/2011/06/08/reading-tables-with-nhibernate-that-have-sql-keywords-as-names/#comments</comments>
		<pubDate>Wed, 08 Jun 2011 15:58:23 +0000</pubDate>
		<dc:creator>Andrew Jerrison</dc:creator>
				<category><![CDATA[MVC]]></category>
		<category><![CDATA[nHibernate]]></category>
		<category><![CDATA[ClassMap]]></category>
		<category><![CDATA[table mapping]]></category>
		<category><![CDATA[SQL Server keyword]]></category>

		<guid isPermaLink="false">http://dotscrapbook.wordpress.com/?p=143</guid>
		<description><![CDATA[With nHibernate, if the name of the table that you are trying to map to happens to have a name which is an SQL Server keyword (i.e. User is a common one), then nHibernate will barf with a syntax error. The way to get around this in your class map is to do as follows [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotscrapbook.wordpress.com&amp;blog=18475170&amp;post=143&amp;subd=dotscrapbook&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>With nHibernate, if the name of the table that you are trying to map to happens to have a name which is an SQL Server keyword (i.e. User is a common one), then nHibernate will barf with a syntax error.</p>
<p>The way to get around this in your class map is to do as follows (for a table named User, mapped to a class named User). Notice the square brackets around the table name.</p>
<p><pre class="brush: csharp;">
public class UserMap: ClassMap&lt;User&gt;
{
    public UserMap()
    {
        Table(&quot;[User]&quot;);
        ...
    }
}
</pre></p>
<p>If you know much SQL then this might have been obvious, but if not then you&#8217;d never get there! Of course you could always just not name your tables with SQL keywords, but if you are developing for legacy systems you may not have a choice&#8230;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotscrapbook.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotscrapbook.wordpress.com/143/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotscrapbook.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotscrapbook.wordpress.com/143/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotscrapbook.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotscrapbook.wordpress.com/143/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotscrapbook.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotscrapbook.wordpress.com/143/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotscrapbook.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotscrapbook.wordpress.com/143/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotscrapbook.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotscrapbook.wordpress.com/143/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotscrapbook.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotscrapbook.wordpress.com/143/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotscrapbook.wordpress.com&amp;blog=18475170&amp;post=143&amp;subd=dotscrapbook&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://dotscrapbook.wordpress.com/2011/06/08/reading-tables-with-nhibernate-that-have-sql-keywords-as-names/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cec23b7b22395d8cdc18267dedad0b0f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ajerrison</media:title>
		</media:content>
	</item>
		<item>
		<title>Removing errors from ModelState in MVC</title>
		<link>http://dotscrapbook.wordpress.com/2011/05/31/removing-errors-from-modelstate-in-mvc/</link>
		<comments>http://dotscrapbook.wordpress.com/2011/05/31/removing-errors-from-modelstate-in-mvc/#comments</comments>
		<pubDate>Tue, 31 May 2011 11:04:49 +0000</pubDate>
		<dc:creator>Andrew Jerrison</dc:creator>
				<category><![CDATA[Controller]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://dotscrapbook.wordpress.com/?p=139</guid>
		<description><![CDATA[I wouldn&#8217;t normally try to override MVC&#8217;s own validation on textboxes etc but occasionally it can be useful. All the things I have seen so far on the Web are pretty messy &#8211; turning the ModelState into a dictionary and then iterating through it &#8211; and then just removing all the errors associated with that [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotscrapbook.wordpress.com&amp;blog=18475170&amp;post=139&amp;subd=dotscrapbook&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I wouldn&#8217;t normally try to override MVC&#8217;s own validation on textboxes etc but occasionally it can be useful. All the things I have seen so far on the Web are pretty messy &#8211; turning the ModelState into a dictionary and then iterating through it &#8211; and then just removing all the errors associated with that screen control regardless of what the error is. Not very subtle and a bit hacky.</p>
<p>The code below shows a way of doing this in the (slightly contrived but simple) situation where you have a view model with a strongly typed non-nullable DateTime tied to a textbox. This will of course throw an error automatically when trying to submit a blank in the textbox &#8211; which is great most of the time. However in a particular context you might want to allow it. Instead of making the DateTime nullable in the view model, and then manually testing for null you could also check for the error in the ModelState and then remove it. Here is how:</p>
<p><pre class="brush: csharp;">
public ActionResult Save(MyViewModel model, string btnSave, string btnCancel)
{
       ModelState val;
       if (ModelState.TryGetValue(&quot;MyDate&quot;, out val) == true)
       {
              if (val.Value.AttemptedValue == &quot;&quot;) // Test for the string you are going to allow here              
              {
                        ModelState.Remove(new KeyValuePair&lt;string, ModelState&gt;(&quot;MyDate&quot;, val));
                        model.MyDate = null; // Set your property to whatever your override is here
              }
       }

      .....
}
 
</pre></p>
<p>Obviously the example is a little bit contrived, but the point is that you can use the AttemptedValue property to check for specific entered values &#8211; which is useful if you only want to check for a particular value. Also &#8211; the TryGetValue method is very useful too, no converting to dictionaries and iterating needed! </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotscrapbook.wordpress.com/139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotscrapbook.wordpress.com/139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotscrapbook.wordpress.com/139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotscrapbook.wordpress.com/139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotscrapbook.wordpress.com/139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotscrapbook.wordpress.com/139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotscrapbook.wordpress.com/139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotscrapbook.wordpress.com/139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotscrapbook.wordpress.com/139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotscrapbook.wordpress.com/139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotscrapbook.wordpress.com/139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotscrapbook.wordpress.com/139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotscrapbook.wordpress.com/139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotscrapbook.wordpress.com/139/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotscrapbook.wordpress.com&amp;blog=18475170&amp;post=139&amp;subd=dotscrapbook&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://dotscrapbook.wordpress.com/2011/05/31/removing-errors-from-modelstate-in-mvc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cec23b7b22395d8cdc18267dedad0b0f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ajerrison</media:title>
		</media:content>
	</item>
		<item>
		<title>MVC &#8211; Getting User Roles From Multiple Sources (register and resolve arrays of dependencis using the fluent api)</title>
		<link>http://dotscrapbook.wordpress.com/2011/05/18/mvc-getting-user-roles-from-multiple-sources-register-and-resolve-arrays-of-dependencis-using-the-fluent-api/</link>
		<comments>http://dotscrapbook.wordpress.com/2011/05/18/mvc-getting-user-roles-from-multiple-sources-register-and-resolve-arrays-of-dependencis-using-the-fluent-api/#comments</comments>
		<pubDate>Wed, 18 May 2011 10:04:24 +0000</pubDate>
		<dc:creator>Alex Hardman</dc:creator>
				<category><![CDATA[Castle]]></category>
		<category><![CDATA[Fluent]]></category>
		<category><![CDATA[Miscellaneous]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[role provider]]></category>
		<category><![CDATA[roles]]></category>
		<category><![CDATA[RolesProvider]]></category>

		<guid isPermaLink="false">http://dotscrapbook.wordpress.com/?p=126</guid>
		<description><![CDATA[In the last post I talked about encapsulating the authorisation and user credentials (i.e IPrincipal) logic in a separate, re-usable DLL (known as AuthServices). Part 1 of that post discussed the DLL contents in detail. Part 2 focused upon using that DLL in an MVC application. This post follows up on &#8220;Part 2&#8243; specifically adding [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotscrapbook.wordpress.com&amp;blog=18475170&amp;post=126&amp;subd=dotscrapbook&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In the last post I talked about encapsulating the authorisation and user credentials (i.e IPrincipal) logic in a separate, re-usable DLL (known as <a title="creating-a-resusable-authorisation-user-principal-library-for-mvc-projects/" href="http://dotscrapbook.wordpress.com/2011/05/17/creating-a-resusable-authorisation-user-principal-library-for-mvc-projects/" target="_blank"><strong>AuthServices</strong></a>).</p>
<p>Part 1 of that post discussed the DLL contents in detail. Part 2 focused upon using that DLL in an MVC application.</p>
<p>This post follows up on &#8220;Part 2&#8243; specifically adding a user&#8217;s roles to the UserData objet prior to serialisation, on-route to becoming the auth cookie.</p>
<p>The code sample that I gave for using the AuthServices DLL is repeated below:</p>
<p><pre class="brush: csharp;">
_authenticationService.Authenticate(userNameString, password);
if (_authenticationService.Result.Authenticated)
{
       _currentUserData = _authenticationService.Result.CurrentUserData;
       _currentUserData.Roles = GetRolesForUser(userName);//THE SUBJECT OF THIS POST
       _cookieManager.CreateUserCookie(userName, _currentUserData);
}
</pre></p>
<p>This post explores in more detail what lies behind the <strong>GetRolesForUser(string userName) method</strong> and how this can utilise more than one provider of roles.</p>
<h2>Why bother?</h2>
<p>The organisation in which I work is big. We have thousands of staff and many thousands more students. Applications written for an organisation of this size usually need to access different sources of data to provide a user&#8217;s roles relevant to the specific application. In projects like this you can&#8217;t easily use the standard RoleProvider stuff in a config file.</p>
<h2>The Answer &#8211; Multiple Role Providers</h2>
<p>To implement multiple roles I inject (in an IOC stylee) into my login service the interface IRolesMgr. IRolesMgr exposes the following:</p>
<p><pre class="brush: csharp;">
public interface IRolesMgr
    {
        List GetAllRolesForUser(string userName);
    }
</pre></p>
<p>The interesting part is in the constructor of the implementation.</p>
<p><pre class="brush: csharp;">
public class RolesMgr: IRolesMgr
    {
        private IRoleMgrComponent[] _roleManagers;

        public RolesMgr(IRoleMgrComponent[] roleManagers)
        {
            _roleManagers = roleManagers;
        }

        public List GetAllRolesForUser(string userName)
        {
            List roles = new List();
            foreach (var mgr in _roleManagers)
            {
                roles.AddRange(mgr.GetRolesForUser(userName));
            }
        }
    }
</pre></p>
<p>As can be seen the constructor has a dependency on an array of <strong>IRoleMgrComponents</strong> each of which will contain the access logic needed to identify a user&#8217;s roles from a different source.<br />
Each IRoleMgrComponent implements the following:</p>
<p><pre class="brush: csharp;">
public interface IRoleMgrComponent
    {
        List GetRolesForUser(string userName);
    }
</pre></p>
<p>That&#8217;s all very good, but the trick is getting the IOC container, in this case, <a title="Castle Windsor" href="http://www.castleproject.org/container/index.html" target="_blank">Castle Windsor</a>, to instantiate the appropriate implementations of IRoleMgrComponent in the roleManagers array.</p>
<p>This is done in the Component Registrar class used to register components to Castle by using the &#8220;ServiceOveride&#8221; method (more details of this can be seen on <a title="Mike Hadlows post" href="http://mikehadlow.blogspot.com/2009/03/castle-windsor-registering-and.html" target="_blank">Mike Hadlow&#8217;s post</a> &#8211; which was the original inspiration for the castle registration code &#8211; thanks Mike!). In effect this allows you to register and resolve arrays of dependencis using the fluent api.</p>
<p><pre class="brush: csharp;">
container.Register(
                Component.For()
                    .ImplementedBy()
                    .ServiceOverrides(
                        ServiceOverride.ForKey(&quot;roleManagers&quot;).Eq(
                            &quot;HumsAuthDbRoleManager&quot;,
                            &quot;StudentAuthRoleMgr&quot;
                        )
                    ),
                AllTypes
                    .FromAssemblyNamed(&quot;ApplicationServices&quot;)
                    .BasedOn()
                        .WithService.FromInterface(typeof(IRoleMgrComponent))
                        .Configure(c =&gt; c.Named(c.Implementation.Name))
                );
</pre><br />
Once you have overriden this specific component you can continue to register all the other components in that assembly in the normal way, say:<br />
<pre class="brush: csharp;">
container.Register(
                AllTypes.Pick()
                .FromAssemblyNamed(&quot;ApplicationServices&quot;)
                .WithService.FirstInterface());
</pre></p>
<h2>Conclusion</h2>
<p>Implementing RolesMgr(IRoleMgrComponent[]) in conjunction with the AuthServices assembly talked about in the last post, means that for any given new project I will only have to write minimal code yet benefit from User Credential information that:<br />
a) Has the execution logic encapsulated in an (extensible) AuthServices library<br />
b) Can uitilise dependency injection to configure how where and how the roles data comes from in the credential information.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotscrapbook.wordpress.com/126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotscrapbook.wordpress.com/126/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotscrapbook.wordpress.com/126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotscrapbook.wordpress.com/126/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotscrapbook.wordpress.com/126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotscrapbook.wordpress.com/126/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotscrapbook.wordpress.com/126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotscrapbook.wordpress.com/126/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotscrapbook.wordpress.com/126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotscrapbook.wordpress.com/126/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotscrapbook.wordpress.com/126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotscrapbook.wordpress.com/126/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotscrapbook.wordpress.com/126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotscrapbook.wordpress.com/126/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotscrapbook.wordpress.com&amp;blog=18475170&amp;post=126&amp;subd=dotscrapbook&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://dotscrapbook.wordpress.com/2011/05/18/mvc-getting-user-roles-from-multiple-sources-register-and-resolve-arrays-of-dependencis-using-the-fluent-api/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1becb701cf4e3c52bceaec36e336439c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">actualal</media:title>
		</media:content>
	</item>
	</channel>
</rss>
