Author Archives: FailBoy

9 Google Wave invites up for grabs

First 9 people to comment on this post get a Google Wave invite.

In all honestly, Wave isn’t that awesome yet. Maybe with a higher adoption it’ll take off.

UPDATE: Once I invite you, Google has to approve the invite and send it to you. This sometimes takes a few days

Difference between a Junior and Senior Developer

This topic came up in the office today and one of our senior developers indicated the following:

A Junior developer says: “It works on my machine”.
A Senior developer says: “Its working fine on the production server”.

I feel that is particularly apt

C# has an ISNULL function, its called ??

Just a very short and quick post. For a while now .Net has had nullable types. Take for example an integer, instead of declaring it as:

int x = 0;

you declare it as:

int? x = 0;

Now in coding examples all over the web I’m seeing the same logic and its driving me nuts!

if(x == null){
    x = -1;
}

There is a much shorter route and that is:

x = x ?? -1;

The “??” operator works exactly the same way an ISNULL function call works in SQL. It evaluates the variable on the left of the operator to ensure its not null (or undefined as some people call it), and if it is, it uses the value on the right of the ?? operator. Quick and easy.

LINQ: Distinct method

Ah the beauty of LINQ. I previously did a post on How to use Lambda Expressions and if you aren’t sure now how to use them, is the time to check it out. I have decided to have a good look at the Methods available to IEnumerable collections and first on the list the DISTINCT method.

The Boring Standard Method:

The Distinct method removes any duplicate entries in a collection without you needing to do much work, the same as the DISTINCT keyword inT-SQL. Here is the basic and standard use that is really not difficult to understand.

string[] names = new string[] { "Peter", "Paul", "Mary", "Peter", "Paul", "Mary", "Janet" };

foreach (string _name in names.Distinct())
{
Console.WriteLine(_name);
}

So like I said, easy enough, we have a string array with names and by using the .Distinct method we remove any duplicates from the resultset that is returned. Now comes the real fun!

Custom Distinct Implementation:

Since the advent of generics, most of us have been creating strongly typed lists of data. Plain example would be a list of our customer UserClass.

public class Users
{
public int ID {get; set;}
public string Name {get; set;}
public int AwesomeScore {get; set;}
}

// Create and populate new list of Users
List<Users> failBoyUsers = new List<Users>();
failBoyUsers.Add(new Users { AwesomeScore = 7, Name = "FailBoy", ID = 1 });
failBoyUsers.Add(new Users { AwesomeScore = 10, Name = "Rathlan", ID = 2 });
failBoyUsers.Add(new Users { AwesomeScore = 10, Name = "Rathlan", ID = 2 });
failBoyUsers.Add(new Users { AwesomeScore = 7, Name = "Joe", ID = 3 });
failBoyUsers.Add(new Users { AwesomeScore = 7, Name = "Joe", ID = 3 });
failBoyUsers.Add(new Users { AwesomeScore = 7, Name = "Joe", ID = 3 });
failBoyUsers.Add(new Users { AwesomeScore = 1, Name = "newbie", ID = 4 });

This would then give us a “strongly typed Array” of our User class. If we now had to call the .Distinct function on the collection it wouldn’t work! Thats because the CLR does not know what to evaluate to decide whether an entry is unique or a duplicate so it returns all the items including the duplicates. The Distinct method accepts an overload paramter, this object must implement the IEqualityComparer interface. So we declare a new class and implement IEqualityComparer as follows:

public class AwesomeComparer : IEqualityComparer<Users>
{
public bool Equals(Users x, Users y)
{
if (x == null || y == null)
return false;
else
return (x.Name.ToLower() == y.Name.ToLower() &&
x.AwesomeScore == y.AwesomeScore &&
x.ID == y.ID);
}

public int GetHashCode(Users obj)
{
return obj.Name.GetHashCode();
}
}

so what we do in the Equals Method is define what we feel a duplicate of our custom class looks like. We also implement the GetHashCode method to return the hash of the “primary field”. This will usually be the Primary Key that you class will be based on. Then we implement our Distinct method, we do so as follows:

