jQuery moveTo() plugin

simple way to move an element from A to B

Say you have these elements:
<ul id="A">
    <li id="L1">Stan</li>
    <li id="L2">Arnold</li>
</ul>
<ul id="B">
</ul>

And you want to move 'L1' (Stan) to ul 'B' - using this simple short plugin:
(function ($) {
    $.fn.moveTo = function (selector) {
        return this.each(function () {
            var element = $(this).detach();
            $(selector).append(element);
        });
    };
})(jQuery);

You can do that with this:
$('#L1').moveTo('#B');

Now you have this in your DOM:
<ul id="A">
    <li id="L2">Arnold</li>
</ul>
<ul id="B">
    <li id="L1">Stan</li>
</ul>

Or, similarly, you can do something like this:
$('li').moveTo('#B');

Now you have this in your DOM:
<ul id="A">
</ul>
<ul id="B">
    <li id="L1">Stan</li>
    <li id="L2">Arnold</li>
</ul>

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).

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
        .GetFullHtmlFieldId(ExpressionHelper
            .GetExpressionText(expression));
    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)
        ret.Add(DoStuff(s));
    return ret;
}

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

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

but even further you can simply take it to:
public IEnumerable DoThings(IEnumerable strs) 
{  
    strs.Select(DoStuff);
}

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 = 
        "!@#$%^&*()_-+=[{]};:<>|./?".ToCharArray();
    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
{
    //System.ComponentModel.DataAnnotations
    [MetadataType(typeof(VWidget))]
    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")]
        [Required]
        [StringLength(50)]
        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.ValidationSummary()
    @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)
            return;
        this.Db = new MyEntities();
        base.OnActionExecuting(filterContext);
    }

    [HttpPost]
    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, 
                obj.GetType().GetProperty("Id")
                .GetValue(obj, null));
            Db.Attach(obj);
            Db.ObjectStateManager.ChangeObjectState(
                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:
[HttpPost]
public ActionResult Edit(Widget model)
{
    if(ModelState.IsValid)
    {
        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:
[HttpPost]
public ActionResult Edit(Widget model)
{
    if(ModelState.IsValid)
    {
        MyEntities db = new MyEntities();
        Widget w = db.Widgets.Single(x => x.Id == model.Id);
        w.Name = model.Name;
        w.Serial = model.Serial;
        db.SaveChanges();
        //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 = 
        PluralizationService.CreateService(
            CultureInfo.GetCultureInfo("en-us"));
    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();

Monitoring a DOM Element for Modification with jQuery

'watching' an element for any change within it

I recently ran into a situation where I had to modify a site that relied on an incredibly obfuscated and impossible to understand javascript file. I had to add in some elements after everything was populated with some function I didn't get, so I had to wait until a specific element was populated to do anything. Turns out the DOMNodeInserted event is what I needed:
var title = $("b.facility");
var title = $('#title');//the element I want to monitor
title.bind('DOMNodeInserted', function(e) {
    alert('element now contains: ' + $(e.target).html());
});

Pretty simple, but took me forever to figure out...