Enums to SelectList

0

So you have an Enum and you want to get a human readable SelectList. Well here is the code to do that. The caveat here is that your enum class must be decorated with a description attribute. T in this case is your type of enumeration. Use it like Eums.ToSelectList<InterestTypes>();

public static class Enums
    {
        public static SelectList ToSelectList<T>() {
            var type = typeof (T);

            if (type.IsEnum) {
                var list = new List<object>();

                var members = type.GetMembers(BindingFlags.Static | BindingFlags.Public | BindingFlags.GetField);

                foreach (var memberInfo in members) {

                    var attribute = memberInfo.GetCustomAttributes(typeof (DescriptionAttribute), false).FirstOrDefault() as DescriptionAttribute;

                    var value = memberInfo.Name;

                    list.Add(attribute != null
                        ? new {Text = attribute.Description, Value = value}
                        : new {Text = value, Value = value});

                }
                return new SelectList(list, "Value", "Text");
            }

            throw new Exception("this method is purely for enumerations.");
        }

        public static T Parse<T>(string input)
        {
            return (T)Enum.Parse(typeof (T), input, true);
        }
    }
public enum InterestTypes : int
    {
        [Description("Attractions")] Attraction = 1,
        [Description("Events")] Event = 2,
        [Description("Restaurants")] Restaurant = 4,
        [Description("Schools")] SchoolDistrict = 5,
        [Description("Featured Developments")] FeaturedDevelopment = 6,
        [Description("Accommodations")] Accommodation = 7
    }

I also threw in a generic enum parser helper for free, have fun.

MvcFlash – Quick Messages to Users

0

At the early stages of NuGet I was worried. I was not about the idea since ruby gems is the core of Rails development, but because of the seemingly disjoint feeling of projects that were in the NuGet repository and the ones I wanted to use that were not in NuGet. Gladly the community has rallied, and now your favorite open source projects are just a click away from being in your solution. So I started looking at what I could do to contribute to this ecosystem. I sat down and looked at what I end up doing a lot and what other developers could benefit from. I also had never done a NuGet package, so this was a venture into that as well. Then it hit me, a simple flash messaging API that let’s you pass messages to your users in an ASP.NET web application. MvcFlash was born and I use it all the time now.

What it can do:

well it can flash specific kinds of messages that are helpful to your users. Below is an example of the calls you can make. Notice the simple interface, you just push a string in, but you can get fancy and push a contextual object in for that particular message. The cool thing about this as well is that you can pass anonymous objects up to the view and it will be handled correctly.

Flash.Notice("Hey, what's up?")
Flash.Error("oh no!");
Flash.Warning("sucks");
Flash.Success("WooHoo!");
Flash.Push(new {CrazyProperty = "I'm a mad man!"});

When you are ready to flash this message in your view, you just need to call.

@Html.Flash()

Simple enough, but you can get crazy with this if you need to divide your messages up into different sections.

// In The Razor View
// Simple Flash
@Html.Flash()	// Flash everything, default template: "Flash"
@Html.Flash("MyOwnTemplate") // Flash evertying, custom template
@Html.Flash((ctx) => Html.Partial("Flash", ctx)) // Flash everything, lambda
// Flash Only
@Html.FlashOnly("success") // pass in the type
@Html.FlashOnly(new [] {"success", "error"}) // pass in many types
@Html.FlashOnly(x => x.Type == "success" || x.Type == "error") // pass in a lambda
// Flash Select
@Html.FlashSelect("success") // pass in the type, default template: "Flash"
@Html.FlashSelect(x => x.Type == "success") // pass in a lambda
@Html.FlashSelect("success", "template") // pass in the type filter, and the template name
@Html.FlashSelect(x => x.Type == "success", (ctx) => Html.Partial("Flash", ctx) ) // pass in a lambda

This is very flexible and you can do very cool things with it.

What it looks like:

MvcFlash comes with a default css file and images that give you amazing looking flash messages right out of the box. If you think they look gross, then you have the ability to style them anyway you want cause MvcFlash depends on a partial view and not embeded HTML code. You have full control over the output.

What to Expect:

At it’s core MvcFlash uses Session, so these messages are resilient when it comes to redirects. They will stick around as long as you haven’t Flashed them yet. In addition, you can replace your session provider with something like the AppFabric and get flash messaging across servers (I haven’t tried this yet). My goal was to make a flexible but instantly useful API here, so you can start using it as soon as you add this package to your solution. No time to setup, or do config mashing.

