Dictionary of U.S. States

1

This post is not exactly ground breaking but can be very useful when you have objects that have a State property. It is this kind of stuff that can kill your development mojo and slow you down. That is why I posted it on here, so you can move on to the more important stuff.

public static class USStates
{
public static readonly Dictionary States = new Dictionary
{
{"AL","	Alabama"},
{"AK","	Alaska"},
{"AZ","	Arizona"},
{"AR","	Arkansas"},
{"CA","	California"},
{"CO","	Colorado"},
{"CT","	Connecticut"},
{"DE","	Delaware"},
{"FL","	Florida"},
{"GA","	Georgia"},
{"HI","	Hawaii"},
{"ID","	Idaho"},
{"IL","	Illinois"},
{"IN","	Indiana"},
{"IA","	Iowa"},
{"KS","	Kansas"},
{"KY","	Kentucky"},
{"LA","	Louisiana"},
{"ME","	Maine"},
{"MD","	Maryland"},
{"MA","	Massachusetts"},
{"MI","	Michigan"},
{"MN","	Minnesota"},
{"MS","	Mississippi"},
{"MO","	Missouri"},
{"MT","	Montana"},
{"NE","	Nebraska"},
{"NV","	Nevada"},
{"NH","	New Hampshire"},
{"NJ","	New Jersey"},
{"NM","	New Mexico"},
{"NY","	New York"},
{"NC","	North Carolina"},
{"ND","	North Dakota"},
{"OH","	Ohio"},
{"OK","	Oklahoma"},
{"OR","	Oregon"},
{"PA","	Pennsylvania"},
{"RI","	Rhode Island"},
{"SC","	South Carolina"},
{"SD","	South Dakota"},
{"TN","	Tennessee"},
{"TX","	Texas"},
{"UT","	Utah"},
{"VT","	Vermont"},
{"VA","	Virginia"},
{"WA","	Washington"},
{"WV","	West Virginia"},
{"WI","	Wisconsin"},
{"WY","	Wyoming"},
{"AS","	American Samoa"},
{"DC","	District of Columbia"},
{"FM","	Federated States of Micronesia"},
{"MH","	Marshall Islands"},
{"MP","	Northern Mariana Islands"},
{"PW","	Palau"},
{"PR","	Puerto Rico"},
{"VI","	Virgin Islands"},
{"GU","	Guam"}
};

public static IList GetAbbreviations()
{
return States.Keys.ToList();
}
}

I have also included Commonwealths and Territories. I have excluded Military states like “Armed Forces Africa”. The list I used can be seen at 50States.com. This list should be good for a long time.

Picking Your Constructor With Unity

0

I use Enterprise Library’s Unity for my Inversion of Control container. I also use constructor based injection when writing my own services, repositories, and objects; this is the cleanest form of injection IMHO. All my classes usually have one constructor, so I rarely run into a problem with overloaded constructors, but other libraries don’t usually follow this convention (rightfully so, not everyone does IoC). I am currently working on a project using Rob Conery’s awesome SubSonic 3, but I ran into a little speed bump.

11-9-2009 11-37-02 AM

oh jeez! So I have a class that has more than one constructor and I need Unity to pick the right constructor. If you are familiar with Unity then the bottom code will look familiar.

            container.RegisterType<IUsersService, UsersService>()
                     .RegisterType<IUsersRepository, SubSonicUsersRepository>()
                     .RegisterType<IPasswordSecuringService, HashingPasswordSecuringService>()
                     .RegisterType<IRepository, SimpleRepository>();

So how do you pick the constructor you want. Well it’s simple, you just have to let Unity know by configuring your container.

            container.RegisterType<IUsersService, UsersService>()
                     .RegisterType<IUsersRepository, SubSonicUsersRepository>()
                     .RegisterType<IPasswordSecuringService, HashingPasswordSecuringService>()
                     .RegisterType<IRepository, SimpleRepository>()
                     .Configure<InjectedMembers>()
                     .ConfigureInjectionFor<SimpleRepository>(new InjectionConstructor(SimpleRepositoryOptions.Default));

You’ll notice we have to say what we are configuring. In this instance we want to configure an injected member. The next step is to pick the target, the concrete target, which is SubSonic’s SimpleRepository. Finally, we create a InjectionConstructor class which will hold all of our parameters for the constructor.  Again, I rarely use this feature within my own code so I forget it and have to go looking for it in old code. Hopefully blogging about it will keep it fresh in my mind or at the very least I know where to look now.

