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.

inline tags... sorting them all out (<%$, <%=, <%, <%#, etc.)

There are all sorts of different inline tags, and I haven't found a place that explains them all in one place, so here is the quick and dirty...

*UDPATED 2012-02-22: Thanks to Conrad Buck and Austin for updates!

<% ... %>

The most basic inline tag, basically runs normal code: 

<% if (User.IsInRole("admin")) { %>
    You can see this
<% } else { %>
    You are no admin fool!
<%} %>



<%= ... %>

Used for small chunks of information, usually from objects and single pieces of information like a single string or int variable: 

The Date is now <%= DateTime.Now.ToShortDateString() %>
The value of string1 is <%= string1 %>

*note: <%= is the equivalent of Response.Write() -  Courtesy of Adam from the US,thanks!



<%# .. %>

Used for Binding Expressions; such as Eval and Bind, most often found in data controls like GridView, Repeater, etc.:

<asp:Repeater ID="rptMeetings" DataSourceID="meetings" 
        <%# Eval("MeetingName")%>



<%$ ... %>

Used for expressions, not code; often seen with DataSources: 

<asp:SqlDataSource ID="party" runat="server" 
    ConnectionString="<%$ ConnectionStrings:letsParty %>" 
    SelectCommand="SELECT * FROM [table]"



<%@ ... %>

This is for directive syntax; basically the stuff you see at the top your your aspx pages like control registration and page declaration: 

<%@ Page Language="C#" 
    AutoEventWireup="true" CodeFile="Default.aspx.cs" 
    Inherits="_Default" Title="Untitled Page" %>
<%@ Register TagPrefix="wp" Namespace="CustomWebParts" %>



<%-- ... --%>

This is a server side comment, stuff you don't want anyone without code access to see:

<asp:Label ID="lblAwesome" runat="server"/>
<%-- sometimes end users make me angry --%>
<asp:LinkButton ID="lbEdit" Text="Edit" OnClick="Edit_Click" runat="server" />


<%: ... %>

This tag is identical to the "<%= ... %>" tag except that it auto-html-encodes the value within the tag. As Phil Haack said: I often tell people it’s <%= but with the = seen from the front.:

<%: Html.TextBox("FirstName") %>


And that's that.  

kick it on

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.

Ternary Operator in SQL

there technically isn't one, but an equivalent isn't too hard to do

This ternary in C#:
(str.Length > 0 ? "yes" : "no");

Is equivalent to this in SQL:
(CASE WHEN LEN(@str) > 0 THEN "yes" ELSE "no" END);

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();

My Case For Using Both UNIQUEIDENTIFIER (Guid) -and- INT Ids in every database table

Case for dual database accessors (not keys) - Guid vs Int/UniqueIdentifier vs Int

Let's face it, you never know what exactly is going to end up with your next application. Has an application ever ended up exactly where it was planned in the beginning? I would say never.

There is an insane amount of writing on the debate of int vs guid, both have their pros and cons, both have storage, index and coding implications and we know (or can find) almost all of them with a simple search. Yet there is no consensus on which is the best, I am not here to add to that discussion.

Therefore I propose using BOTH - hear me out.

I propose that the best solution is to provide ONE of the two as your primary key, I prefer Guid as the PK, as it can be referenced more universally (think recycle bin, etc.), but it does have the added indexing cost of being larger; then simply add the auto-incrementing integer as an additional field. Whichever one you choose as your alternative (integer in my case) is simply as a just-in-case means of accessing your data - also indexed. This provides you the best of both worlds, without too much sacrifice. For example, you get the ubiquity of being able to generate a Guid anywhere (without a DB trip), but also have the ability to access your data by a clean 4-bit integer. If for some reason, the code is accessed by software that relies on integers, you are not stuck without one, and vice-versa.

Yes, this will obviously cause more data to be stored for every entry in a table (I am talking about main tables here, not necessarily lookup tables, etc.). This will cause extra index storage as well, but in the long run, I feel it provides enough advantage and future-proofing to justify the sacrifice. Now tell me how wrong I am...