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.

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.

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.



best javascript toggleDiv function ever

Everyone has a javascript toggleDiv function somewhere, but this is the cleanest one you will ever see

All this is is an expand and collapse of whatever you want it to expand/collapse - it is made for divisions with the 'block' declaration, but could also be used for inline elements if you simply changed it to 'inline' 

function toggleDiv(divid){
  var div = document.getElementById(divid);
  div.style.display = div.style.display == 'block' ? 'none' : 'block';}

Basically it is just a condensed if/then statement.  Keep in mind it will only work on the very first click if you already have 'display' set to 'block' or 'none' at first, otherwise it will take 2 clicks.  It is about as simple as it gets.