Conclusion:

Download this and give it a try, you might like it. If you do like it, rate it on NuGet. If you find a bug, please file it on GitHub.

Better Mapping with ValueInjecter

2

I recently received an email from a Simon Gorski asking where the AutoMapper code went, and sad to say I deleted it from GitHub. Why did I do that, you may ask? Well after many moons of using AutoMapper I have moved on to better frameworks that can do this far easier for me. I didn’t want anyone using that code because it would be painful for them (it was for your own good, I promise). Currently I use ValueInjecter which is a convention based mapping framework and helps make mapping a negligible part of my work day. Oh the early days of my career, where I thought mapping was all there really was to do in programming. I’ve wised up and now I’m going to show you how you can spend almost no time doing your own mappings.

The code to this sample can be found on GitHub at https://github.com/khalidabuhakmeh/ValueInjecter-Sample

My sample is pure POCO, but I currently use the code first approach with Entity Framework in real world projects and this would also work with most ORMs. My sample is also written in an ASP.NET MVC application, so I’ll be making mention of controllers and actions, but this would work easily as nicely in any .NET application.

Let’s start with the final look and feel of your controller, how will this feel when you are developing with it?

      Person Current {
            get { return Session["Person"] as Person; }
            set { Session["Person"] = value; }
        }

        [HttpGet]
        public ActionResult Index() {
            var model = Current.ToViewModel<PersonViewModel>();
            return View(model);
        }

        [HttpPost]
        public ActionResult Index(PersonViewModel model) {
            Current = model.ToDomain(Current).Audit();
            return RedirectToAction("Index");
        }

The mapping code is one line in both my actions: From a domain model (EF, Linq2SQL, POCO) to a view model, from a viewmodel back to a domain model. Now if you are familiar with what happens originally with AutoMapper then you are dreading seeing the mapping classes that make this happen. Fear not, I’ll show you this in a second but you will see that there really isn’t much to it.

public static class Extensions
    {
        public static T ToDomain(this object source, T domain = default(T))
            where T: class, new()
        {
            if (domain == null)
                domain = new T();

            if (source == null)
                return domain;

              domain.InjectFrom(source)
                .InjectFrom<IgnoreAudit>(source)
                .InjectFrom<FlatLoopValueInjection>(source)
                .InjectFrom<UnflatLoopValueInjection>(source);

            return domain;
        }

        public static T ToViewModel(this object source, T viewmodel = default(T))
            where T : class, new()
        {
            if (viewmodel == null)
                viewmodel = new T();

            if (source == null)
                return viewmodel;

           viewmodel.InjectFrom(source)
                .InjectFrom<FlatLoopValueInjection>(source)
                .InjectFrom<UnflatLoopValueInjection>(source)
                .InjectFrom<NullablesToNormal>(source)
                .InjectFrom<NormalToNullables>(source)
                .InjectFrom<IntToEnum>(source)
                .InjectFrom<EnumToInt>(source);

            return viewmodel;
        }

        public static T Audit( this IAudit&lt;T&gt; target, string user = "system")
        {
            if (!target.CreatedAt.HasValue) {
                target.CreatedAt = DateTime.UtcNow;
                target.CreatedBy = user;
            }

            target.UpdatedAt = DateTime.UtcNow;
            target.UpdatedBy = user;

            return (T) target;
        }
    }

I know, how boring. That’s it?!? Yes it is, this is all the code you will need to map from complex objects to your view models. Never again will you have to do trivial mapping (unless you like that sort of thing). I do also want to show you one more thing about the Audit method.

When you say Audit() on your objects you want to make sure that it doesn’t overwrite the previous values, even if there are values coming from somewhere else. These are read only values and the mapping should respect that. So I wrote a specific convention to make sure that these properties retain their original value regardless of what happens.

 public class IgnoreAudit : ConventionInjection
    {
        private static readonly string[] AuditNames = typeof (IAudit).GetProperties().Select(p => p.Name).ToArray();

        protected override bool Match(ConventionInfo c) {
            var result = AuditNames.Contains(c.TargetProp.Name);
            return result;
        }

        protected override object SetValue(ConventionInfo c) {
            // don't override these values
            return c.TargetProp.Value;
        }
    }

