loads of useful information, examples and tutorials pertaining to web development utilizing asp.net, c#, vb, css, xhtml, javascript, sql, xml, ajax and everything else...

 



Advertise Here
C-Sharpener.com - Programming is Easy!  Learn Asp.Net & C# in just days, Guaranteed!

Double Input problem with CheckBoxFor in MVC while serializing

by naspinski 1/25/2013 2:44:00 PM

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

by naspinski 10/20/2012 5:03:00 PM

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:

DynamicProperty

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

IQueryableSearch

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


LinqToSql

Universal Get Extensions for your DataContexts, Find the Primary Key of any table, and more
Naspinski.Utilities.GetPrimaryKey<table>();
// will return the PropertyInfo of the Primary Key(s) of 'table'

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

FileStreamSave

Simple extension to save a FileStream to disk, option to avoid overwriting will automatically update the filename to avoid overwriting:
someFileStream.Save(@"C:\file.txt")
// 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

StringConversions

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)

Tags: , ,

c# | linq

MVC Html Helper for including an Id with a DisplayFor

by naspinski 10/18/2012 5:29:00 PM

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

by naspinski 9/18/2012 4:21:00 PM

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#

by naspinski 9/14/2012 3:23:00 PM

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.