Hopefully this helps.

Visual Studio 2010 Without ReSharper 5.0

1

I’ve started a new project in Visual Studio 2010 because I want to take advantage of the new features in ASP.NET MVC 2. The features I am really interested in are Areas and the support of the new client side validation libraries that utilize the Data Annotations attributes. I sat down and set up my new solution as usual. Everything at this point was going great. Rolling up my sleeves, after several minutes of coding the ReSharper 5.0 nightly build started barfing on me. The shortcut keys barely worked and it would constantly freeze VS2010 when viewing Html pages. Ultimately, I realized that ReSharper 5.0 was not ready for VS2010, although it works great in VS2008. Now I was faced with the cold reality of having to uninstall ReSharper, for the greater good of the project. I haven’t coded a project without ReSharper in about two years, but now I am venturing forth until ReSharper 5.0 can catch up with me. Below, I’m going to list the things that I miss most about development life with ReSharper.

Visual Studio 2010 Without ReSharper

Visual Studio 2010 Without ReSharper

1. Development Time Error Checking

Resharper tells you that you’ve made a mistake before you ever compile your solution. It is constantly compiling you application in the background and making sure everything is still gravy. This keeps you from hitting f5 or Ctrl+Shift+B every ten seconds. This has to be the feature I miss the most. This is definitely a feature Microsoft should look into building directly into future versions of Visual Studio. Wouldn’t you like to know that you typed something wrong  the second you type it wrong? In addition to finding your mistakes, it places a nice little sidebar to tell you where you can find where you went wrong.

2. Solution Wide Searches for Dependencies

Resharper is really smart about what classes you are using. It can search through your entire solution and add any dependency to your existing project. This greatly reduces the need to right click on a project and click the “Add Reference” option. It even remembers third party assemblies and can add them; assemblies like NUnit or Enterprise Library.

3. Ctrl + Click = Magic

ReSharper lets you hold down the control key on your keyboard and click on a class name, which instantly takes you to the source of that class. Can greatly speed up you navigational abilities.

4. ReSharper Test Runner

ReSharper has a great test runner which runs almost all unit testing frameworks. The alternative for me right now is running tests using TestDriven.Net and Gallio, which isn’t too bad but it isn’t as nice a workflow as using ReSharper.

5. The Super Shortcut Alt+Enter

Alt+Enter, remember that key combination if you want to be a coding ninja. A super shortcut in ReSharper that understands the context you are in and shows you appropriate actions. Want to remove unused namespaces? Move your cursor to the namespaces section of your code and press Alt+Enter. Want to use var instead? Alt+Enter. Want to rename a file to match a class name? Alt+Enter. Want to move a class to a namespace? Alt+Enter. Want to rule the world? Alt+Enter (coming in ReSharper 6).

6. Smarter Templates

If you use code snippets in Visual Studio then you owe it to yourself to look at the templates in ReSharper. You can create really smart templates that include things like namespaces, filename, and much more. This feature has save my fingers countless hours of typing.

Conclusion

I miss ReSharper, but the advantages to using VS 2010 greatly outweigh my selfish need to be comforted by a productivity tool. Until ReSharper 5 becomes more stable I will have to wander the development wilderness alone. Lets hope that isn’t too long.

Should I Support Internet Explorer 6?

4

As a web developer, I am constantly concerned about the consistency of web sites across all browsers, that is why I have most of the major browser’s pinned to my Windows 7 taskbar. My current development path is to usually start by designing and confirming in Google Chrome followed by getting my sites to look similar in Mozilla Firefox, Microsoft Internet Explorer, and Apple Safari. But recently I looked at a site I was developing in a little tool called IE Tester, which allows a developer to view their webpage in Internet Explorer 5.5 up to Internet Explorer 8. Now I don’t assume anyone is still using version 5.5, it’s just so old; internet explorer 5.5 released in March of 1999 and worked on Windows version 3.1 to Windows 2000. Most CSS and JavaScript techniques used today probably wouldn’t even work in IE 5.5, but what about the predecessor of 5.5, Internet Explorer 6.0? I decided to look up some information on who is still using IE6. This is what I found.

