<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title type="html">aspnet - on code</title>
  <icon>http://suhair.in/Content/icons/flame.ico</icon>
  <logo>http://suhair.in/Content/icons/flame.png</logo>
  <updated>2010-01-06T08:00:00</updated>
  <id>http://suhair.in/tags/aspnet/atom</id>
  <link rel="alternate" type="text/html" hreflang="en" href="/tags/aspnet/atom"/>
  <link rel="self" type="application/atom+xml" href="http://suhair.in/Tags/aspnet/ATOM"/>
  <generator uri="http://oxite.net" version="1.0">Oxite</generator>
  <entry>
    <title type="html">Dependency Injection in Asp.net MVC using MVC Contrib</title>
    <link rel="alternate" type="text/html" href="http://suhair.in/Blog/Dependency-Injection-in-Aspnet-MVC-using-MVC-Contrib"/>
    <id>http://suhair.in/Blog/Dependency-Injection-in-Aspnet-MVC-using-MVC-Contrib</id>
    <updated>2010-01-07T05:23:10.037</updated>
    <published>2010-01-06T08:00:00</published>
    <author>
      <name>Admin</name>
    </author>
    <category term="structuremap" />
    <category term="dependencyinjection" />
    <category term="csharp" />
    <category term="mvccontrib" />
    <category term="aspnet" />
    <category term="mvc" />
    <content type="html" xml:lang="en">
      &lt;p&gt;
	For the sake of creating the sample let&amp;#39;s introduce the dependency of a ILinkRepository in our brand new asp.net MVC application. Eventually this repository will be used by our HomeController to display a number of Links and finally we will inject the dependency by StructureMap dependency framework..&amp;nbsp;&lt;/p&gt;
&lt;p&gt;
	&lt;img alt=&quot;Hosted by imgur.com&quot; src=&quot;http://imgur.com/ZAy6c.jpg&quot; /&gt;&lt;/p&gt;
&lt;p&gt;
	Next we will add the dependency of ILinkRepository on our HomeController. Since the default ControllerFactory cannot cope with controllers having no default constructor we will hard code the initialization of this dependency on the default constructor. Finally we will pass the list of links to the view and the view will display it for the user. This is the common scenario.&lt;/p&gt;
&lt;p&gt;
	&lt;img alt=&quot;Hosted by imgur.com&quot; src=&quot;http://imgur.com/A1Mze.jpg&quot; /&gt;&lt;/p&gt;
&lt;p&gt;
	Since view is strongly typed, it will just iterate over the collection producing a list of links. We are now done with the basic structure of the application. We have just used a type of dependency injection infamously known as Poor Man&amp;#39;s dependency injection since the HomeController constructor hard coded the creation of the repository.&lt;/p&gt;
&lt;p&gt;
	&lt;img alt=&quot;Hosted by imgur.com&quot; src=&quot;http://imgur.com/VRO0a.jpg&quot; /&gt;&lt;/p&gt;
&lt;p&gt;
	Now, it&amp;#39;s time to modify the controller for dependency injection. Since we are using dependency injection, controller is not concerned with creating the repository as in previous version. Dependency injection framework will automatically provide the dependent repository to the controller.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;
	&lt;img alt=&quot;Hosted by imgur.com&quot; src=&quot;http://imgur.com/O1iki.jpg&quot; /&gt;&lt;/p&gt;
&lt;p&gt;
	Running the application now will definitely produce an error since the default controller factory cannot create controllers having no parameterless constructor as shown below.&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;
	&lt;span class=&quot;inlinecode&quot;&gt;&lt;i&gt;No parameterless constructor defined for this object.&lt;/i&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;
	Finally we are in a position to introduce the StructureMap dependency injection framework to the MVC application. It could be configured in the Global.asax.cs file as follows and the application will run as expected.&lt;/p&gt;
&lt;p&gt;
	&lt;img alt=&quot;Hosted by imgur.com&quot; src=&quot;http://imgur.com/8ISjh.jpg&quot; /&gt;&lt;/p&gt;