So it’s that easy to make sure those original values are respected.

My revelation when it comes to mapping is that I follow a lot of conventions and by doing so I save myself a ton of time coding. You can use this same technique to cut a lot of noise out of your own code base and make your intentions clearer. So here you go Simon (and anybody else). Hope this helps out. Please feel free to ask any questions.

The code to this sample can be found on GitHub at https://github.com/khalidabuhakmeh/ValueInjecter-Sample

Asp.Net MVC ViewModel with AutoMapper

7

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.

JavaScript Views for Easier Ajax (with JQuery)

2

I tweeted Phil Haack a while ago asking for a new feature in Asp.Net MVC 3. That feature was JavaScript views. What the heck is a JavaScript View? Well first, let’s define what the problem is and then you will see how JavaScript views can be very helpful. Let’s look at how we make an ajax request in JQuery


$.ajax({
  url: "test.html",
  cache: false,
  success: function(html){
    $("#results").append(html);
  }
});

Do you see a problem? You might not, because this is a valid statement. The problem is with the url property. It is hard coded to be “test.html” which might be ok for simple applications, but this can be problematic as your application gets larger.

Asp.Net 4 (or 3.5) to the Rescue

If you’ve been keeping up with Asp.Net then you know there is something new called routing. It allows you to define friendly urls. It is integral to Asp.Net MVC. From this point on, I will assume you know about Asp.Net MVC and routing. I have a complex site that has actions, several of which are purely for Ajax. The issue is that my routing scheme is still very experimental and I am still deciding on how to get the prettiest urls I can. What is very solid is the functionality each of these actions perform. So what is the challenge.

How do I dynamically inject urls into JavaScript by utilizing the Routes I have already defined?

Luckily the solution is very straightforward and easy to implement. Let’s look at how your JavaScript file might look like.

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

$(document).ready(function() {
  $(".button").click(function() {
        $.ajax({
            type: "POST",
            url: "<%= Url.Action("Ajax","Home") %>",
            success: function(response){
            $(".result").html(response.message);
            }
        });
  });
});

Sweet right! Well it isn’t that easy. You have to set somethings up in your MVC project before this works.

Step 1 – Create a Controller

Create a controller specifically for handling dynamic JavaScript views.


public class JsController : Controller    {

public ViewResult Index(string file)        {

return View(file);

}

}

Step 1 is complete. We need a controller so that a RequestContext is passed to our JavaScriptView, without this our views will bomb. Let’s move on to Step 2.

Step 2 – Specify the Route


routes.MapRoute(

"JavascriptViews",

"js/{file}.js",

new { controller = "Js", action = "Index", file = UrlParameter.Optional });

We need this route, so that MVC handles requests and points them to our controller.

Step 3 – Create Your JavaScript View and Link it

 

Add a new view under a “Js” folder under the “Views” folder. That’s it! All you need now. You can start utilizing the tools inside of Asp.Net MVC to start generating routes. Technically, you could do a lot more than just generate routes, but I wouldn’t go crazy with using C# to generate your JavaScript files.


<script src="js/master.js" type="text/javascript"> </script>

Conclusion

This is a great way to manage the Urls in your JavaScript files without the concern of worrying about modifying all your JavaScript files just because you want a different route. Download my sample and see if you like it or you think I’ve gone completely insane.

JavascriptViewExample

Using the 960 Grid System for Layout

2

So I’ve been using the 960 grid system for over 6 months now and I have learned a thing or two that could be helpful to those looking at using it as well. If you don’t already know, 960.gs is a css framework to help you quickly enable layouts and help ease the pain of cross browser compatibility. I will start by laying out the pros and the cons of the 960 and then show you how to overcome possible gotchas.

The Pros

This is what you want to hear right, how is 960.gs going to make your layout easier to manage and create. Well let’s start then.

  • Complex layouts relatively fast.
  • Consistent layout (IE, Firefox, Chrome, …)
  • Reusable and Flexible
  • Easy to learn

The Cons

Ok so some of the down sides of using 960.gs, cause there are some obvious ones.

  • More stylesheets ( 960.gs, reset.css, text.css and then yours)
  • Respect it or it will bite back
  • Divitus (lots of div tags based on your layout)
  • Everything you need to do isn’t a grid
  • not semantic (grid_12 is not expressive)
  • multiple css classes on one element

Overview

