Asp.Net MVC ViewModel with AutoMapper

Hello readers. It’s been a while because Aqua Bird Consulting has been doing some awesome work recently and I am finding it hard to sit down and write. But today I found some time, so you will get an experimental post about Asp.Net MVC and Automapper.

This post is targeted toward those developers who use a ViewModel to as the foundation to their views. When using the ViewModel pattern there is always the pain of mapping. Mapping is central to any ViewModel pattern. You have your domain model that maps to your ViewModel, which is representative of your view. Before you continue reading I am assuming you are familiar with the basics of Asp.Net MVC.

As of right now, Asp.Net MVC has no mapping library built in. This means you have two options: Map the objects yourself manually inside the controller action, or delegate it to a third party library like AutoMapper. I usually choose the later due to it’s ease and readability in code.

Let’s looks at the final product and I’ll explain what is happening from a high level. Below you will see two methods, one for a GET and one for a POST to show that I can map out to the view and in from a request.

    public class HomeController : MappingController
    {
        public ActionResult Index()
        {
            var person = new Person
                            {
                                Name = "Khalid Abuhakmeh",
                                Address = new Address {City = "Camp Hill", Street = "111 November Dr"}
                            };

            return ViewModel<indexviewmodel>(person);
        }

        [HttpPost]
        public ActionResult Index( [IndexViewModelMap] Person person)
        {
            return ViewModel<indexviewmodel>(person);
        }
    }

You will notice two subtle differences about the code above. First of all, at the end of each action you notice that I call ViewModel<IndexViewModel>(person) instead of View(person). Secondly, in the second action I have an attribute of IndexViewModelMap.

The ViewModel method takes your domain model and maps it to the ViewModel you specify. All you have to do is specify AutoMapper map somewhere else in your code. What is the advantage of doing this? Well for one, your controllers have reduced noise, no more mapping things right in your controller action. Secondly, you still get to work with your domain objects and not have to worry about the ViewModels except for view purposes.

The IndexViewModelMap just tells Asp.Net MVC to use a ModelBinder designed to use AutoMapper. It takes the incoming IndexViewModel and maps it to the Person model. Now you can deal with your person object directly without knowing of your ViewModel.

What if my ViewModel has more than one domain model mapped to it?

Well I’ve thought of that. Rarely does a ViewModel simply map to one object. If I couldn’t handle that then there would be no point to this post. Check this out.

   public ActionResult Complex()
        {
            var person = new Person
            {
                Name = "Khalid Abuhakmeh",
                Address = new Address { City = "Camp Hill", Street = "111 November Dr" }
            };

            var car = new Car()
                          {
                              Color = "Black",
                              Make = "Audi",
                              Model = "A4"
                          };

            return ViewModel(person,car);
        }

Now I am mapping two to infinity objects to your ViewModel. That is where the money is at, if I do say so myself. To get this working all you need is to define your AutoMapper Maps and you are ready to go. Let me show you what a Mapping class looks like.

        public static void Person_To_ComplexViewModel()
        {
            AutoMapper.Mapper.CreateMap
()
                .ForMember(target => target.Name, opt => opt.MapFrom(source => source.Name))
                .ForMember(target => target.City, opt => opt.MapFrom(source => source.Address.City))
                .ForMember(target => target.Street, opt => opt.MapFrom(source => source.Address.Street));
        }

That is easy right!

To see all of this code check it out at GitHub http://github.com/khalidabuhakmeh/AutoMapperExperiment.

Let me know what you think.

Aqua Bird Consulting’s Competitive Edge Review

CERBanner I am happy to announce, after popular demand, that we have started offering a new service: Competitive Edge Review. This service is for any business looking to have a review of their business processes, staff, or other aspects of their business. So how does it work and what do our clients get?

Our experts visit your location or remotely communicate with key business people and engage in a intensive but exciting session. These sessions include personal interviews, questionnaires, process walkthroughs, and brainstorming. The idea is to get our clients talking about their business. We make sure to get clients talking about what they like about their business and what could use improvement. All information gathered  is kept confidential; that includes the names of all people who take our questionnaires. The questionnaires are meant to extract truthful information, and we want all participants to feel that they can be honest. Once all this data is compiled we take the information and write a detailed report.

Our clients receive a document that details their current business process and where improvements can be made. This includes hard actionable data that can save some clients thousands of dollars. Other data can help reduce time spent on activities. For some clients we’ve been able to eliminate crucial activities completely by automating the task.

This is an amazing service for a business of any size because it let’s you know about what is possible.

Windows 7 Open Firewall Ports To IIS7

In the saga of trying to figure out where this phantom page is coming from I decided to host the site on my local machine and see if it was ASP.NET MVC 2 itself or my host. If you are reading this I assume you already know how to use IIS and create a web application. The issue i was having is that I needed the external service Web-Sniffer to get my site as a GoogleBot. So you will need the following to open up your site. A word of caution, this opens a port on your machine and could potentially be a security hole if left open.

What You’ll Need To Start

  1. Your Router IPN
  2. Your Internal IP Address
  3. Your External IP Address
  4. Your Web Application Port Number