browsers

W3 Schools is a website dedicated to teaching web developers about the basics of HTML, CSS, XML, JavaScript, and Server-Side Languages. Their statistics as of October 2009 states that 10.6% of all their visitors still use the IE6 browsers. The interesting thing is that 47.5% of their users visit through the Mozilla Firefox browser. I would take this statistic with a grain of salt. I realize that most of the users visiting the W3 Schools site are web developers, and over the last several years there has been a movement on the web to stop supporting IE6. Some have even gone as far as trying to block IE6 users from viewing their site. So do I believe that 10.6% of all internet users are IE6 users? No, I believe it is much higher, but I don’t believe it is more than 25%. How can I say that?

Most new PCs today are being sold with Windows Vista or Windows 7? These machines don’t have IE6 and a user would have to go through major hoops to install it. To those still running Windows XP, they probably have upgraded to IE7 or IE8 without even realizing; Windows Update probably suggested that they install IE7 and a click later it’s there. The user audience that concerns me are those business folks. Business users are usually under the reign of a tyrannical IT staff, with locked down machines. Upgrading isn’t really an option.  Digg breaks it down here.

To support or not support IE6 users? That is the question. Well I think if you are a web developer you should think about IE6 but not very long. If it looks right in all the latest browsers mentioned above then you should be happy and continue. If you can support IE6 with minimal effort then you should try to do so, but if it is going to take thousands of lines of CSS and code to make it work then you should probably use that time more wisely. For my site it was as simple as changing a couple CSS definitions and changing some PNG images to GIFs. Total effort was less than 10 minutes.

As web developers we want to deliver a consistent experience to all users, but sometimes that is an unrealistic reality. We either have to choose to support a subset of users or compromise the experience.  There is no right answer, the only approach is consider your audience and what you want to deliver to them. Hopefully this won’t be an issue 2 years from now.

Business Ideas : Development Mobile

3

A requirement for working with some businesses is that they want you to work on site with their development staffs. I personally like that, because in addition to meeting new people I get to interact, teach, and learn a few new things from other developers. The frustrating part is that they usually clients never accounted for outside developers or staff and they always happen to find the smallest, most isolated area for you to sit in. In addition to less than ideal seating arrangments, I have a certain development environment setup for increased productivity, comfort, and overall well being. So I thought how do I keep all the things I like but still give the client the comfort of being on site? Let me introduce the Aqua Bird Consulting Development Mobile.

Aqua Bird Consulting Development Mobile

Aqua Bird Consulting Development Mobile

You probably have some questions that might be running through your head. Let me address some of them.

Why wouldn’t you just get a laptop that you could take to client sites?

That would only address my development environment as far as hardware and software. A development environment consists of a lot more than that. Whiteboards are integral, lighting, office supplies, and furniture.

What about things like internet, phones, and television, and the thing that drives them all electricity?

Anybody these days can afford wireless broadband, Scott Hanselman had a review of one provider and got some pretty decent speeds. Phones…*cough*… everyone has a cellphone right? I could approach television in two ways, I could go through the internet or get a satellite dish. Electricity will be provided by several batteries daisy chained together. If it works to power million watt competition stereo systems, I’m sure I could power some over the counter electronics.

What happens when nature calls?

I’d hope my clients would be nice enough to let me use their facilities; but if they choose not to then I could drive to the closest gas station. This is a vehicle we are talking about.

Won’t you get claustrophobic sitting in a dark truck compartment?

Well I am considering placing windows and sunroof, this would make the compartment feel more open and keep the smell out, especially when dealing with smelly code.

What about multiple developers?

This is a concern, but I find most projects really only need about three to four developers, which a group of developers would easily fit into. They would just have to cut back on the hot pockets and red bull.

I’m still batting this idea around in my head, it might seem crazy at first. but the more I think about it the more sense it makes. Not saying it will happen any time soon, but many successful businesses have moved into the back of trucks and have never looked back. Let me know what you think and if you have any other ideas or questions about the development mobile.

ASP.NET MVC Clean HTML

10

