Double Input problem with CheckBoxFor in MVC while serializing

if you have tried to serialize a CheckBoxFor from MVC to JSON, you will notice that you get two inputs, and it can mess up the data you are sending

It's no surprise that JavaScript is not sure how MVC works so when you try data.serialize() on MVC form data, you get odd results. Here is a simple workaround for when you need something to be serialized. I modified the GetPropertyName method from this post on StackOverflow.
public static string GetPropertyName<TModel, TValue>
    (Expression> exp)
    MemberExpression body = exp.Body as MemberExpression;
    if (body == null)
        UnaryExpression ubody = (UnaryExpression)exp.Body;
        body = ubody.Operand as MemberExpression;
    return body.Member.Name;

public static MvcHtmlString CheckBoxForJson<
    TModel, TValue>(this HtmlHelper<TModel> helper, 
    Expression<Func<TModel, TValue>> expression)
    string propName = GetPropertyName(expression);
    string html = "<input type=\"checkbox\" name=\"" 
        + propName + "\" id=\"" 
        + propName + "\" value=\"true\" />";
    return MvcHtmlString.Create(html);

And use it like this:
@Html.CheckBoxForJson(x => x.SomeBool)

The reason for the 'true' is because otherwise it will always pass as false since 'on' is not a bool value (html default).

Naspinski.Utilities now on NuGet

Utilities class for .Net including Dynamic property getters/setters, automatic IQueryable searching, LinqToSql shortcuts, FileStream shortcuts, String extensions and more

This is a utility class that was developed with the help of others that I use in almost all of my .Net projects. It is available via NuGet as well as on CodePlex. It includes:


Change a property value at run time without knowing the property ahead of time:
someObject.SetPropertyValue("Name", "new value")
// is the same as 
someObject.Name = "new value";
// no need to know which property to code in

More Information


Search all/any properties of an IQueryable with one single search.

The 'quick search' is a great tool. Google has shown us that searching with one single, universal search field is the way that people prefer to search. Anyone who has worked with Linq for any amount of time knows this is possible, but it requires a lot of hard-coding and a long jumble of 'where' statements. This class will allow you to run a universal 'google-like' search on any IQueryable. More Information
var results = cars.Search(new object[] {"chevy", 2007});
// will search cars for the string "chevy" 
// and the int 2007 across all fields


Universal Get Extensions for your DataContexts, Find the Primary Key of any table, and more
// will return the PropertyInfo of the Primary Key(s) of 'table'

// is the same as writing:
someDataContext.Cars.FirstOrDefault(x => == someKey);
// regardless of what Type someKey is or what the 
// PropertyInfo.Name of the Primary Key is; never write 
// a Get accessor again!


Simple extension to save a FileStream to disk, option to avoid overwriting will automatically update the filename to avoid overwriting:
// will save the file to the given path
// 'file[1].txt' if the file is already there 
// the file name will be returned 

someFileStream.Save(@"C:\file.txt", false);
// will save the file to the given path,
// overwriting if the file already exists


Convert strings to things you often need to convert them to, easily.
string s = s.RemoveCharacters(new[] { 'a', 'b' })
// removes any instances of 'a' or 'b' from s

string s = Strings.Random(10)
// random string, all alphanumeric, length 10
string s = Strings.Random(10, 2)
// random string, min 2 special chars, length 10

double x = "8".To<double>; 
// converts string to any type 
// (double in this case)

EnumType et = "Something".ToEnum<EnumType>; 
// turns string into any enum 
// (EnumType.Something in this case)

int? x = "5".ToNullable<int>;
// turns a string into any Nullable Type you want 
// (int in this case)

MVC Html Helper for including an Id with a DisplayFor

there are cases when you want to include an id with your DisplayFor()

public static MvcHtmlString DisplayWithIdFor(
    this HtmlHelper helper, 
    Expression> expression, 
    string wrapperTag = "div")
    var id = helper.ViewContext.ViewData.TemplateInfo
    return MvcHtmlString.Create(
        string.Format("<{0} id=\"{1}\">{2}", wrapperTag, 
        id, helper.DisplayFor(expression)));

It is used like this:
@Html.DisplayWithIdFor(x => x.Name)
<!-- to produce -->
<div id="Name">Bill</div>

Or if you want to wrap it in a non-div:
@Html.DisplayWithIdFor(x => x.Name, "span")
<!-- to produce: -->
<span id="Name">Bill</span>

Quick LINQ Trick

cool way to shorten and make your code more readable with LINQ

Say I have this function:
public string DoStuff(string s) 
    //whole bunch of stuff
    return s; 

Now say I have the following:
public IEnumerable DoThings(IEnumerable strs) 
    var ret = new list();
    foreach(var s in strs)
    return ret;

Which can be reduced to:
public IEnumerable DoThings(IEnumerable strs) 
    foreach(var s in strs)
        yield return DoStuff(s);

public IEnumerable DoThings(IEnumerable strs) 
    strs.Select(x => DoStuff(x));

but even further you can simply take it to:
public IEnumerable DoThings(IEnumerable strs) 