&lt;p&gt;
	&amp;nbsp;&lt;/p&gt;
&lt;p&gt;
	Source code could be downloaded from &lt;a href=&quot;http://github.com/suhair/DependencyInjection-Demo&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;
	&amp;nbsp;&lt;/p&gt;
&lt;a rev=&quot;vote-for&quot; href=&quot;http://dotnetshoutout.com/Dependency-Injection-in-Aspnet-MVC-using-MVC-Contrib-on-code&quot;&gt;&lt;img alt=&quot;Shout it&quot; src=&quot;http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fsuhair.in%2FBlog%2FDependency-Injection-in-Aspnet-MVC-using-MVC-Contrib&quot; style=&quot;border:0px&quot;/&gt;&lt;/a&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Asp.net MVC Areas in depth - Part 2</title>
    <link rel="alternate" type="text/html" href="http://suhair.in/Blog/Aspnet-MVC-Areas-in-depth-Part-2"/>
    <id>http://suhair.in/Blog/Aspnet-MVC-Areas-in-depth-Part-2</id>
    <updated>2009-10-12T08:42:07.097</updated>
    <published>2009-10-10T08:00:00</published>
    <author>
      <name>Admin</name>
    </author>
    <category term="csharp" />
    <category term="aspnet" />
    <category term="mvc" />
    <content type="html" xml:lang="en">
      &lt;p&gt;
	One of the first gotchas that will come across while using the asp.net MVC areas is in the usage of same controller name across different areas and the main project. For example the default asp.net MVC template has a &lt;span classs=&quot;inlinecode&quot;&gt;HomeController&lt;/span&gt; and if we add the &lt;span classs=&quot;inlinecode&quot;&gt;HomeController&lt;/span&gt; to one of the areas, accessing the home part of the areas will work fine but accessing the main home url will result in the following error&lt;/p&gt;
&lt;pre&gt;	&lt;i&gt;The controller name &amp;#39;home&amp;#39; is ambiguous between the following types: 
        AreasInDepth.Controllers.HomeController 
        AreasInDepth.Areas.Blog.Controllers.HomeController&lt;/i&gt;

&lt;/pre&gt;
&lt;p&gt;
	The easiest solution is to come up with unique controller names. Since the routing for the controllers in the areas works fine in this case and the only thing we have to fix is the main controllers we can use another concept to make this code work. The following code in Global.asax file is all that is required to fix this mess&lt;/p&gt;
&lt;pre class=&quot;prettyprint&quot;&gt; protected void Application_Start()
 {
      AreaRegistration.RegisterAllAreas();
      RegisterRoutes(RouteTable.Routes);
      ControllerBuilder.Current.DefaultNamespaces.Add(&amp;quot;AreasInDepth.Controllers&amp;quot;); &lt;span class=&quot;box nocode&quot;&gt;1&lt;/span&gt;
 }
&lt;/pre&gt;
&lt;p&gt;
	Simply, the above code instructs the &lt;span class=&quot;inlinecode&quot;&gt;DefaultControllerFactory&lt;/span&gt; to give priority for the controller inside the main project over those in areas and do not throw the previous &lt;span classs=&quot;inlinecode&quot;&gt;InvalidOperationException&lt;/span&gt; if the controller name is happened to be unique among these default name spaces &lt;span class=&quot;box&quot;&gt;1&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;
	It&amp;#39;s time to continue exploring the areas in asp.net MVC 2 preview 2&lt;/p&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;public Route MapRoute(string name, string url, object defaults, object constraints, string[] namespaces) 
{
    if (namespaces == null &amp;amp;&amp;amp; Namespaces != null) {
        namespaces = Namespaces.ToArray();
    }

    Route route = Routes.MapRoute(name, url, defaults, constraints, namespaces); &lt;span class=&quot;box nocode&quot;&gt;1&lt;/span&gt;
    route.DataTokens[&amp;quot;area&amp;quot;] = AreaName;&lt;span class=&quot;box nocode&quot;&gt;2&lt;/span&gt;

    bool useNamespaceFallback = (namespaces == null || namespaces.Length == 0);
    route.DataTokens[&amp;quot;UseNamespaceFallback&amp;quot;] = useNamespaceFallback; &lt;span class=&quot;box nocode&quot;&gt;3&lt;/span&gt;

    return route;
}