Forwarding Some Ports

First log into your router using the IPN address. It is usually something like 192.168.1.1. Log in and forward the Web Application Port to Your Internal IP Address. This depends on your router so consult your manual about the specifics.

Opening Some Ports

Although your ports are now forwarded to your machine, all traffic will be blocked by the Windows Firewall. This next step will open those ports.

1.) Open up Control Panel and click System and Security

image

2.) Next Click Windows Firewall

image

3.) Next click Advanced Settings on the left.

image

4.) In the new window click Inbound Rules, Then Click “New Rule…” on the right

image

5.) Then in the new window select Port and click Next

image

6.) Proceed to type in your Web Application Port Number in the textbox

image

7.) And then just keep clicking next until you are done.

Now To See The Site

Open up your favorite web browser and type your External IP Address followed by the Web Application Port. ex. 99.99.999.99:8080. You should see your site come up. If your site doesn’t come up make sure that you are forwarding ports and that your IIS web application is running. You can also enable and disable the rules in the Windows Firewall Advanced Security panel. Good Luck.

GoogleBots and the Phantom ASP.NET MVC Page

No this is not the newest nerd science fiction film directed by James Cameron, instead this is my current problem with ASP.NET MVC 2 and it is a huge one. I was recently reading Justin Etheredge’s blog CodeThinked and his complaints about his Google page ranking. So being curious to how my main site was doing, I began using several tools to get an SEO grade for my main site. The first tool I used was WebSite Grader to give me a grade on my SEO.

image image

 

This grade was poop! But I read a little more and realized that the page Website Grader had read was not my main page. How do I know that? Well for starters, I wouldn’t be stupid enough to keep a page’s title “Index”.

image

So what is the page the GoogleBot is seeing? I decided to use Web Sniffer a tool that let’s you mimic different clients and this is what I got.

image

WHAT THE F@$*%!!!!!! Where is that coming from. The amazing thing is that a page with a title and an empty body get’s a score at all! Obviously, if you go to my site you’ll realize that this is not the main page. What is also strange is that nowhere in my current application does this view exist, well how could it?!?! So as I tried some other pages to see what I would get, and check it out.

image

Ok so I got one page getting a grade. But something strange is occurring. The crawler tried to traverse a page that doesn’t exist! On the good side it did find metadata.

image

image

So what is the culprit here? I have no clue, but I am leaning towards routing. The strange “Services/About” page is giving me a strong a hint that something is not right. But routing wouldn’t explain the phantom view that I am getting. Who wrote it? Is it from some lost civilization of MVC developers and I was lucky enough to find it? “I See You” phantom ASP.NET MVC view, now you need to go away so my real page can get indexed, UGGGGG!

lucy_and_charlie_brown

Chrome Hidden Feature – Search Other Than Google

I love using Google chrome for my daily browsing, it just loads fast and does the job I need it to do (although I love FireFox as a developer). Anyways, I love using the quick search feature they have built into the browser. If you don’t know what I’m talking about I’ll show you.

First you type in Google.com, like below.

image

Then you press the TAB key, and you get the search box.

image

Nothing new here if you are a regular chrome user, but check this out. What if you don’t like Google (I bite my tongue a little as I say this). What if you like Bing? What if you like Yahoo!? What if you want to search WordPress.com?

image

image

image

Well all you have to do is type the address and press tab. Pretty cool if you ask me. This trick only works with certain sites, so play around with a few and see if you can’t discover one that is search enabled through the Chrome awesome bar.

No longer waste time navigating to the front page of a search engine, you could use those extra seconds for something more useful.

Aqua Bird Consulting Site Up!

Well I’ve had this done for a while, but here at Aqua Bird Consulting we are going through some procedures that didn’t allow us to publish our site. Today we decided it would be a good time to do so. Go check it out. From a user stand-point, there is a lot of information about what we do here at Aqua Bird Consulting. Through the nerd’s eye view, the web site was built using Asp.Net MVC 1, JQuery and a lot of other cool stuff under the covers. I can say I’m proud of the work done on the site. If you don’t have time to head over right now, just look at some of the screenshots below.

image image

Write Your Own Haikus and Win an Xbox 360 and TV

haikuhttps://www.r2haiku.com/

Aqua Bird Consulting also has a artsy side, but we also really want that TV and Xbox 360 Elite. Here are our two Haikus, vote for them and if we win you are welcome to come play with us on our new TV and Xbox. You could also write your own Haikus. A haiku is a poem with 17 syllables and three lines. The first line has 5 syllables, the second 7 syllables, and the third 5 again. It doesn’t have to rhyme.

Haiku # 1

This Server is Zen
Processing In Harmony
Now Relax Forever

Haiku # 2

This is an easy choice
no fuss, no muss, no hassle
Get back to your life

ReSharper 5.0 Early Access Program

I found today that JetBrains has just released an early beta of ReSharper 5 so I’m giving it a shot. The one done side to the Beta is that it still doesn’t support Visual Studio 2010 (which I am itching to move to). So if you are brave and want to try it out, here is the link to the ReSharper download.

ReSharper Installer

ReSharper Installer