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 
        Enum.GetValues(typeof(Enums.SearchType))) 
    { searchTypeL.Add(type.ToString()); }
    string searchTypes = string.Join("|", searchTypeL);
    
    routes.MapRoute(
        "Searches",
        "Search/{type}",
        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.

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

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://
        www.google.com/recaptcha/api/challenge?k={0}";
    public string googleImageUrl = "http://
        www.google.com/recaptcha/api/image?c={0}";
    public string googleImageHtml = "<img style=
        \"display: block; \" height=\"57\" width=\"300\" 
         src=\"{0}\"/>";

    [HttpGet]
    public ContentResult GetChallengeKey(
        string proxyIpAndPort = null)
    {
        string http = string.Format(googleChallengeUrl, 
            ReCaptchaValues.PublicKey);
        WebClient client = new WebClient();

        //assuming no proxy on a local machine
        if (!string.IsNullOrEmpty(proxyIpAndPort) && 
            !Request.IsLocal) 
        {
            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()
                .Deserialize(json);
        return this.Content(state.challenge, 
            contentReturnType);
    }

    [HttpGet]
    public ContentResult GetImageUrl()
    {
        return this.Content(string.Format(googleImageUrl, 
            GetChallengeKey().Content), contentReturnType);
    }

    [HttpGet]
    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).

Deserializing ReCaptcha JSON with C#

Turning a ReCaptcha request into a strongly-typed C# object on the fly

When requesting a ReCaptcha image, you send out this request:
http://www.google.com/recaptcha/api/challenge?k=your_public_key

You then receive this in return:
var RecaptchaState = {
    site : 'your_public_key',
    challenge : 'returned_challenge_key',
    is_incorrect : false,
    programming_error : '',
    error_message : '',
    server : 'http://www.google.com/recaptcha/api/',
    timeout : 18000
};

document.write('<scr'+'ipt type="text/javascript" 
    s'+'rc="' + RecaptchaState.server + 'js/recaptcha.js">
    </scr'+'ipt>');

Looking at that, you can pull the information you need into this object:
[Serializable]
public class ReCaptchaState
{
    [DataMember]
    public string site { get; set; }

    [DataMember]
    public string challenge { get; set; }

    [DataMember]
    public bool is_correct { get; set; }

    [DataMember]
    public string programming_error { get; set; }

    [DataMember]
    public string error_message { get; set; }

    [DataMember]
    public string server { get; set; }

    [DataMember]
    public int timeout { get; set; }
}

By using this code:
WebClient client = new WebClient();
string ret = client.DownloadString(google_url);
int start = ret.IndexOf('{');
int length = ret.IndexOf('}') - start + 1;
string json = ret.Substring(start, length);

ReCaptchaState state = new JavaScriptSerializer()
    .Deserialize<ReCaptchaState>(json);

Now you have a ReCaptchaState .net object you can use the values from; simple.

CohesiveSoftware.com

As I have been getting more and more freelance offers and work, the decision was made to launch a new website and brand

Yesterday I launched CohesiveSoftware.com as a contact point for custom work. Me and some fellow developers have teamed up on a few projects and decided to make it official. If you need any work done, please feel free to drop us a line - happy coding!

Updating Multiple Fields via LINQ and Reflection Automatically (EF4)

You can use reflection to avoid manually entering a ton of fields

Recently, the question was asked on Stackoverflow about updating multiple integer fields in an EF4 object without having to type each out manually. I had run into a similar problem like this in the recent past where I had a large number of int fields (38 to be exact) and I didn't really want to write in 38 lines of essentially the same thing into my code. Instead, I cam up with this using Reflection. This simple example shows an object 'o' and a single new value 'newValue', but you can easily use an array or list as well for inserting values - this just gets the point across:
foreach(PropertyInfo prop in o.GetType().GetProperties()) 
{
    if(prop.PropertyType == typeof(int))
        prop.SetValue(o, newValue, null);
}

You can see in this example, I look only for integer fields, but it would be simple to check for any other type of field, or name, or a field that has a name that starts with 'abcd' - the list is endless and simple to adapt to.

Running C# libraries with the SQL CLR

You can run your dlls from inside SQL - but it is a bit limited

Sometimes you need your SQL server to run a little bit of one of your programs, this is not a common case, but I have found it does happen. It is quite possible and not too complicated, but you are limited in what you can use. For example, even in SQL 2008, the maximum framework you can run is 3.5 (really 2.0), so anything with 4.0 is off limits due to the CLR. Also, many dlls are also off limits such as System.Data.Linq and System.Data.Entity so kiss most of your ORM solutions goodbye if you plan on doing this.

For this example, I am going to use a simple table in my SQL which will follow after this. For the example, I am going to write a C# method that writes in a new Widget to the Widgets table in the 'SqlClrTest' database at the current time - nothing fancy or useful, but it is easy to understand.
CREATE TABLE Widget(
	Id INT NOT NULL IDENTITY PRIMARY KEY,
	Name NVARCHAR(100) NOT NULL,
	Created DATETIME NOT NULL
);

Now you need to set up your environment to handle the CLR:
--allow you to use it
ALTER DATABASE SqlClrTest SET TRUSTWORTHY ON;

--and turn it on
sp_configure 'clr enabled', 1
GO
reconfigure
GO

Now in a new library, I will make a simple class with older ADO that inserts a new entry. Yes, I know this isn't written well, but it is very simple to understand...
using System;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

namespace SqlClr
{
    public class Widget
    {
        public Widget() { }

        [SqlProcedure]
        public static void Insert(SqlString name)
        {
            string connectionString = 
                "Data Source=.\\sqlexpress;
                 Initial Catalog=SqlClrTest;
                 Integrated Security=True";
            string date = SqlDateTime
                .Parse(DateTime.Now.ToString())
            SqlConnection conn = new 
                SqlConnection(connectionString);

            SqlCommand sqlComm = new 
                SqlCommand("INSERT INTO Widget 
                (Name, Created) VALUES 
                ('" + name.ToString() + "', '" + 
                date + "')", conn);

            conn.Open();
            sqlComm.ExecuteNonQuery();
            conn.Close();
        }
    }
}

Notice that the inputs are defined in System.Data.SqlType, also, the method is painted with a [SqlProcedure] attribute. Now compile the dll and take down the path to it. Go back into SQL and enter the following to compile the assembly into SQL:
CREATE ASSEMBLY Sql_Clr
AUTHORIZATION dbo
FROM 'C:\path-to-assembly\SqlClr.dll'
WITH PERMISSION_SET = UNSAFE;

Now you will notice it shows up under your table > programmability > assemblies directory if it worked correctly. I gave it a name with an underscore so you can see where that comes into play later. Next you will need to make a stored procedure that calls the method:
CREATE PROCEDURE WidgetInsert 
	@name nvarchar(100)
AS EXTERNAL 
	NAME Sql_Clr.[SqlClr.Widget].Insert;
GO

You can see that you call it in this format: SqlDllName[C#DllName].Method. Now all that is left is to call the method in SQL:
EXEC WidgetInsert 'NEW WIDGET'

And you have successfully (in the most round-about way possible) used a SQL stored procedure to call a .Net dll to run a method to update the database.

Adding Custom Exception Handling Attributes to Your Asp.Net MVC Actions

Attributes are a simple way to run common handling across many actions without repeating yourself

I ran into a position where I was handling exceptions and pushing them to xml ContentResults the same way on multiple actions across many controller repeating a lot of code. I was working on a REST interface that always was to return xml. All Exception were to be returned in xml as well. I found myself writing a lot of actions like this:
public ContentResult Fidget()
{
    try
    {
        //do a bunch of stuff
        //throw exceptions if I need to
    }
    catch(Exception ex) //now catch them and display xml
    {
        // turn the exception into xml
        return this.Content(myXmlException, "text/xml");
    }
    
    // if it made it here, return success xml
    return this.Content(successXml, "text/xml");
}

This worked great, but after a bunch of actions, the code was very redundant. I want to handle exception the same on a lot of actions, but not all, so I decided to go to an Attribute, specifically ActionFilterAttribute and the IExceptionFilter. If I override the OnException, I can automatically handle the Exceptions in the painted actions, so this is what I came up with:
[HttpGet]
public class XmlExceptionAttribute : 
    ActionFilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext 
        filterContext)
    {
        if (filterContext.Exception == null) return;
        filterContext.ExceptionHandled = true;
        var response = filterContext.Controller
            .ControllerContext.HttpContext.Response;
        response.ContentType = "text/xml";
        response.Write((new Status(
            filterContext.Exception)).ToXmlString());
    }
}

*Note that the Status object is a just an object I made to be serializeable and .ToXmlString() is an extension method I came up with a while back to convert objects into xml strings on the fly.

Now, if the attribute is applied, all I have to do for the above behavior in an action is simply this:
[HttpGet]
[XmlException]
public ContentResult Fidget()
{
    //do a bunch of stuff, throw exceptions if I need to
    
    // if it made it here, return success xml
    return this.Content(successXml, "text/xml");
}

The behavior is now the EXACT same!

The argument types 'Edm.Decimal' and 'Edm.Double' are incompatible for this operation.

error you may run into while making queries in Linq-to-Entities

What this is indicating is that you are comparing a Decimal data type to a number that is not a Decimal. While it may look like it, this:
0.007 // is *not* a double in .Net land

// the proper form is this:
0.007M

So instead of this query:
var query = db.aTable.Where("it.Length = 0.01");
// make sure it is this instead:
var query = db.aTable.Where("it.Length = 0.01M");

Serializing and DeSerializing XML Objects in .Net

these two simple extension methods with have you switching between XML and objects in no time

First off, it is pretty well known that if you have any Object and want to convert it into an XML strong, you can use the XmlSerializer to do so. I encapsulated the process is a simple extension method that run from any object - this will work as long as the object has a constructor with no inputs (ie: new SomeObject()) as that is the constraint passed up from XmlSerializer. Here is the method for converting from an object to an xml string:
public static string ToXmlString(this Object o)
{
    StringWriter xml = new 
        StringWriter(new StringBuilder());
    XmlSerializer xS = new XmlSerializer(o.GetType());
    xS.Serialize(xml, o);
    return xml.ToString();
}

With this, now all you need to do is:
MyObject obj = new MyObject();
// a bunch of stuff here...
// now I want the xml representation of this:
string xml = obj.ToXmlString();

Now to go backwards, you can use the similar Deserialize along with the XmlSerializer with this method:
public static T XmlToObject<T>(this string s)
{
    var xR = XmlReader.Create(new 
        StringReader(s));
    XmlSerializer xS = new XmlSerializer(typeof(T)); 
    T obj = (T)xS.Deserialize(xR);
    return obj;
}

It is important to notice that this is taking in a raw xml string, which would not be web safe. If you were taking in data from a web source, you would want to employ HttpUtility.UrlDecode(s) instead of just s above. Now if you want to turn your above string 'xml' into an object again, simply call it like this:
MyObject obj2 = xml.XmlToObject<SomeObject>();