&lt;/pre&gt;
&lt;p&gt;
	&lt;span class=&quot;inlinecode&quot;&gt;MapRoute&lt;/span&gt; function of the &lt;span class=&quot;inlinecode&quot;&gt;AreaRegistrationContext&lt;/span&gt; class, discussed in the previous &lt;a href=&quot;http://suhair.in/Blog/aspnet-areas-in-depth&quot;&gt;post&lt;/a&gt;, creates and adds &lt;span class=&quot;box&quot;&gt;1&lt;/span&gt; a Route to the global static &lt;span class=&quot;inline&quot;&gt;RouteTable.Routes&lt;/span&gt;. It also places two data tokens namely area &lt;span class=&quot;box&quot;&gt;2&lt;/span&gt; and UseNamespaceFallback &lt;span class=&quot;box&quot;&gt;3&lt;/span&gt; which are later utilized in the route mapping workflow. If namespaces are not provided UseNameSpaceFallBack data token will have the value of true and the &lt;span classs=&quot;inlinecode&quot;&gt;DefaultControllerFactory&lt;/span&gt; will probe the rest of the namespaces to get a valid controller type. This is a useful hook to prevent the &lt;span classs=&quot;inlinecode&quot;&gt;DefaultControllerFactory&lt;/span&gt; from searching for controller in unintended areas. Rest of the magic happens during the request processing and we have to look the code inside &lt;span classs=&quot;inlinecode&quot;&gt;DefaultControllerFactory&lt;/span&gt;, and here it is&lt;/p&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;protected internal virtual Type GetControllerType(RequestContext requestContext, string controllerName) {
    if (String.IsNullOrEmpty(controllerName)) {
        throw new ArgumentException(MvcResources.Common_NullOrEmpty, &amp;quot;controllerName&amp;quot;);
    }

   
    object routeNamespacesObj;
    Type match;

     &lt;span class=&quot;box nocode&quot;&gt;1&lt;/span&gt;
    if (requestContext != null &amp;amp;&amp;amp; requestContext.RouteData.DataTokens.TryGetValue(&amp;quot;Namespaces&amp;quot;, out routeNamespacesObj)) 
    {
        IEnumerable&lt;string&gt; routeNamespaces = routeNamespacesObj as IEnumerable&lt;string&gt;;
        if (routeNamespaces != null) {
            HashSet&lt;string&gt; nsHash = new HashSet&lt;string&gt;(routeNamespaces, StringComparer.OrdinalIgnoreCase);
            match = GetControllerTypeWithinNamespaces(controllerName, nsHash);

            
            if (match != null || false.Equals(requestContext.RouteData.DataTokens[&amp;quot;UseNamespaceFallback&amp;quot;])) {
                
                return match; &lt;span class=&quot;box nocode&quot;&gt;2&lt;/span&gt;
            }
        }
    }

    
    HashSet&lt;string&gt; nsDefaults = new HashSet&lt;string&gt;(ControllerBuilder.DefaultNamespaces, StringComparer.OrdinalIgnoreCase);
    match = GetControllerTypeWithinNamespaces(controllerName, nsDefaults); &lt;span class=&quot;box nocode&quot;&gt;3&lt;/span&gt;
    if (match != null) {
        return match;
    }

    
    return GetControllerTypeWithinNamespaces(controllerName, null /* namespaces */); &lt;span class=&quot;box nocode&quot;&gt;4&lt;/span&gt;
}


