Sunday, April 29, 2012

Using description attribute class with enums

Enums are very useful way to make constant strongly typed replacements for magic numbers/string that are also self-documenting, the down side is they can be a little limiting, to solve this we can use class attributes and extension methods to get more out of them.

Adding a description to a Enum is fairly easy just use the System.ComponentModel.DescriptionAttribute class to add descriptions to the enum values
   1: public enum BuildingTypes
   2: {
   3:     [Description("Retail Space")]
   4:     RetailSpace=1,
   5:     [Description("Office Space")]
   6:     OfficeSpace=2,
   7:     [Description("Single Family Residence")]
   8:     SingleFamilyResidence=3,
   9:     [Description("Multi Family Residence")]
  10:     MultiFamilyResidence=4,
  11:     [Description("Warehouse")]
  12:     Warehouse =5,
  13:     [Description("Manufacturing")]
  14:     Manufacturing =6
  15: }

In order to get the descriptions from the enum we need to do a little reflection and wrap it up in an extension method
   1: public static string ToDiscription(this Enum value)
   2: {
   3:     var description = string.Empty;
   4:     FieldInfo fi = value.GetType().GetField(value.ToString());
   5:  
   6:     var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute),false);
   7:  
   8:     if (attributes != null && attributes.Length > 0)
   9:     {
  10:         description = attributes[0].Description;
  11:     }
  12:     else
  13:     {
  14:         description = value.ToString();
  15:     }
  16:     return description;
  17: }
Simple as that, for the full source see my sample code repository

Monday, March 26, 2012

Creating Custom Asp.net MVC ViewEngine

In the last post I talked about creating a custom ActionResult, the next question is, what if I want to add my a custom view engine?   As an example lets say your company’s intranet uses multiple platforms (php, java, and now asp.net mvc) and to keep the look and feel constant you use xslt to render your header and footer, a simple solution is to add a xslt View Engine to generate the markup.

First you create a view to parse and output for content
   1: public class XsltView : IView
   2: {
   3:     private readonly XslCompiledTransform _template;
   4:  
   5:     public XsltView(ControllerContext controllerContext, string viewPath)
   6:     {
   7:         _template = new XslCompiledTransform();
   8:         _template.Load(controllerContext.HttpContext.Server.MapPath(viewPath));
   9:     }
  10:  
  11:     public void Render(ViewContext viewContext, TextWriter writer)
  12:     {
  13:         var xmlDoc = viewContext.ViewData.Model as XDocument;
  14:         if(xmlDoc==null)
  15:         {
  16:             var xs = new XmlSerializer(viewContext.ViewData.Model.GetType());
  17:             xmlDoc = new XDocument();
  18:             using (var xWriter = xmlDoc.CreateWriter())
  19:             {
  20:                 xs.Serialize(xWriter, viewContext.ViewData.Model);
  21:             }
  22:         }
  23:         _template.Transform(xmlDoc.CreateReader(),null,writer);
  24:     }
  25: }
then you create a view engine by inheriting from VirtualPathProviderViewEngine and override the CreatePartialView and CreateView methods to call your view
   1: public class XsltViewEngine : VirtualPathProviderViewEngine
   2: {
   3:     protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
   4:     {
   5:         return new XsltView(controllerContext, partialPath);
   6:     }
   7:  
   8:     protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
   9:     {
  10:         return new XsltView(controllerContext, viewPath);
  11:     }
  12: }

to add the view open global.ascx.cs and modify the application start method to add the new view engine
   1: protected void Application_Start()
   2: {
   3:     AreaRegistration.RegisterAllAreas();
   4:     ViewEngines.Engines.Clear();
   5:     ViewEngines.Engines.Add(new WebFormViewEngine());
   6:     ViewEngines.Engines.Add(new RazorViewEngine());
   7:     ViewEngines.Engines.Add(new XsltViewEngine
   8:         {
   9:             ViewLocationFormats = new [] { "~/Views/{1}/{0}.xslt", "~/Views/Shared/{0}.xslt" },
  10:             PartialViewLocationFormats = new[] { "~/Views/{1}/{0}.xslt", "~/Views/Shared/{0}.xslt" }
  11:         });
  12:     RegisterGlobalFilters(GlobalFilters.Filters);
  13:     RegisterRoutes(RouteTable.Routes);
  14: }
