Archive for June, 2011

Must Have NuGet Packages

2

I am loving NuGet, and as it matures it just becomes more of a paradigm shift. How do you program without this thing? What was development like before it? So what are NuGet packages I am usually including in my projects. Here is a list of the them below, in no particular order.

  • Depot (Common Caching)
  • Dynamic Expression API (LINQ Extensions)
  • ELMAH on XML (Error Logging)
  • FileDB (a leap in storing files)
  • SimpleMembership
  • ValueInjecter
  • WebActivator
  • RhinoETL
  • FluentMigrator
  • RestfulRouting
  • JQuery
  • FluentValidation
  • Entity Framework Code First
  • NUnit
  • Moq
  • WaTin
  • RestSharp
  • MvcFlash (yes I am bias :P )

Great respect goes out to these projects and their contributors, except MvcFlash cause I don’t want to strain my arm patting myself on the back :P .

Update: How could I forget about MvcMailer.

How to Increase Decimal Precision in Entity Framework

1

So you are saving your decimal values to the database, but you are noticing that they are being rounded. Not what you want, because you want to be as close as you can be. If you are using entity framework you just need to add this little snippet to your OnModelCreating method in your DataContext.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
           modelBuilder.Entity<Address>()
                .Property(m => m.Latitude)
                .HasPrecision(19, 5);

            modelBuilder.Entity<Address>()
                .Property(m => m.Longitude)
                .HasPrecision(19, 5);
        }

The example above makes sure that my latitude and longitude at least have a precision of 5. Make sure you database reflects this precision.

Capitalize First Letter of Every Word (C#)

5

I hate non uniform data, I really do. It’s one of those things that a client will enter into the system a thousand times incorrectly with no rhyme or reason. It is also followed by the eventual, can you fix these million records so they are correct. Ugh! What?!? Ok, so you can fix it in your database or create code at display time to fix it. I always opt for the second, since you can’t trust your users to stop doing what they have been doing. So here is code to nicely display peoples names, cities, or whatever needs to the first letter capitalized.

 public static string CapitalizeFirst(this string input)
        {
            if (string.IsNullOrEmpty(input)) {
                return input;
            }

           var words = input.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);
           var result = words.Select(w => w[0].ToString().ToUpper() + w.ToLower().Remove(0, 1)).Aggregate((s,w) => s + ' ' + w );
           return result.Trim();
        }

Not rocket science, I know but still equally helpful.

LamdaComparer – A Must Have Snippet

1

I found this blog post about LambdaComparer and it is a must have snippet if you are doing anything with LINQ. Check it out http://brendan.enrick.com/post/linq-your-collections-with-iequalitycomparer-and-lambda-expressions.aspx

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

Go to Top