I love ASP.NET MVC and I feel it is the future of ASP.NET Web Development, but what I don’t like is trying to get your pages to look nice and I’m not talking about visually for the end user, that actually is very easy and enjoyable. If you are like me, then you probably spend hours looking at the source of web pages. I consider myself a source snob, always wanting to see properly indented tags and elements. Below you’ll see what I’m talking about, a nightmare of bad HTML output. ASP.NET MVC doesn’t modify your HTML, which is great for web developers but it can also frustrate the same people if they suffer from being source snobs. So how do we address this issue without spending hours indenting views and thinking of nesting scenarios. There are two approaches we could take.

        <div id="main">

            <h2>About</h2>
                    <div>
<div>
                                    <div>
<div>
            <div>
<p>
    Put content here.
</p>
            </div>
</div>
                                </div>
                </div>
</div>

HttpModule

This was the standard way of doing it in a ASP.NET Web Form application. Before any html is spit out to the Response stream, you would modify it to meet your needs. This is partly the right approach for the MVC solution, but HttpModules are indiscriminate and will fire every time a request comes in. You can put logic in our httpmodule but what you will find is that it is very difficult to tell the difference between a ViewResult, JSonResult, or FileResult in an HttpModule.

ActionFilter

We get all the advantages of an HttpModule with the ability to discriminate, either by placing the filter only on actions that return a ViewResult or by accessing properties in the context passed to the filter. So this is the approach to go with, now let’s look at some code.

The Solution

For this solution I am using TidyNet, a great library that let’s you clean up HTML. There are a ton of features in this library but what I am concerned with is indenting, clean html, and making sure there are not stupidly placed tags (look at the above code, we don’t really need all those divs).

So let’s start by thinking about our ActionFilter. We need to access the response stream and modify the HTML right before output. We also need to take into consideration that ViewResults (output that is in html) is our only concern. Other results like JsonResult will be ignored since they aren’t HTML. We also want this to happen after the action is executed (although the approach I’ll take, it probably doesn’t matter). Beep Boop Beep, after some computing we have our action filter. Let’s look at the meat of the filter.

    public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext.Result is ViewResult)
            {
                var tidy = new Tidy
                               {
                                   Options =
                                       {
                                           DocType = DocType,
                                           DropFontTags = DropFontTags,
                                           LogicalEmphasis = LogicalEmphasis,
                                           XmlOut = XmlOut,
                                           Xhtml = Xhtml,
                                           IndentContent = IndentContent,
                                           HideEndTags = HideEndTags,
                                           MakeClean = MakeClean,
                                           TidyMark = TidyMark,
                                       }
                               };

                filterContext.RequestContext.HttpContext.Response.Filter =
                    new HtmlTidyFilter(filterContext.RequestContext.HttpContext.Response.Filter, tidy);
            }
        }

For this solution, we attach a filter to the response which will run at the time the response is written. Cool right? Let’s look at the meat of the filter itself, which is stream heavy but pretty straight forward. We get the HTML, clean the HTML, and then write the HTML.

            public override void Write(byte[] buffer, int offset, int count)
            {
                var data = new byte[count];
                Buffer.BlockCopy(buffer, offset, data, 0, count);
                string html = Encoding.Default.GetString(buffer);

                using (var input = new MemoryStream())
                {
                    using (var output = new MemoryStream())
                    {
                        byte[] byteArray = Encoding.UTF8.GetBytes(html);
                        input.Write(byteArray, 0, byteArray.Length);
                        input.Position = 0;
                        _tidy.Parse(input, output, new TidyMessageCollection());

                        string result = Encoding.UTF8.GetString(output.ToArray());

                        byte[] outdata = Encoding.Default.GetBytes(result);
                        _stream.Write(outdata, 0, outdata.GetLength(0));
                    }
                }
            }

So now that we have this super sweet ActionFilter, let’s use it. I place the attribute like such.

    [TidyHtml]
    [HandleError]
    public class HomeController : Controller
    {     // Controller Actions
           ...
     }

When all is run and the response is written to the page, we have the following output.

    <div id="main">
        <h2>
          About
        </h2>
        <div>
          <p>
            Put content here.
          </p>
        </div>
        <div id="footer">
        </div>
      </div>

Awesome!!! Clean HTML that makes me feel all warm and fuzzy inside and makes the web designers smile. If you are worried about this running everytime you hit an action then I suggest you use the OutputCacheActionFilter so that your pretty HTML is cached. Download the example and feel free to modify it. I exposed certain properties for TidyNet, but you can remove or add the ones you can see using in your projects. Have fun.