&lt;/string&gt;&lt;/string&gt;&lt;/string&gt;&lt;/string&gt;&lt;/string&gt;&lt;/string&gt;&lt;/pre&gt;
&lt;p&gt;
	&lt;span classs=&quot;inlinecode&quot;&gt;GetControllerType&lt;/span&gt;, first searches &lt;span class=&quot;box&quot;&gt;1&lt;/span&gt; the route namesapaces for the matching controller type. It will exit the search if a match is found or the namespace fallback option &lt;span class=&quot;box&quot;&gt;2&lt;/span&gt; is set to false. If the previous two conditions were not satisfied the function will search for the type in the application&amp;#39;s default namespaces collection &lt;span class=&quot;box&quot;&gt;3&lt;/span&gt;. This is the scenario explained at the beginning of this post. Finally there will be a fallback option to search all of the namespaces for valid controller type. &lt;span class=&quot;box&quot;&gt;4&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;
	&amp;nbsp;&lt;/p&gt;
&lt;div class=&quot;shoutout&quot;&gt;
	&lt;a href=&quot;http://dotnetshoutout.com/Aspnet-MVC-Areas-in-depth-Part-2-on-code&quot; rev=&quot;vote-for&quot;&gt;&lt;img alt=&quot;Shout it&quot; src=&quot;http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fsuhair.in%2FBlog%2FAspnet-MVC-Areas-in-depth-Part-2&quot; style=&quot;border: 0px none ;&quot; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&lt;a href=&quot;http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fsuhair.in%2fBlog%2fAspnet-MVC-Areas-in-depth-Part-2&quot;&gt;&lt;img alt=&quot;kick it on DotNetKicks.com&quot; border=&quot;0&quot; src=&quot;http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fsuhair.in%2fBlog%2fAspnet-MVC-Areas-in-depth-Part-2&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Asp.net MVC Areas in depth</title>
    <link rel="alternate" type="text/html" href="http://suhair.in/Blog/aspnet-areas-in-depth"/>
    <id>http://suhair.in/Blog/aspnet-areas-in-depth</id>
    <updated>2009-10-04T12:10:05.617</updated>
    <published>2009-10-02T08:00:00</published>
    <author>
      <name>Admin</name>
    </author>
    <category term="csharp" />
    <category term="aspnet" />
    <category term="mvc" />
    <content type="html" xml:lang="en">
      &lt;pre class=&quot;prettyprint&quot;&gt;protected void Application_Start()
{
     AreaRegistration.RegisterAllAreas(); &lt;span class=&quot;box nocode&quot;&gt;1&lt;/span&gt;
     RegisterRoutes(RouteTable.Routes);
}

&lt;/pre&gt;
&lt;p&gt;
	In the &lt;span class=&quot;inlinecode&quot;&gt;Application_Start&lt;/span&gt; event, the Asp.net MVC application registers the areas by calling a static function on the &lt;span class=&quot;inlinecode&quot;&gt;AreaRegistration&lt;/span&gt; abstract class &lt;span class=&quot;box&quot;&gt;1&lt;/span&gt;.&lt;/p&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;public static void RegisterAllAreas() 
{
      RegisterAllAreas(null);
}

