Generate class from XSD

Discovered something nice today, Microsoft has built a small tool to convert a XSD file into a code class for you. This is very very useful when need to serialize some information and using a XSD file as a base. Simply open up the Visual Studio Command Prompt and navigate to the folder that contains the XSD file and enter the following:

xsd /classes /language:CS XSDFileNameHere.xsd

This will generate a delightful little .cs class file for you, ready to be used in your project!

Improve your server Garbage Collection Performance

I came across a little known config of ASP.Net applications. We all know about the built-in Garbage Collection system that the .Net Framework uses to recycle “dead” or unused objects from memory and recycle the space. By default the Garbage Collector is set to “Workstation” Mode. That means the Garbage collector will be efficient on a machine with a single processor and little RAM. This is usually the case on most developer PCs. However, when we deploy our applications to the server we usually have hugely powerful servers that have multiple cores and gigs of RAM. On these servers we should enable the Garbage Collection to run on Server Mode. The application will be more CPU and RAM intensive but the garbage collection will be a lot more responsive and active in monitering the objects currently in memory. To do this, in your web.config you need to add the following section:

<configuration>
   <runtime>
      <gcServer enabled="true"/>
   </runtime>
</configuration>

Why should you enable this though? How does it benefit your application? It comes down to the performance of your application on the server. Not how quick your page loads, but how well your application handles large volumes of traffic without your application falling over and dying. Here’s why! Server Garbage Collection creates one GC heap per processor, which are collected in parallel. This GC mode maximizes the number of requests per second. So imagine having a server with 4 gigs of RAM and a quad core CPU, your application would be able to withstand much larger amounts of traffic without the application running over of memory! Effectively, on a quad core CPU, you would have 4 Garbage Collectors working in unison!

C#: TinyUrl conversion code

I am currently working on a small project using ASP.Net MVC and I want to incorporate a TinyUrl facility such as that of www.tinyurl.com and the million other clones there are. I found this awesome piece of code that does the trick beautifully! I found the code @ http://blogs.msdn.com/bramveen/archive/2009/01/06/converting-url-to-tinyurl-in-c.aspx

It was really quick to implement and works really nicely.

protected string ToTinyURLS(string txt)
{
    Regex regx = new Regex("http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);

    MatchCollection mactches = regx.Matches(txt);

    foreach (Match match in mactches)
    {
        string tURL = MakeTinyUrl(match.Value);
        txt = txt.Replace(match.Value, tURL);
    }

    return txt;
}

public static string MakeTinyUrl(string Url)
{
    try
    {
        if (Url.Length <= 12)
        {
            return Url;
        }
        if (!Url.ToLower().StartsWith("http") && !Url.ToLower().StartsWith("ftp"))
        {
            Url = "http://" + Url;
        }
        var request = WebRequest.Create("http://tinyurl.com/api-create.php?url=" + Url);
        var res = request.GetResponse();
        string text;
        using (var reader = new StreamReader(res.GetResponseStream()))
        {
            text = reader.ReadToEnd();
        }
        return text;
    }
    catch (Exception)
    {
        return Url;
    }
}

Hope this can as useful to you as it was for me!

Convert LiNQ resultset to DataTable

When the LiNQ to SQL framework was originally released in BETA there was a built in extension method to convert the LiNQ result to either a DataTable or DataSet if I remember correctly. However when it came to release this disappeared for some strange reason.

Now I’m sure MS had their reasons for removing it but I don’t care and want it back ;) So I’ve written a little extension method to convert the LiNQ resultset to a DataTable using a bit of Reflection. Here’s the code and enjoy! As always, I take no responsibility for its usage ;)

/// <summary>
/// Converts an IEnumerable type collection into a DataTable
/// </summary>
/// <param name=”collection”>Collection type that implements IEnumberable</param>
/// <returns>Datatable representing IEnumerable collection</returns>
public static DataTable ToDataTable<T>(this IEnumerable<T>collection)
{
// Create DataTable to Fill
DataTable _newDataTable = new DataTable();

// Retrieve the Type passed into the Method
Type _impliedType = typeof(T);

//Get an array of the Type’s properties
PropertyInfo[] _propInfo = _impliedType.GetProperties();

//Create the columns in the DataTable
foreach (PropertyInfo pi in _propInfo)
{
_newDataTable.Columns.Add(pi.Name, pi.PropertyType);
}

//Populate the table
foreach (T item in collection)
{
DataRow _newDataRow = _newDataTable.NewRow();
_newDataRow.BeginEdit();

foreach (PropertyInfo pi in _propInfo)
{
_newDataRow[pi.Name] = pi.GetValue(item, null);
}

_newDataRow.EndEdit();
_newDataTable.Rows.Add(_newDataRow);
}

return _newDataTable;
}

Encrypting SQL connection string

This is something that is so easy to configure yet I’ve seen it countless times where projects are deployed and the connection string in the web.config file is not encrypted. Regardless of how small your application is, it poses a challenge to someone somewhere to try break into it. Here I’ll show you something most people don’t even know about and depending on your code in your projects Data Access Layer you might not even need to change your code at all!

ASPNET_regiis:

When you initially install the .Net Framework, if you look carefully, you’ll see this little executable run. The aspnet_regiis executable is there to register the ASP.Net runtimes with IIS6 and you can use this to install Sql Server State Management on a web application. There is however some very interesting other things this little executable can do for you. One of which being automatically encrypting and decrypting your connection string in your website’s web.config file.

Encryption time:

Say for instance you have the following connection string in your web.config file. From this, your attacker would know exactly where your database server is located as well a valid username and password.

<configuration>
<connectionStrings>
<add name=”SqlConn” connectionString=”Server=dbServer; Database=pubs;
User Id=usrName; password= p4ssw0rd” providerName=
“System.Data.SqlClient” />
</connectionStrings>
</configuration>

To make sure your SQL location and account credentials stay secret, you should encrypt the connection string in the web.config file using the Aspnet_regiis utility with at least the Windows Data Protection API (DPAPI) protected configuration provider. By executing the following command in your Visual Studio Command Prompt, you will have successfully encrypted your connection string!

aspnet_regiis -pe “connectionStrings” -app “/WebApp” –prov “DataProtectionConfigurationProvider”

Just remember that this command is cAsE SeNsItIve. Remember to set /WebApp to the virtual path to your application.

Decrypting the Connection String:

This is the easiest part of all. When you retrieve your connection string from the web.config file, this is how you should do it:

string dbConn = ConfigurationManager.ConnectionString["SqlConn"].ToString();

By doing it this way, ASP.Net will automatically decrypt the connection string for you! This is recommended as a Best Practice by Microsoft and it is incredibly easy to implement. There is no excuse to not implement such basic security in your web based applications.