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.

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

Random .Net SQL Generator (Open Source)

A random generator for all types of queries in SQL - extend-able to any SQL provider

I have often ran into the case where I need to insert a bunch of random records against a table or do a lot of queries to test for integrity - but those tools always seem to cost money. Some classmates and I did a project last semester that allowed for random SQL generation of all types. This is a generation tool for random queries in SQL in the Windows environment. It can produce random queries, tables, deletes, and updates as well as generate random data for a table. This was implemented with PostgresSQL, but we tried to structure it to allow easy adaptation for other SQL implementations as well.

The interface was meant to be very simple and requires no information about the tables themselves, just feed in basic information like the connectionstring and the table name to run the query against:

insert 100 random records

PgSqlGenerator pg = new PgSqlGenerator("127.0.0.1", 5432, 
    "postgres", "sql", "my_database");
Table people = pg.GetTable("people");
QueryInformation report = 
    pg.ExecuteBulkInsert(people, 100);

//now check the results:
Console.WriteLine("Query: " + report.Query);
Console.WriteLine("Time Taken: " + report.Time);
Console.WriteLine("Rows Affected: " + report.Affected);

It is far from bug-free, but works very well - figured we would share what we did.



Generate random values in C#

all sorts of random values including date, times, numbers, binary, bit, etc.

Nothing new here, but it's nice to have it all in one spot.

generate random values

public int Integer(int max = Int16.MaxValue)
{
    max = max > Int16.MaxValue ? Int16.MaxValue : max;
    return new Random().Next(-max, max);
}

public string Binary(int length = 8)
{            
    int decNum = new Random().Next(1000, int.MaxValue);
    return Convert.ToString(decNum, 2)
        .Substring(0, length);
}

public DateTime Date(int start_year = 1995)
{
    DateTime start = new DateTime(start_year, 1, 1);
    int range = ((TimeSpan)(DateTime.Today - start))
        .Days;
    start.AddDays(new Random().Next(range))
        .AddSeconds(new Random().Next(86400));
}

public TimeSpan Time()
{
    return Date().TimeOfDay;
}

public int Bit()
{
    return new Random().Next() % 2 == 0 ? 1 : 0;
}

public bool Bool()
{
    return new Random().Next() % 2 == 0 ? true : false;
}

public string String(int limit = 255)
{
    // added spaces so there will be 
    // a higher chance of spacing words
    string legal = "        abcdefghijklmnopqrstuvwxyz" +
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789      ";
    StringBuilder s = new StringBuilder();
    //Random length for the string
    limit = new Random().Next(1, limit); 
    for (int i = 0; i < limit; i++)
        s.Append(legal[new Random().Next(legal.Length)]);
    return s.ToString();
}

Learning Ruby on Rails for a .Net MVC C# Coder

quick reference for equivalent methods/approaches

I am learning RoR for a new project that requires the ability to truly run cross-platform (don't even say Mono...). That said, I love .net, but Ruby on Rails is a fantastic MVC framework. I am learning a lot about MVC programming in general and here is my contribution to others trying to learn RoR in my situation.

And yes, I know there are many more syntax options than the ones I show, but this is just a quick reference -if you want them all, check out the API.

Everything presented here will render the same html in the respective languages, as well as behave the same as data access (ORM):

stylesheet/javascript links

Asp.Net MVC
<link rel="stylesheet" type="text/css" 
 href="<%=Url.Content("~/public/stylesheets/style.css") %>"
/>
<script type="text/javascript" 
 src="<%=Url.Content("~/public/javascripts/jquery.js") %>"
></ script>

RoR
<%= stylesheet_link_tag 'style' %>
<%= javascript_include_tag 'jquery' %>


hyperlinks

Asp.Net MVC
<%= Html.ActionLink("View Widgets", "Index", "Widget") %>
<%= Html.ActionLink("Widget 5", "Show", "Widget",
  new {id = 5}) %>

RoR
<%= link_to 'View Widgets', widgets_path %>
<%= link_to 'Widget 5', widget_path(5) %>


forms

Asp.Net MVC
<% using(Html.BeginForm()) { %>
 <%= Html.LabelFor(x => x.Name) %>
 <%= Html.TextBoxFor(x => x.Name) %>
 <input type="submit" value="submit" />
<% } >

RoR
<% form_for(@widget) do |f| %>
 <%= f.label :name %>
 <%= f.text_field :name %>
 <%= f.submit 'submit' %>
<% end %>


rendering partials

Asp.Net MVC
<%= Html.Partial("form") %>

RoR
<%= render :partial => 'form' %>


looping

Asp.Net MVC
<% foreach(var widget in Model.Widgets) { %>
  <%= widget.Name %>
<% } %>

RoR
<% for widget in @widgets %>
  <%= widget.name %>
<% end %>


validation

Asp.Net MVC
[MetadataType(typeof(WidgetValidation))]
public partial class Widget { }

public class WidgetValidation
{
  [Required(ErrorMessage = "Name is Required")]
  [RegularExpression("[\\S]{5,}", ErrorMessage = "Min 5 chars")]
  [StringLength(30, ErrorMessage = "Max 30 chars")]
  public string Name { get; set; }
}

RoR
class Widget < ActiveRecord::Base
  validates_presence_of :name
  validates_length_of :name, :in => 5..30
end


orm data access

Asp.Net MVC (Linq-to-Sql)
var db = new MyDataContext();
var widgets = db.Widgets;
var widget = db.Widgets.SingleOrDefault(x => x.Id == 5);
var components = widgets.Components.OrderBy(x => x.name);

RoR (ActiveRecord)
@widgets = Widget.all
@widget = Widget.find(5)
@components = @widget.components.sort_by{|w| w.name}


saving a model

Asp.Net MVC (Linq-to-Sql)
public ActionResult Create(Widget widget)
{
  db.InsertOnSubmit(widget);
  db.SubmitChanges();
}

RoR (ActiveRecord)
def create
  @widget = Widget.new(params[:widget])
  @widget.save
end


helper methods

Asp.Net MVC
// define it:
public static string DivThis(this HtmlHelper html, string text)
{
  return "<div>" + text + "</div>";
}

<!-- call it: -->
<= Html.DivThis("hello") %>

RoR
# define it
def div_this(text)
  '<div>' + text + '</div>'
end

<!-- call it: -->
<%= div_this('hello') %>



temporary data

Asp.Net MVC
// set it
TempData["someKey"] = "hello"

<!-- use it -->
<%= TempData["someKey"].ToString() %>

RoR
# set it
flash[:some_key] = 'hello'

<!-- use it -->
<%= flash[:some_key] %>


That's all I have for now, hopefully I will be adding more in the near future. I think I like RoR...

ServerInfo - Easily scan a Machine/Server Farm for Information

new open-source project in Asp.Net MVC 2

More than once I have been asked what databases are on what server, if server X is running application Y or what websites server ABC is running. These are are relatively simple things to accomplish, and there are tools available to get this information, but this is an extremely simple and portable solution - all the data is kept in xml, so there is no need to install a backend.

All that it is required to get all this information is to enter ip addresses and the user has the rights to scan the machines requested.

In addition, this can keep track of all of the owners of the machines and has a GUI for running WMI Queries, which is extremely powerful if you know how to use it.

This is written with Asp.Net MVC 2, C# and xml; it requires .Net 4.0 framework. I will be updating this to MVC 3/Razor in the near future.