Monthly Archives: May 2009

Unable to launch the ASP.NET Development server because port is in use.

Bumped into an interesting problem today. My ASP.Net Development server would not start because the port was apparently in use. I though this was very strange and tried another port, and this one was also in use. Starting to suspect spyware I was getting worried. I finally remember that I had installed ESET NOD32 Antivirus.

ESET comes with a little HTTP firewall as well. So easy right? Just disable the firewall, WRONG!!! Error was still occuring. So after googling for a bit I found my problem. I was right, ESET was to blame, but I hadn’t approached the situation from correct angle. To fix the situation you need to add Visual Studio to a “safe list” so that ESET doesn’t block it.

To unblock Visual Studio do the following: open ESET and click setup -> advanced firewall setup -> antivirus & anti spyware -> web access protection -> HTTP -> webbrowsers. ESET will then show a list of Applications, find VS2008/2005 in the list and deselect it. Save your changes and close the setup window.

And there we go, VS2008′s buildt in Dev Server will now work again!

Set Forms Authentication Path dynamically

Lets say we have IIS with a default website and two Virtual Directories, both containing an instance of an application. So when a user logs into Instance A and then into Instance B, he is then logged out of Instance A. In testing I saw that if I hardcoded the path attribute on the forms tag under authentication in the web.config then the systems would work fine and not effect each other. So I set about trying to set the path dynamically but I was doing it all over and it wasn’t working.

My stupidity lead me into trying to set the Path on each cookie. That, however,  wasn’t the problem. A Colleague of mine found the solution this morning though. After we log the user into the system we fire the following code:

FormsAuthentication.RedirectFromLoginPage(authToken, true);

However the RedirectFromLoginPage does take a 3rd parameter which will be the path that I’ve been trying to set. So now the code reads:

string applicationBasePath = Request.ApplicationPath;
FormsAuthentication.RedirectFromLoginPage(authToken, chkRememberMe.Checked, applicationBasePath);

So once that was done everything worked like a charm!

Enumerable methods .All() and .Where()

Today I made one of my classic mistakes. I didn’t *READ* the MSDN documention on an Extension Method in its entirety. I was discussing some Enumerable extension methods with a friend and looked up the .All() extension method.

Instead of reading all of the code I read how the code was implemented and jumped to some conclusions. I sat ranting about how .All() and .Where() do exactly the samething and how silly that is. Once I actually sat down and read the examples properly I saw the very obvious difference. Here is the difference between the methods though.

.All()

The Enumerable.All() method determines whether all elements of a sequence satisfy a condition according to its MSDN entry. When using this it would be implemented as follows:

users.All(user => user.Name.StartsWith("B"));

This would return a boolean value *ONLY* if all the entries in our users Enumerable had a user.Name starting with the letter “B”.

.Where()

The Enumerable.Where() method filters a sequence of values based on a predicate according to its MSDN entry. When using this it would be implemented as follows:

IEnumerable query = users.Where(user => user.Name.StartsWith("B"));

This would return all the records where the user’s name starts with “B”

I am FailBoy

This is exactly why I have been named FailBoy. So often I only read parts of something and jump to conclusions. The lesson learnt, READ the manual and don’t jump to conclusions!

SqlParameter is already contained by another SqlParameterCollection

I discovered an interesting bug today. While executing some SQL Stored Procedures via C# I was trying to reuse a SqlParameter. However, when the SqlParameter was added to a second SqlCommand, it would throw an error when trying to execute the second command. The error encountered was the “SqlParameter is already contained by another SqlParameterCollection“.

It seems that .Net’s garbage collection retains a reference to the SqlParameter used in the first SqlCommand. This reference seems to survive the closing and even disposing of the connection in use. As long as the SqlCommand object is in use, .Net seems to remember that it has already been used. To bypass this, simply call the sqlCommand.Parameters.Clear() method. You’ll need to readd the SqlParameter or SqlParameter[] to the SqlCommand and it’ll work.

Procedure expects parameter ‘@statement’

Recently I was working on a script to upgrade a database and was using some dynamic T-SQL to execute a command. I kept getting the error “Procedure expects parameter ‘@statement’ of type ‘ntext/nchar/nvarchar’”. Being true to my name (“FailBoy”) I knew I was doing something stupid. In my SQL Script I had declared something like this:

DECLARE @tSql VARCHAR(max)
SET @tSql = ‘<insert Dynamic query here>’
execute sp_executesql @tSql

Can you spot the problem? The problem is the declaration of the variable as VARCHAR. The execute sp_executesql procedure expects a NVARCHAR value. I simply replaced the VARCHAR with NVARCHAR and all worked perfectly.

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.