Aqua Bird Clean Html ActionFilter (318 kb)

Update : There is a bug in Tidy.Net that puts a break in your textarea tags. Your textareas will still work, but it will have an indent at the beginning. This can be very annoying.

DataContract Serialization Extension Methods

0

This is a classic that I have pulled from my last blog’s archives, but I thought I would post it here because I find myself going back time and time again. It really is a great set of extension methods, especially if you need an instant object dump or you are creating a simple XML repository. These methods allow you to serialize to a string/XML and deserialize from a string to the type you specify.

public static class DataContractSerializationExtensions
    {
        #region Serialize
        public static string Serialize<T>(this T target)
        {
            return Serialize(target, null);
        }
        public static string Serialize<T>(this T target, IEnumerable<Type> knownTypes)
        {
            using (var writer = new StringWriter())
            {
                using (XmlWriter xmlWriter = new XmlTextWriter(writer))
                {
                    var ser = new DataContractSerializer(typeof(T), knownTypes);
                    ser.WriteObject(xmlWriter, target);
                    return writer.ToString();
                }
            }
        }
        #endregion
        #region Deserialize
        public static T Deserialize<T>(this string targetString)
        {
            return Deserialize<T>(targetString, null);
        }
        public static T Deserialize<T>(this string targetString, IEnumerable<Type> knownTypes)
        {
            using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(targetString)))
            {
                using (var reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas()))
                {
                    var ser = new DataContractSerializer(typeof(T), knownTypes);
                    // Deserialize the data and read it from the instance.
                    return (T)ser.ReadObject(reader);
                }
            }
        }
        #endregion
    }

Have fun serializing and deserializing.

Static Google Maps Html Helper

0

Maps are always a nice thing to have on a site, especially if you are a business that relies on customers finding you; businesses like restaurants, car repair shop, or clothing store. Google has a great map API that has found it’s way into everything from mobile applications to your local news. It really is a great product. This particular helper will dynamically generate an image of your location to be placed on your site. The final result will look like the following. Again, this example uses the static API, so there is no dragging functionality or JavaScript involved.

Final result of the GoogleMaps Html Helper

Final result of the GoogleMaps Html Helper

Before you use this html helper, I suggest you read the documentation of the Google Maps API. This will give you an understanding of what properties are available and how you can customize your map.

Using the Helper

You will need to get an API key from Google or else you won’t be able to make requests. The minimum requirements for a request are a key, center, and sensor. Below you will see the code used to generate the image seen above. Don’t forget to replace “your_key” with your actual key.

Note: if you do local development, generate a Google API key using http://localhost so that you can streamline local development.

  <%= Html.GoogleMap(new
                              {
                                  key = "your_key",
                                  zoom = 14,
                                  size = "400x400",
                                  center = "Capitol Complex East Wing, Harrisburg, PA",
                                  sensor = "false",
                                  markers = "color:blue|label:H|Capitol Complex East Wing, Harrisburg, PA"
                              }
                            )%>

Now here is the code to spit out the image tag necessary to display your new map.

    public static class GoogleExtensions
    {
        public static string GoogleMap(this HtmlHelper htmlHelper, IDictionary<string,object> mapValues, IDictionary<string,object> attributes )
        {
            var builder = new TagBuilder("img");
            var source = new StringBuilder();
            var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
            const string template = "{0}={1}&";

            source.Append("http://maps.google.com/maps/api/staticmap?");

            // Create the Url
            foreach (var key in mapValues.Keys)
                source.AppendFormat(template, key, urlHelper.Encode(mapValues[key].ToString()));

            // remove the last ampersand
            var finalSource = source.ToString().Remove(source.Length - 1, 1);

            builder.Attributes["src"] = finalSource;
            builder.MergeAttributes(attributes);

            return builder.ToString(TagRenderMode.SelfClosing);
        }

        public static string GoogleMap(this HtmlHelper htmlHelper, object values)
        {
            return GoogleMap(htmlHelper, values, null);
        }

        public static string GoogleMap(this HtmlHelper htmlHelper, object values, object attributes)
        {
            return GoogleMap(htmlHelper, values.TurnObjectIntoDictionary(), attributes.TurnObjectIntoDictionary());
        }

        public static IDictionary<string, object> TurnObjectIntoDictionary(this object data) {
           var attr = BindingFlags.Public | BindingFlags.Instance;
           var dict = new Dictionary<string, object>();

           if (data == null)
               return dict;

            foreach (var property in data.GetType().GetProperties(attr).Where(property => property.CanRead))
                dict.Add(property.Name, property.GetValue(data, null));

           return dict;
       }
    }