now to use it just add you xslt file to your view folder like you would with any other view and return your serializable object to the the View you’re returning
   1: public ActionResult TransformedView()
   2: {
   3:     var model = new BasicDemoModel{Name = "Demo User"};
   4:     return View(model);
   5: }

for the full source (click here)

Saturday, March 24, 2012

Creating Custom Asp.net MVC ActionResults

One of the most powerful things in Asp.net MVC is how easy it is to extend, a really good example is ActionResults.  Basically all you have to do is inherit the ActionResult class and override the ExecuteResult method and add a constructor, with a few lines for code you can have an action return anything you want from dynamically generated pdf and xls files, to images. 

Here is an example of returning an object as xml
   1: public class XmlResult : ActionResult
   2: {
   3:     private readonly object _item;
   4:  
   5:     public XmlResult(object item)
   6:     {
   7:         _item = item;
   8:     }
   9:  
  10:     public override void ExecuteResult(ControllerContext context)
  11:     {
  12:         if (_item != null)
  13:         {
  14:             var xs = new XmlSerializer(_item.GetType());
  15:             context.HttpContext.Response.ContentType = "text/xml";
  16:             xs.Serialize(context.HttpContext.Response.Output, _item);
  17:         }
  18:     }
  19: }

basically you pass the object you want serialized into the constructor, and return it.  Inside the ExecuteResult method I do a quick null check, spin up a XmlSerializer set the response content type to “text/xml” and use the HttpContext.Response.Output to write the serialized data.

All you have to do to use it is create a new instance and return it from your action
   1: public ActionResult Index()
   2: {
   3:     var model = new BasicDemoModel();
   4:     return new XmlResult(model);
   5: }

To see the code used checkout the sample application at here.

Thursday, January 19, 2012

Automated Builds and Continuous Integration with Jenkins

The concept of an automated build is fairly basic, you simply take your existing build file (make, nant, ant, msbuild(.sln), rake) and set up a service to build it from your source control repository. 

Automating builds

Setting up automated builds provide a number of advantages:

  1. Everything your project needs to build and run is checked into source control.
  2. By scripting your builds you remove human error problems, computers are just better at running repetitive tasks
  3. Logging what was done and when it was done.

At a former employer the marketing department needed to do content updates on a fairy regular basis; So they wouldn’t have to wait for us, I set them up with svn for the content directory and created some users for content deployment.  All they had to do was update the content and commit it and then deploy it.  We where happy because we didn’t need to spend time on their deployments, and they where happy because they could push content any time they wanted to.

Continuous Integration 

This is a key part of doing Test Driven Development, making sure your tests are run when checked in.  This makes sure that all of the tests are working in the build environment, and lets everyone know when there is a problem as soon as the build runs, and lets the developer responsible to fix it as soon as possible, creating an over all better code quality. 

Using Jenkins

Jenkins is an open source Build server forked from the Hudson project, basically when Oracle bought Sun/Java some of the Hudson team decided to was time to go their own way.  Jenkins Benefits from a log history of community support from it’s Hudson days allowing it to be a very mature and extendable system.  Having said that, it not as easy to use as some other build servers (see Continues Integration with TeamCity) but what it lacks in ease of use, it makes up for in versatility and flexibility.

User Management

Like most things in Jenkins User management is very flexible by default supporting LDAP, it’s own internal user DB, delegate to servlet container, and has a huge list of user management plug-ins for everything from Active Directory to GitHub OAuth.  Once the user is added you also have a fairly flexible authorization set up  from allowing anyone to do anything to completely locking it down. 

My biggest complaint here is that by default everything is wide open and the responsibility of locking everything down is placed on the administrator.

Build Jobs

By default Jenkins supports Maven2/3, completely rolling your own multi part build, and Monitoring an external job but  with a large selection of plug-ins supporting everything from rake to powershell to Fitness, to an Android Emulator.

Rolling your own multi part build is fairly strait forward if a little involved with a lot of the basic options you would expect like wither to keep old builds, how long do you want to keep them, how many do you keep, Quiet period, retry count, etc.

With it’s plug-ins your source control provider options are just about anything you can think of including:SVN, CSV, Git, ClearCase, etc. The same for build triggers by default it supports build after other projects, build periodically(nightly builds for example), pull scm, and remote triggering(call a url with an auth token to start a build).