public static void RegisterAllAreas(object state) 
{
                                 &lt;span class=&quot;box nocode&quot;&gt;2&lt;/span&gt;                        &lt;span class=&quot;box nocode&quot;&gt;3&lt;/span&gt;
      RegisterAllAreas(RouteTable.Routes, new BuildManagerWrapper(), state);
}
&lt;/pre&gt;
&lt;p&gt;
	&lt;span class=&quot;inlinecode&quot;&gt;RegisterAllAreas&lt;/span&gt; function was finally invoked with a &lt;span class=&quot;inlinecode&quot;&gt;RouteCollection&lt;/span&gt; &lt;span class=&quot;box&quot;&gt;2&lt;/span&gt; and an &lt;span class=&quot;inlinecode&quot;&gt;IBuildManager&lt;/span&gt; instance &lt;span class=&quot;box&quot;&gt;3&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;
	&lt;span class=&quot;inlinecode&quot;&gt;Buildmanager&lt;/span&gt; provides the methods to manage the Asp.net compilation. &lt;span class=&quot;inlinecode&quot;&gt;GetReferencedAssemblies&lt;/span&gt; method of the &lt;span class=&quot;inlinecode&quot;&gt;Buildmanager&lt;/span&gt; will return a collection of assemblies which includes those specified in assemblies element of web.config, assemblies built from App_Code folder, and assemblies from other top level folders.&lt;/p&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;internal static void RegisterAllAreas(RouteCollection routes, IBuildManager buildManager, object state) 
{
                                                                                               &lt;span class=&quot;box nocode&quot;&gt;4&lt;/span&gt;
        List&lt;type&gt; areaRegistrationTypes = TypeHelpers.FilterTypesInAssemblies(buildManager, IsAreaRegistrationType);
        foreach (Type areaRegistrationType in areaRegistrationTypes) 
        {
            AreaRegistration registration = (AreaRegistration)Activator.CreateInstance(areaRegistrationType);&lt;span class=&quot;box nocode&quot;&gt;5&lt;/span&gt;
            registration.CreateContextAndRegister(routes, state);
        }
}
&lt;/type&gt;&lt;/pre&gt;
&lt;p&gt;
	From the referenced assemblies, the application filters, using a predicate &lt;span class=&quot;box&quot;&gt;4&lt;/span&gt;, those of &lt;span class=&quot;inlinecode&quot;&gt;AreaRegistration&lt;/span&gt; Type and creates an instance for each item found &lt;span class=&quot;box&quot;&gt;5&lt;/span&gt;. In asp.net MVC preview 2 a class that is derived from &lt;span class=&quot;inlinecode&quot;&gt;AreaRegistration&lt;/span&gt; Type should be present in the corresponding area&amp;#39;s folder and the instances of these classes are the ones created in the above step.&lt;/p&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;public class Routes: AreaRegistration &lt;span class=&quot;box nocode&quot;&gt;6&lt;/span&gt;
{
                                           &lt;span class=&quot;box nocode&quot;&gt;7&lt;/span&gt;
    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(&amp;quot;blog_default&amp;quot;, &amp;quot;Blog/{controller}/{action}/{id}&amp;quot;,
                             new {controller = &amp;quot;Post&amp;quot;, action = &amp;quot;index&amp;quot;, id = &amp;quot;&amp;quot;});&lt;span class=&quot;box nocode&quot;&gt;8&lt;/span&gt;
    }

    public override string AreaName &lt;span class=&quot;box nocode&quot;&gt;5&lt;/span&gt;
    {
        get { return &amp;quot;blog&amp;quot;; }
    }
}
&lt;/pre&gt;
&lt;p&gt;
	&lt;span class=&quot;inlinecode&quot;&gt;CreateContextAndRegister&lt;/span&gt; method of &lt;span class=&quot;inlinecode&quot;&gt;AreaRegistration&lt;/span&gt; instance packages the &lt;span class=&quot;inlinecode&quot;&gt;RouteCollection&lt;/span&gt;, object state, and area name &lt;span class=&quot;box&quot;&gt;5&lt;/span&gt; (which is obtained from the user defined AreaRegistration derived class &lt;span class=&quot;box&quot;&gt;6&lt;/span&gt;) in to an &lt;span class=&quot;inlinecode&quot;&gt;AreaRegistrationContext&lt;/span&gt; and passes the context &lt;span class=&quot;box&quot;&gt;7&lt;/span&gt; to the &lt;span class=&quot;inlinecode&quot;&gt;RegisterArea&lt;/span&gt; method which is implemented in the user defined &lt;span&gt;AreaRegistration&lt;/span&gt; class. The custom defined AreaRegistration class then can add the required routes &lt;span class=&quot;box&quot;&gt;8&lt;/span&gt; to the RoutesCollection and the internals of these will be further explored in the next post.&lt;/p&gt;


&lt;a rev=&quot;vote-for&quot; href=&quot;http://dotnetshoutout.com/Aspnet-MVC-Areas-in-depth-on-code&quot;&gt;&lt;img alt=&quot;Shout it&quot; src=&quot;http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fsuhair.in%2FBlog%2Faspnet-areas-in-depth&quot; style=&quot;border:0px&quot;/&gt;&lt;/a&gt;
    </content>
  </entry>
</feed>