by default the 960.gs is split into either a 12 column grid or a 16 column grid. I will focus on the 12 column grid. Each column in a 12 column grid is 60px wide with a margin of 10px on each side. You can see that below the max content area you can have is 940px, while the container expands to 960px due to the 10px margin on each side. You can also see that the margin between two columns is 20px, because each column has a 10px when two columns margins combine they make 20px. And finally, a div tag can span multiple columns and it’s length is made up of all the columns it spans and 10px of margin on each side.

ex. a column that spans 11 columns is 880px. column: 60px + 10px + 10px.  11 x 80px = 880px total : 880px with outside margins and 860px without outside margin (content area).

Ok that was a lot of math, but you only need to know how to count up to 12 or 16 to use this system. No need to do this math because it is done for you automatically. The point of the math is to show you that the box model is important to understand. Margin is outside of your div tag, while everything else is inside.

image

Example – The Basics

So you are curious about the above example, how what does the HTML look like? It looks like this.

<div class="container_12">
	<h2>
		12 Column Grid
	</h2>
	<div class="grid_12">
		<p>
			940
		</p>
	</div>
	<!-- end .grid_12 -->
	<div class="clear"></div>
	<div class="grid_1">
		<p>
			60
		</p>
	</div>
	<!-- end .grid_1 -->
	<div class="grid_11">
		<p>
			860
		</p>
	</div>
	<!-- end .grid_11 -->
</div>

Simple right, you see that we use a div with a class of container_12. This is used to help center your page and give a place to start laying out your page. The next thing you will see is grid_12. That is telling that div to span the whole way across, and it is then followed by grid_1, and grid_11. You can guess that we are specifying that the first div is a size of one column, while the next is 11 columns. The div with a class of clear forces the grids to the next line, but I have found if your rows always add up to 12 you can forgo the clearing, since floating will force elements to the next line anyways, that is up to you.

Gotchas

The first and major gotcha that people run into is they attempt to overly style their div tag that already has a grid class. This is a mistake and can lead to huge headaches. Let’s look at why you shouldn’t. I will show you what css rules are ok to use and which aren’t.

Border

The first no-no is border. You shouldn’t use border on your grid divs because it adds size to your layout.

ex. You have a grid div that spans 5 columns. 5 x 80px = 400px. So you want to add a border of 1px solid black (always bet on black). What does that do?

That changes the math 5 x 80px + 2px (border-left and border-right) = 402px. now 2px might not seem like a lot, but it can force whole divs to the next line, throwing off your layout completely.

To fix this problem you should put another div inside the grid div and then style that. What you end up with is a container –> content relationship.

Margin and Padding

So you want to move a grid just a little bit over huh? DON’T. The same problem happens that occurs with Border. You force the columns to stretch pass what they were designed to do. Think of yourself trying to wear pants that are two sizes too small, it just isn’t pretty.

The solution again is to use a container-> content relationship. Where you have another div inside that handles margin and padding.

Width

You might be seeing a theme here, width is the enemy of the grid system, especially explicit widths. If you have an element that is 200px in a column that is only 60px, then you’ll have problems.

The solution is to be mindful of your parent div. If you want to use width, look at using percentage. ex. width: 100% on the content div.

Things that are OK to Style:

background-color, color, background-image, position (absolute and relative).

Conclusion

The 960.gs is very powerful, but some CSS purist might not like it’s lack of semanticness (not sure if that’s a word). I see their point, but the up side is so great that I can overlook my HTML/CSS purism. Keep in mind the gotchas and you should be able to create consistent layouts in all major browsers.

Get a VS2010 Ultimate Experience for Less

3

As of writing this blog post, there are thousands of developers converging in Las Vegas for the official release of Visual Studio 2010. I’ve been using Visual Studio 2010 for the a while now and it has been a generally positive experience. While as was exploring the VS2010 site I saw this question posed. “What Edition is Right for Me?” That prompted me to look through the editions. Microsoft has planned to sell for commercial versions: Professional, Premium, Ultimate, and Test Professional. A much smaller selection that the VS2008 editions, but that is a good thing. What shocked me was the outrageous price jump from Professional to Ultimate, from $799 to $11,899; that is over $11,000 difference for one copy of Visual Studio. So this blog post is to show you how to get an Ultimate experience for less, so that you can utilize that extra money for pizza and beers for you development staff.

1.) Visual Studio Professional ($799)