When your done with your build you have built in support to ftp or ssh your build results with plug-ins to do everything from upload to Amazon S3 to the Appaloose Store for mobile apps.

The down side to all of this flexibility is you are forced to do a lot for the configuration your self, unlike TeamCity, if you want your code test results published you have to configure it yourself, if you want your code coverage results, you have to configure it to use something like PartCover yourself.

Reporting

Just as important as automating your builds is knowing what is going on with them, when are they running, did it fail, what failed, etc.  Jenkins has fairly nice tools built in to show you what is going on.  With a build history trend report, rss feeds, Email notification, and plug-ins to support everything from dashboard views to creating a Wall friendly display of all build jobs.

Conclusion

While not as nice to set up and manage as some other build servers, Jenkins is incredibly powerful with a lot of flexibly, and to be honest it’s really hard to complain about an enterprise level build server for free.  I would make the comparison between running Linux VS. Windows servers, Windows may be more polished but it’s not as flexible.

Sunday, January 8, 2012

Finally decided to do a dev tools list

One of the most important parts of being a craftsman is your selection of tools, it doesn’t matter if you are a carpenter, a mason, cabinet maker, or even a software developer, your tools allow you to get the work done.   What tools you use really depends on your style and technique and may very greatly depending on the person.  This is a simple list of IDEs, editors, libraries, etc. that I like and work for me, some are pay for, most are not.  This isn't a complete list of the tools I use but it's a good solid overview of what I use on a day to day basis, take a look and see what you like, or don’t.

IDEs

  • Visual Studio 2010 – The default editor for doing .NET development, it has it’s share of problems but for the most part it a very sold IDE.
  • MonoDevelop – This is where .NET started for me 8 years ago, not a lot of frills, but for a fully functional cross platform IDE for .NET the price is right at free, unless you want to do Android or IOS, then you need to buy monoDroid or monoTouch.
  • NetBeans – My go to java and PHP IDE, with good intellisense and built in refactoring tools. 

Visual Studio Plugins

  • Resharper – The most valuable IDE plugin I have ever used, providing nUnit support, refactoring, add reference, and the list keeps going.  I honestly have a hard time using Visual Studio with out it.
  • DotCover – An important part of test driven development is code coverage, and DotCover is my coverage tool of choice.  It integrates with Resharper’s test runner to provide on request code coverage in the IDE.

Source Control

  • AnkhSVN – Provides SVN support for Visual Studio, so far this is the best free SVN plugin I have found for Visual Studio
  • Visual SVN server – A simple and easy SVN server that just works, it may not have a lot of bells and whistles but it’s easy to install and manage users.

Text Editors

  • Notepad++ – One of the first things I do on any new windows system is install Notepad++, it integrates with Windows explorer making it simple to edit any text file with out having to deal with what the default app is for the ext. with a huge list of plugins for everything from XML to powershell it is the Swiss Army Knife of text editors.

SQL Tools

  • Toad For SQL Server – This is a new item on my tools list, I just started using it this week, but I really like it.  The community version has some really nice intellisense, and the way the UI works is just clean.  I’m really interested in seeing a head to head comparison between Redgate’s SQL Tool belt and Toad Development Suite for SqlServer, the features look about the same, but at around $1,300 vs. $2,000 toad is a lot cheaper.
  • FluentMigriator – A .NET version of the Ruby Migrations tool.  With a fairly simple syntax and helpers it makes scripting DB changes easy, to read more check out this blog post I did a little while ago, Using Fluentmigrator with nant.

Unit Testing

  • NUnit – The work horse of the .NET unit testing world.  It’s a solid testing framework with some of the best tool support out there, with the exception if Visual Studio, but Resharper fixes that.
  • Moq – The Simplest mocking framework for .NET.  With a clean fluent syntax that provides ease of use and versatility.   

Build And CI Server

  • Team City – By far the easiest to get set up and start running with.  With built in support for most of the tools I use and has DotCover built in, it provides a solid solution out of the box with a very polished UX. 
  • Jenkins – A fork of the Hudson project, Jenkins is a solid if less then polished build and CI server solution, but what it lacks in polish it makes up in versatility and flexibility, with a huge selection of plugins for integrating into just about development environment and deploying to just about any other system out there.