AwesomeComparer awesomeComparer = new AwesomeComparer();

foreach (Users usr in failBoyUsers.Distinct(awesomeComparer))
{
Console.WriteLine(usr.ID.ToString() + " - " + usr.Name + " - " + usr.AwesomeScore.ToString());
}

And that will only return Distinct values from our custom class! I hope this helps someone at some stage as I never knew about this myself and stumbled onto it. Drop me a comment if you think I suck or if my some margain of luck I managed to produce some bug free code, I am after FailBoy for a reason :P

How to use Lambda Expressions

Until I recently started working at Chase Software I hadn’t really dived to deep into the C# 3.0 features. I really wish I had though because man it would’ve cut down so much code at my previous job. A colleague of mine has taught me so much that I am now looking a lot deeper into C# 3 features. Just in time before C# 4.0 is released! One of the first things I learned to get the hang of is Lambda expressions. Lambdas are inline expressions. These expressions are mainly used in conjunction with LiNQ and thus mostly on IQueryable and IEnumerable collections. Here is an example on how it can cut a lot of code out of you work.

Assume we have a basic class that contains a Name, ID and AwesomeScore for Users.

public class Users
{
public int ID {get; set;}
public string Name {get; set;}
public int AwesomeScore {get; set;}
}

So as you can see there’s nothing difficult about that. Its a basic class definition. So lets create a basic console application and fill a List of Users so we can work with that:

public static void Main(string[] args)
{
// Create and populate new list of Users
List<Users> failBoyUsers = new List<Users>();
failBoyUsers.Add(new Users { AwesomeScore = 7, Name = "FailBoy", ID = 1 });
failBoyUsers.Add(new Users { AwesomeScore = 10, Name = "Rathlan", ID = 2 });
failBoyUsers.Add(new Users { AwesomeScore = 9, Name = "Joe", ID = 3 });
failBoyUsers.Add(new Users { AwesomeScore = 1, Name = "newbie", ID = 4 });
}

So here we create a Generic List Collection of Users. So our failBoyUsers collection now contains 4 users with varying scores. Now, originally before the wonders of learning how to use Lambda’s, I would’ve done the following to return the users with an AwesomeScore of 8 or over:

public static List GetAwesomestPeople(List<Users> usersToSort)
{
List<Users> returnList = new List<Users>();

foreach (Users userItem in usersToSort)
{
if (userItem.AwesomeScore >= 8 )
{
returnList.Add(userItem);
}
}

return returnList;
}

So yeah, that was me, FailBoy being very intelligent. Now, that same functionality using Lambda’s.

public static IQueryable GetAwesomestPeopleLAMBDA(IQueryable usersToSort)
{
return usersToSort.Where(user => user.AwesomeScore >= 8).AsQueryable();
}

Thats right! Using Lambda’s its a single line. So lets look at that line, I pass in the usersToSort as IQueryable instead of the List. Converting from the List to IQueryable is as easy as passing the List parameter in and simply adding .AsQueryable() to the end of the parameter name! So it would be called as :

IQueryable awesomeOkes = GetAwesomestPeopleLAMBDA(failBoyUsers.AsQueryable());

Then I use the .Where() method which is an extension method on the IQueryable collection class and as such on the List<> class since List<> inherits from IEnumerable and IEnumerable inherits from IQueryable. The fun comes in where I pass the argument into the .Where() method.

user => user.AwesomeScore >= 8

Here I am declaring a new variable called user. The variable is an instance of the Collection we want to sort, in this case usersToSort. the “=>” is what is referred to as the Lambda operator. After the Lambda operator we specify our condition. In this as we only want the users with an AwesomeScore of 8 or higher. I then append the

.AsQueryable()

because we want to return the resultset as an IQueryable Collection of Users.

Using Lambda’s I’m condensed 9 lines of code into 1 line of code. And the less you need to code, the more time you save! I hope this is helpful to you! I’ve included the full code below.

FailBoy

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.