you are going to need this right? So what is missing from Professional that is in Ultimate?

  • Intellitrace (Historical Debugger)
  • Static Code Analysis
  • Code Metrics
  • Profiling

image

a.) Intellitrace ( $0 no alternative )

sadly I couldn’t find something that replaced this feature. It is very cool. Look at it this way though, the fact that Microsoft moved it up to the premium edition makes me think that they feel the common developer probably doesn’t need it. I also rarely used this feature in my own development.

b.)Static Code Analysis & Code Metrics ($410)

so what is static code analysis? Wikipedia defines it as the analysis of computer software that is performed without actually executing programs built from that software. Hmm… this sounds familiar, I think I’ve done that before. Oh wait I have! NDepend is a great static analysis tool that has been around for a while now.

c.) Profiling ( $0 – $500 )

There are a ton of profilers for the .Net framework, and some of them are FREE! In this post I chose the two that a company might buy ANTS Memory Profiler and JetBrains ReSharper.

2.) Testing

So you are a testing kind of developer, that’s great but you want all the extras that ultimate offers.

  • Code Coverage
  • Test Impact Analysis
  • Coded UI Test
  • Web Performance Testing
  • Load Testing
  • etc…

a.) Code Coverage ($479)

NCover is a mature and great tool for code coverage.

b.) Web Performance Testing and Load Testing($0)

The web has been around long before VS2010, so this problem has been solved a million times. Realizing that there are a ton of tools out there to do this and I won’t list each of them. Just Google and prepare to be overwhelmed by the possibilities.

c.) Coded UI Test ($0)

Watin allows you to code tests for UI interaction of web applications, which is probably the hardest interaction to test for.

d.) Resharper ($349)

I have to mention this tool just because it is so good and it improves the unit testing experience inside of visual studio, regardless of your framework.

3.)Database Development

the dreaded database…. how do we handle this stuff?

  • Database Deployment
  • Database Change Management
  • Database Unit Testing
  • Data Generation

a.) Database Deployment ($0 – not needed)

In theory this sounds great, but the majority of companies have a company structure that forbids any developer from making database pushes; the job of pushes are usually left to a Database Administrator. They will probably want to execute SQL that they have crafted and labored over.

b.) Database Change Management ($0 – code option)

again this is probably left up to your DBA with a combination of your source control (SVN, Hg, Git, TFS). I recommend looking into a migration framework if you really want to control the versioning of a database.

c.)Database Unit Testing (Whaaaaat? $0)

this troubles me on two fronts. First off you probably shouldn’t be unit testing enough of your database to have a whole project dedicated to it. Secondly, this is what developers refer to as integration tests and you don’t need any other tools other than your  favorite unit testing package to do this. Granted, VS2010 probably has some nice UI tools to make this more pleasurable, but in my opinion tests are about results and not how pretty the UI is.

d.) Data Generation ($0)

This is a problem that isn’t that complicated to solve, and again has been solved. Check out AutoPoco which allows you to generate a ton of data easily through a fluent interface. After generation, just go ahead and pump this data into your database with your favorite ORM or DAL.

4.)Architecture and Modeling ($100)

Buy a whiteboard for modeling and get your team involved. There is nothing worse than an Ivory tower architect that pushes his architectural will on the team without discussion.

5.)Source Control ($300)

Unfuddle is a great online source control provider and in my opinion gives you a lot of things your business will use from Team Foundation Server. When I quote the $300, I am talking about for your whole company and not per developer. This is a huge cost savings. There are also a ton of other online source control providers that are similar to Unfuddle.

Tools I have to mention: TortoiseSVN, MsysGit, TortoiseHg, AnkhSVN (all free)

Conclusion and Total Price: $2637 ($2832 less than Premium and $9262 less than Ultimate)

That savings per developer is nothing to joke about. You could save over $9000 dollars but just looking around more. So what is the downside? Well you will have a hodgepodge of tools to use and many of these options might lack UI tools and possibly Visual Studio integration. Do your homework and see if the benefits of buying these tools outweigh your desire to have a all in one tool like VS2010. If you have a team of five developers, I just saved you over $45k. Your welcome.

Aqua Bird Consulting’s Competitive Edge Review

0

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.

FluentSitemap: Build Sitemaps for Asp.Net MVC

0