Since the enumeration is already strings, the Select statement knows just to pass them through the method supplied. With it this small, the method is almost useless to write out:
// Tnstead of:
var x = DoThings(strs);

// you can simply substitute: 
var y = strs.Select(DoStuff);

// giving you the same results without having to write 
// a method

It's nothing revolutionary, but can clean up your code where applicable.

Random String Generator in C#

produce random string simply in .net, without special characters if need be

It is very simple to get random string since the introduction of Membership.GeneratePassword() - so this really just a way to utilize that and pull out special characters if that is what you are looking for.
public static string ToRandomString(this string s, 
    int length, bool isOnlyAlphaNumeric = true, 
    int minSpecialCharacters = 1)
    if (isOnlyAlphaNumeric) minSpecialCharacters = 0;
    s = Membership
        .GeneratePassword(length, minSpecialCharacters);
    if (!isOnlyAlphaNumeric) return s;
    char[] msSpecialCharacters = 
    string filler = 
        Membership.GeneratePassword(length, 0);
    int fillerIndex = 0;
    int fillerBuffer = 0;

    while(s.IndexOfAny(msSpecialCharacters) > -1 
        || s.Length < length)
        s = s.RemoveCharacters(msSpecialCharacters);
        fillerBuffer =length - s.Length;
        if((fillerBuffer + fillerIndex) > filler.Length)
        {   // filler would out-of-bounds, get a new one
            filler = 
                Membership.GeneratePassword(length, 0);
            fillerIndex = 0;
        s += filler.Substring(fillerIndex, fillerBuffer);
        fillerIndex += fillerBuffer;
    return s;

public static string RemoveCharacters
    (this string s, char[] characters)
    return new string(s.ToCharArray()
        .Where(c => !characters.Contains(c)).ToArray());

This has been added to my Naspinski.Utilities library, though it isn't released just yet, looking to tweak it a bit first.

Helper Methods for Validating Generated Linq-to-Entities edmx Files using Partial Classes

Centralized client and server side validation as well as property and method additions to auto-generated classes

Say I have an auto-generated Widget class (from a database, generated into a .edmx file):
namespace My.NameSpace
    public partial class Widget
        public int Id { get; set; }
        public string Name { get; set; }

Now I want to add some methods and validation to the class, but I do not want to edit the class directly. What I need to do is make a partial class and add the things in there. This accomplished two things: 1. separates logic from structure and 2. separates the files so another auto-generation or update will not lose the work you do. This is very simple to do, here is an example:
// be SURE that it is in the same namespace
namespace My.NameSpace
    public partial class Widget
        // I want to add another property
        public string FullName
        { get { return Name + Id; } }

    // this is the validation segment
    // this is the same as the class name above
    public class VWidget
        [Display(Name = "Widget Name")]
        public string Name { get; set; }

Now this was very simple, but it shows how to add this in. First of all, there is a new property to Widget called 'FullName' which will combine the 'Name' and 'Id' properties. Not really all that useful, but you can see how it is used.

The next part is really cool, you can put all of your validation in the 'VWidget' class (name doesn't really matter here). Here you can see that 'Name' is now required, has a max length of 50 characters, and a label will display "Widget Name" instead of the default property name. This way, if you are using this library with MVC, you can do something this simple:
@using (Html.BeginForm())
    @Html.LabelFor(x => x.Name)
    @Html.EditorFor(x => x.Name)

And you will be pushing client-side validation as well as a centralized area to hold your custom labels. On top of that, in your code, if you simply include:
if (ModelState.IsValid)

You will be enforcing server-side validation as well.

Later I will get into how you can use .resx files for localization and centralization along with these partial classes.

Using a Custom Controller Class in Asp.Net MVC to Simplify Coding

Controllers often have some repetitive code, implementing your own Controller class can help eliminate a lot of this

Here is a small snippet and how I use some simple tricks to help clean up my Controllers in Asp.Net MVC (using MVC 4 at the moment):
public class MyController : Controller
    public MyEntities Db { get; set; }

    protected override void OnActionExecuting(
        ActionExecutingContext filterContext)
        if (filterContext.IsChildAction)
        this.Db = new MyEntities();

    public ActionResult Index(FormCollection form)
        string srch = form["Search"] ?? string.Empty;
        return RedirectToAction("Index", 
            new { search = srch });

    protected void AttachToDb(EntityObject obj, 
        bool save = false, string entityKeyField = "Id")
            obj.EntityKey = new EntityKey(
                obj.ToPluralizedString(), entityKeyField, 
                .GetValue(obj, null));
                obj, System.Data.EntityState.Modified);
            if (save) Db.SaveChanges();

The first thing in the code is simple declaration of an EntityContext - this is implemented directly, but could (and usually should) be implemented differently for dependency injection, but you get the idea. Here is where I also like to include stuff that is often used and could be vital (and centralized) for an application like an output type for web services (JSON, XML, etc.).

Next the OnActionExecuting is over-ridden and the Context is initialized. Here is where you can initialize the properties you set above.

The next method, the HttpPost Index method is just an example of how often times you can consolidate a commonly used method. For this example, it was from an application that had searches on all index pages. Instead of repeating this code in every controller, you can just put it here.

The final method has become very useful. A use I often find, is when taking in a large model after an Asp.Net MVC POST event, I can attach the model to the Db generically without any extra work

This method is a bit confusing, but it is simply attaching the new model to the Db without a Db lookup. In my tables, I generally have a field 'Id' that houses the Primary Key of every table, whether it is an Int or Guid. This way, I can simply pass in whatever object I am currently working with, and by using the pluralize method, and reflection, the method can figure out which table to attach the model to - eliminating the need for me to do extra coding. Alternatively, if I want to change the Key from 'Id', I can pass that in as well.

Now when I get a model being POSTed, it is easy to deal with:
public ActionResult Edit(Widget model)
        AttachToDb(model, true);
        //do stuff
    else { /*do other stuff*/ }

This avoids the need to take another trip to the DB, change the properties on the object, then submit - streamlining the process very much and cutting down a lot of code.

This would be an example of how this would be done manually with the normal Controller class:
public ActionResult Edit(Widget model)
        MyEntities db = new MyEntities();
        Widget w = db.Widgets.Single(x => x.Id == model.Id);
        w.Name = model.Name;
        w.Serial = model.Serial;
        //do stuff
    else { /*do other stuff*/ }

Not a huge difference when you are just getting 2 values, but you could see how a model with 20 or 30 fields can be cut down from 30+ lines to just 1 or 2.

Pluralize a String or Class Name in C# and .Net

Sometimes you need to pluralize names like when you are working with Entity Framework or countless other sitautaions

When you auto-generate from tables in Entity Framework, it will make the table names plural, and the objects singular. Often times, when you are trying to use more generic functions like creating EntityKey objects for attaching to an unknown table, you will need to pluralize a class name, so for this, I came up with a couple static methods to simply return a plural version of an Object's name or a string itself:
using System.Data.Entity.Design.PluralizationServices;
using System.Globalization;

public static string Pluralize(this string s)
    PluralizationService plural = 
    return plural.Pluralize(s);

Simple enough, now I make this specifically to get the table name of an EntityObject:
public static string GetTableName(this EntityObject obj)
    return obj.GetType().Name.Pluralize();

In use:
//returns "Cats":
string cats = "Cat".Pluralize();

//now specifically for EntityObjects:
string tableName = MyEntityObject.GetTableName();

Constraining Routes in MVC to an Enum the Easy Way

simple way to constrain a route to only allow enum values

Say I have the following enum:
public enum SearchType { Facilities, Courses, Exercises};

And I only want those the be available in route Search/{SearchType}. I could constrain it manually with a string, but then what if the enum changes and I have this in a bunch of routes? Here is a simple way to accomplish this constraint:
public static void RegisterRoutes(RouteCollection routes)
    List searchTypeL = new List();
    foreach (Enums.SearchType type in 
    { searchTypeL.Add(type.ToString()); }
    string searchTypes = string.Join("|", searchTypeL);
        new { controller = "Search", action = "Index" },
        new { type = searchTypes }

Very basic, all this does is enumerate through your enum and create a simple string to filter with.

ReCaptcha - Getting the Challenge Key and/or image with Asp.Net MVC

Often times you do not need the whole deal, or you are working with a technology that doesn't employ javascript or iframes

Recently I was working on a project that needed to provide (via MVC 3) the ReCaptcha image and/or challenge key only, and not the whole html/javascript portion due to limitations by the data consumer. It took me a while, but there is quite an elegant and simple solution to this.

Here is the controller I came up with:
public class CaptchaController : Controller
    public string contentReturnType = "text/plain";
    public string googleChallengeUrl = "http://{0}";
    public string googleImageUrl = "http://{0}";
    public string googleImageHtml = "<img style=
        \"display: block; \" height=\"57\" width=\"300\" 

    public ContentResult GetChallengeKey(
        string proxyIpAndPort = null)
        string http = string.Format(googleChallengeUrl, 
        WebClient client = new WebClient();

        //assuming no proxy on a local machine
        if (!string.IsNullOrEmpty(proxyIpAndPort) && 
            client.Proxy = 
                new WebProxy(proxyIpAndPort, true);

        string html = client.DownloadString(http);
        int start = html.IndexOf('{');
        int length = html.IndexOf('}') - start + 1;
        string json = html.Substring(start, length);

        ReCaptchaState state = 
            new JavaScriptSerializer()
        return this.Content(state.challenge, 

    public ContentResult GetImageUrl()
        return this.Content(string.Format(googleImageUrl, 
            GetChallengeKey().Content), contentReturnType);

    public ContentResult GetImageHtml()
        return this.Content(string.Format(googleImageHtml, 
            GetImageUrl().Content), contentReturnType);

This is using json deserializing of the ReCaptcha return string into a .Net object named ReCaptchaState which is covered here.

Now all that you need to do is call one of the urls to get the desired result in a plaintext format (you can change the output if you wish).