There you have it. Now when you want to display a quick map on your site, this helper will make it a breeze.

ASP.NET MVC: Strongly Typed MasterViewPage

9

I am a big advocate of the viewmodel and it’s application not only in ASP.NET MVC applications but also in Silverlight, WPF, and even WinForm applications. I always find using the technique of a viewmodel really get’s you thinking about how to structure your entire application. The issue most ASP.NET MVC developers face is the following scenario. We have a site that has recurring functionality on each page; for example, we have a twitter roll which displays all our latest twitters. We would like this to appear on each page, but we don’t want to repeat ourselves in code (usually by copying and pasting code, blech!). So how do we accomplish our goal? An ASP.NET article suggests that you have a base master controller with recurring functionality. I agree with this approach, but I don’t like stuffing objects into ViewData. “Khalid, what is it about ViewData that you are so against?” Let me explain.

ViewData is a string based dictionary, which is dangerous on two levels. From a development standpoint, a dictionary can easily become a dumping ground for data. Before you know it, you have every aspect of your application dependent on values in ViewData. This inherently is bad because to retrieve a value, you need to know the key. This can slow down development for large teams or teams with less than ideal communication. Secondly, accessing a dictionary in the view can lead to really dirty views. I’m sure there are more arguments against and even for ViewData, but as a rule of thumb I try and avoid using this grab bag approach.

Solution

As I mentioned about the referenced ASP.NET article, I agree with the idea of a master controller. It makes sense that recurring functionality would be inherited into new controllers. To put this solution together, let us think about what specifically we need to reach our goal.

  1. We need a base controller with repeating functionality
  2. We need an inheriting controller
  3. We need a viewmodel for the MasterPage
  4. We need a viewmodel for the ViewPage
  5. The MasterPage viewmodel doesn’t need to know about the ViewPage viewmodel

Stating and believing these assumptions gives us a clear path to go down to accomplish our goal of a strongly typed MasterPage/

Addressing Assumptions 1 through 5

We are going to create a base controller that passes a master viewmodel up to the view. In addition to passing the master viewmodel, this base controller has to pass the view’s viewmodel. So we have two models that need to be merged or passed as a pair up to the view. My approach was to create two wrapper classes that will encapsulate the developers viewmodels. I felt this approach would let me reuse this functionality in future projects.

    public class ViewModelForMasterWrapper<TMasterModel>
    {
        public ViewModelForMasterWrapper(TMasterModel masterModel)
        {
            Master = masterModel;
        }

        /// <summary>
        /// Gets or sets the master model.
        /// </summary>
        /// <value>The master model.</value>
        public TMasterModel Master { get; set; }
    }

    public class ViewModelForViewWrapper<TMasterModel, TViewModel>
        : ViewModelForMasterWrapper<TMasterModel>
    {
        public ViewModelForViewWrapper(TMasterModel masterModel, TViewModel viewModel)
            :base(masterModel)
        {
            View = viewModel;
        }

        /// <summary>
        /// Gets or sets the view model.
        /// </summary>
        /// <value>The view model.</value>
        public TViewModel View { get; set; }
    }

You’ll see that the wrapper for the View inherits from the Master wrapper. This is necessary as you’ll see later. Now we need to populate these wrappers with the viewmodels that our application will need. I created a base master controller called BaseMasterController (really creative). The controller will create the ViewModelForViewWrapper and populate the View property and the Master property on the wrapper instance. You’ll see this class below.

   public abstract class BaseMasterController<TMasterViewModel>: Controller
    {
        /// <summary>
        /// Views this instance.
        /// </summary>
        /// <returns></returns>
        protected virtual new ActionResult View()
        {
            return View(ViewData.Model);
        }

        /// <summary>
        /// Views the specified model.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        protected virtual new ActionResult View(object model)
        {
            var masterModel = GetMasterViewModel();
            object wrapper = CreateModel(model, masterModel);

            return base.View(wrapper);
        }

        /// <summary>
        /// Gets the master view model.
        /// override this in your master controller.
        /// </summary>
        /// <returns></returns>
        protected virtual TMasterViewModel GetMasterViewModel()
        {
            return default(TMasterViewModel);
        }

        /// <summary>
        /// Creates the model.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="masterModel">The master model.</param>
        /// <returns></returns>
        private static object CreateModel(object model, TMasterViewModel masterModel)
        {
            var modelType = typeof (object);

            if (model != null)
                modelType = model.GetType();

            var types = new[] { typeof(TMasterViewModel), modelType };
            Type generic = typeof (ViewModelForViewWrapper<,>).MakeGenericType(types);

            return Activator.CreateInstance(generic, masterModel, model);
        }
    }