Building your site is only half the battle. Getting people to know it exists is the other half. If you are creating a public facing site, or even an intranet that utilizes an in-house search server then I have created a library just for you. The library is FluentSitemap. This library is designed to help you easily build sitemaps to be utilized by major search engines. The great thing about this library is that utilizes all your existing routes and controllers to build a sitemap even for the most complex Asp.Net MVC sites.

The FluentSitemap library can be found at GitHub Here.

How to use you, Let me count the ways

There are several ways you can utilize this library. The first is to specify each node manually. Let’s look at how that looks.

           // You can pass in a HttpContext from anywhere
            // in you application
            ISitemapConfigurator configurator = new SitemapConfigurator(HttpContext);

            // create sitemap node and set
            ISitemap sitemap = configurator.Create()
                .WithLocation("http://localhost.com/")
                .WithPriority(0.3)
                .WithChangeFrequency(ChangeFrequencyType.Never)
                .Set().Export();

The second is to use a controller/action pair.

        // You can pass in a HttpContext from anywhere
            // in you application
            ISitemapConfigurator configurator = new SitemapConfigurator(HttpContext);

            // Add From a controller and action
            ISitemap sitemap = configurator.Add("Home", "Index")
                .Add("Home", "About").Export();

The third is to use a route

       // You can pass in a HttpContext from anywhere
            // in you application
            ISitemapConfigurator configurator = new SitemapConfigurator(HttpContext);

            // Add From a controller and action
            ISitemap sitemap = configurator
                // Add From a Route
                .AddFromRoute("Default", new {id = "2"}).Export();

The last is to use the ISitemetadata. This is specifically there for IoC.

public class HomeControllerSitemapMetadata : ISitemapMetadata
    {
        private const string Home = "Home";

        #region ISitemapMetadata Members

        public void Create(ISitemapConfigurator sitemap)
        {
            sitemap.Add(Home, "Index")
                .Add(Home, "Scanner")
                .Add(c =&gt; c.Metadata());
        }

        #endregion
    }

    public class OtherControllerSitemapMetadata : ISitemapMetadata
    {
        private const string Other = "Other";

        #region ISitemapMetadata Members

        public void Create(ISitemapConfigurator sitemap)
        {
            sitemap.Add(Other, "Index")
                .Add(c =&gt; c.Test(1, "dude"));
        }

        #endregion
    }
            // An example, you'll probably use your favorite
            // IoC container to resolve all the metadata classes
            var metadata = new List
                               {new HomeControllerSitemapMetadata(), new OtherControllerSitemapMetadata()};

            ISitemap sitemap = new SitemapConfigurator(HttpContext).FromMetaData(metadata).Export();

There is more API sugar, so go download it and give it a try.

MVC Turbine – A Great Platform

0

I love Asp.Net MVC, that isn’t a secret. Although the framework isn’t perfect, it is a great leap in the right direction. When I start an Asp.Net MVC project there are things I always have to do just to jump into the meat of the new site. These things include replacing the ControllerFactory with a IoC enabled ControllerFactory, changing routing, and other boiler plate actions. This is where MVC Turbine comes in, and I am liking it more and more the deeper I dive into it. Javier Lozano, the creator, defines MVC Turbine as

MVC Turbine is a plugin for ASP.NET MVC that has IoC baked in and auto-wires controllers, binders, view engines, http modules, etc. that reside within your application. Thus you worry more about what your application should do, rather than how it should do it.

image

If you consider ASP.NET MVC as a stock Nissan 370z, then MVC Turbine is the Nissan 370z with the Nismo package. Ultimately the same car, but the tweaks make the ride so much more fun to drive. Everyday I find something cool in this framework, but these are my favorite features so far.

Services Registration and IoC

I love IoC, because it makes testing your applications easier and shrinks your code base over the long run. What I hate is having to wire it up every time I start a new project. With MVC Turbine, it is already handled for you. Just create classes that implement the IServiceRegistration interface. You will be passed your favorite IoC and you can do what you need to do to register your services.

Inferred Actions

If your controller actions just return a view, then you are going to love this. You can create a controller class with no actions, and MVC Turbine will look in your views folder and display that view. Check it out here.

Route Registration

When you have a large Asp.Net MVC application, then you’ll probably have a lot of routes. MVC Turbine allows a great facility for registering routes, while keeping you project clean.

I can definitely get behind MVC Turbine and I recommend you check it out.

Go to Top