This is an abstract base class. The functionality here is generic so it can be reused in multiple different projects. We now have the majority of our solution, but we need to put it together. To finish this solution we need to create business functionality. We’ll need our own master controller, our own controller, our own master viewmodel, and our own viewmodel. Here are our classes.

    public class HomeIndexViewModel
    {
        public string MessageFromHome { get; set; }
    }

    public class MasterViewModel
    {
        public string MessageFromMaster { get; set; }
    }

    public class MyMasterController : BaseMasterController<MasterViewModel>
    {
        protected override MasterViewModel GetMasterViewModel()
        {
            return new MasterViewModel {MessageFromMaster = "Hello from the master controller."};
        }
    }

    [HandleError]
    public class HomeController : MyMasterController
    {
        public ActionResult Index()
        {
            var model = new HomeIndexViewModel {MessageFromHome = "Hello from the Home controller's Index."};
            return View(model);
        }
    }

After reusing the classes from above, you’ll see that the implementing the actual business functionality is trivial. No more than ten lines (granted this is a simple example). Now, before we can use these we have to strongly type our MasterPage and Views. Let’s take a look.

Typing Our Views

Here you will see why the view wrapper inherits from the master view wrapper. The declarations for the MasterPage and the View will look like the following.

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage<ViewModelForMasterWrapper<MasterViewModel>>" %>
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ViewModelForViewWrapper<MasterViewModel,HomeIndexViewModel>>" %>

If the ViewModelForViewWrapper class was not an instance of the ViewModelForMasterWrapper class we would get runtime errors when the viewmodel is passed to the view. Now all we have to do is use the models in both our MasterPage and View.

Our MasterPage looks like the following.

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage<ViewModelForMasterWrapper<MasterViewModel>>" %>
<%@ Import Namespace="AquaBird.StrongTypeMasterPage.Models" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
    <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div class="page">
        <div id="header">
            <div id="title">
                <h1>Strongly Typed Master Page View</h1>
            </div>
        <div id="main">
            <p id="master"><%=Model.Master.MessageFromMaster %></p>
            <asp:ContentPlaceHolder ID="MainContent" runat="server" />
            <div id="footer">
            </div>
        </div>
    </div>
</body>
</html>

And our View.

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ViewModelForViewWrapper<MasterViewModel,HomeIndexViewModel>>" %>
<%@ Import Namespace="AquaBird.StrongTypeMasterPage.Models" %>

<asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>

<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
    <p id="view">
        <%= Model.View.MessageFromHome %>
    </p>
</asp:Content>

After running the solution, my final output looks like this.

Final Result of Strongly Typed Solution

Final Result of Strongly Typed Solution

Conclusion

This solution is only one way of strongly typing your master pages and it surely works well for me. This solution doesn’t fully address the issue of widgetized pages. Complexly composed pages take a lot of time and effort design and are unique to each project. If this solution meets your needs the that is great, but always evaluate solutions to make sure they work for you. Download the solution and see how it will work in your project. Hope this helps you in your ASP.NET MVC project.

Strongly Type MasterPage (271 kb)

That Pesky Active Page for ASP.NET MVC

3

When working with HTML and CSS there are some visual queues that you can add to enhance the user experience. One of these tricks is to highlight the menu button in your navigation. Most web applications do it, but how do you accomplish this in your current ASP.NET MVC application? First let’s look at what we are trying to do. Below you will see the header to the Aqua Bird Consulting site. You’ll notice that one of the buttons is different than the others; the button that relates to the page we are on is different.

Header to Aqua Bird Consulting site. Notice the "Home" button is highlighted.

Header to Aqua Bird Consulting site. Notice the "Home" button is highlighted.

If we look at the source of the page we’ll see that the home button has an id of “active”. Obviously you could accomplish the same thing by putting a class on the HTML element, but that’s another discussion. So how do you get the correct button to be active as we move around the site? There are two ways, I’ll first talk about the BAD way to do it.

 <ul>
    <li id="active">
        <a href="/"><span>Home</span></a>
    </li>
    <li>
        <a href="/About"><span>Company</span></a>
    </li>
    <li>
        <a href="/Services"><span>Services</span></a>
    </li>
    <li>
        <a href="/Portfolio"><span>Portfolio</span></a>
    </li>
    <li>
        <a href="/Products"><span>Products</span></a>
    </li>
    <li>
        <a href="/Contact"><span>Contact</span></a>
    </li>
  </ul>

The Bad

You could always place a value into ViewData, TempData, or even on your view model. This is bad because, now we are pulling visual elements down into our controller. This is a big no-no, and we would be violating the will of the MVC gods. Having the “Home” button highlighted doesn’t change the state of our underlying application (by underlying, I mean business logic). So don’t do this; it will definitely work but you’ll be in a world of pain if you decide to redesign your site or refactor.

The Good

The great thing about ASP.NET MVC and .NET 3.5 is the extensibility of it all. Everything is right there for you to access. So knowing that little fact about the extensibility of the ASP.NET MVC framework, you have to figure there is a way to know what Controller, Action, or even View we are on. For the scenario pertaining to the Aqua Bird Consulting site, we needed to link buttons to Controllers and Actions. Know let’s look at how we get the Controller and Action.

// helper is and HtmlHelper
var currentController =  helper.ViewContext.RouteData.Values["controller"].ToString();
var currentAction = helper.ViewContext.RouteData.Values["action"].ToString();

Cool! Nothing to it. Now all we need to do is check it on the view. I created an extension method, where you pass in a controller name, or a controller name and action pair. In addition to those parameters you pass in your designated output. I also have one where you can pass the controller name only, possibly for multipurpose controllers or sections.

public static string IsActive(this HtmlHelper helper, string controllerName, string output)
{
   var currentController = helper.ViewContext.RouteData.Values["controller"].ToString();
   return (currentController == controllerName) ? output : string.Empty;
}

public static string IsActive(this HtmlHelper helper, string action, string controllerName, string output)
{
    var currentController =  helper.ViewContext.RouteData.Values["controller"].ToString();
    var currentAction = helper.ViewContext.RouteData.Values["action"].ToString();

    return (currentController == controllerName && action == currentAction) ? output : string.Empty;
}

And here is what the view code looks like. Notice that I declare my output as a constant string in the view. I chose to do this in case I chose to change my html. I also didn’t want html to sneak into my helpers and thought this was a good alternative to that.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%@ Import Namespace="AquaBird.MainSite.Infrastructure.Extensions"%>
<%const string output = " id=\"active\""; %>
  <ul>
    <li<%=Html.IsActive("Index", "Home", output)%>>
        <a href="<%=Url.Action("Index", "Home") %>"><span><Home</span></a>
    </li>
    <li<%=Html.IsActive("About", "Home", output) %>>
        <a href="<%=Url.Action("About", "Home") %>"><span>Company</span></a>
    </li>
    <li<%=Html.IsActive("Services", output) %>>
        <a href="<%=Url.Action("Index","Services") %>"><span>Services</span></a>
    </li>
    <li<%=Html.IsActive("Portfolio", output) %>>
        <a href="<%=Url.Action("Index", "Portfolio") %>"><span>Portfolio</a>
    </li>
    <li<%=Html.IsActive("Products", output) %>>
        <a href="<%=Url.Action("Index", "Products") %>"><span>Products</a>
    </li>
    <li<%=Html.IsActive("Contact", output) %>>
        <a href="<%=Url.Action("Index", "Contact") %>"><span>Contact</a>
    </li>
  </ul>

There you have it. Now you can know whether you are on a certain controller and action from your view without breaking the rules of MVC.

P.S. Having multiple elements on the same page with the same id will make your page invalid when run through a HTML validator, keep that in mind.

Go to Top