Free Typemock licenses – ASP.NET bundle launch

•May 19, 2009 • Leave a Comment

Today I’ve read this Get Free Typemock licenses – ASP.NET bundle launch on the official Typemock blog. I thought to myself : Is it possible for me to win a FREE license ? Why not. After all it’s Typemock and it’s an official blog post.  I hope I’ll be in the group of these 60 lucky bloggers. I need to hurry :)

Unit Testing ASP.NET? ASP.NET unit testing has never been this easy.

Typemock is launching a new product for ASP.NET developers – the ASP.NET Bundle – and for the launch will be giving out FREE licenses to bloggers and their readers.

The ASP.NET Bundle is the ultimate ASP.NET unit testing solution, and offers both Typemock Isolator, a unit test tool and Ivonna, the Isolator add-on for ASP.NET unit testing, for a bargain price.

Typemock Isolator is a leading .NET unit testing tool (C# and VB.NET) for many ‘hard to test’ technologies such as SharePoint, ASP.NET, MVC, WCF, WPF, Silverlight and more. Note that for unit testing Silverlight there is an open source Isolator add-on called SilverUnit.

The first 60 bloggers who will blog this text in their blog and tell us about it, will get a Free Isolator ASP.NET Bundle license (Typemock Isolator + Ivonna). If you post this in an ASP.NET dedicated blog, you’ll get a license automatically (even if more than 60 submit) during the first week of this announcement.

Also 8 bloggers will get an additional 2 licenses (each) to give away to their readers / friends.

Go ahead, click the following link for more information on how to get your free license.

Stop posting images of the code, post the code !

•April 14, 2009 • Leave a Comment
Windows Vista Source Code

Windows Vista Source Code

First there is no Copy/Paste so the reader can’t easily copy the code to try it and/or test it.

Second there is no search available on the page.

Third for a search engines it’s impossible to mine the data represented by the image. You won’t have a match event if the user keywords perfectly match your (image)contents.

ForEach method on IEnumerable

•January 22, 2009 • 3 Comments

I’ve noticed that when I use IEnumerable<T> very often I have a construction like this

.ToList().ForEach(x=> ...)

in my code. I’ve thinked about it and I’ve realized that ToList() will create (probably) a large list just to iterrate over it and perform some action. That’s just because IEnumerable<T> doesn’t have ForEach method. Using an extension method I’m able to fill this gap. So here’s the ForEach method on IEnumerable<T> :

public static void ForEach<T>(this IEnumerable<T> values, Action<T> action)
{
    foreach (var v in values)
    {
        action(v);
    }
}

It’s possible to return the values reference to allow method chaining  but personally I think the foreach must be the last thing to perform, otherwise it will lead you to a bad practice. Let me explain what I mean. Imagine we have this Person class and a method that returns all Persons.

public static IEnumerable<Person> GetAllPersons()
{
    // ...
    yield break;
}
public class Person
{
    public long Fortune { get; private set; }

    public void SlowMethod()
    {
        Thread.Sleep(1000);
        // ...
    }
}

Take a look a the fowling two methods that retrieves all rich persons

var richPersonsSlow = GetAllPersons().ForEach(p => p.SlowMethod()).Where(p => p.Fortune > 1000000);
var richPersonsFast = GetAllPersons().Where(p => p.Fortune > 1000000).ForEach(p => p.SlowMethod());

Take this scenario : we have 3600 persons and only one have more then one million.

The first line will take an hour to return the millionaire.

The second line will take only one second to return the millionaire because p.SlowMethod will be called only on the millionaire.

There’s a little semantic difference in the example but I think you get the point. Using the ForEach returning void eliminates this possible issue.

I hope the BCL Team will include this method (not necessarly my implementation) in C# 4.0 .

SCOPE_IDENTITY() vs @@IDENTITY – 1:0

•September 19, 2008 • Leave a Comment

@@IDENTITY returns the most recently created identity for your current connection, not necessarily the identity for the recently added row in a table. Always use SCOPE_IDENTITY() to return the identity of the recently added row.

Usuful methods – 11 of N – Copy/Move Directory

•September 12, 2008 • 2 Comments

Today I have to copy an entire directory including all files, sub directories and all sub files to another directory. The .NET framework doesn’t provide such method (at least I don’t know of it) so I have coded one myself. Here’s the implementation of the CopyDirectory method.

        public static void CopyDirectory(string source, string destination)
        {
            if (destination[destination.Length - 1] != Path.DirectorySeparatorChar)
            {
                destination += Path.DirectorySeparatorChar;
            }
            if (!Directory.Exists(destination))
            {
                Directory.CreateDirectory(destination);
            }
            var entries = Directory.GetFileSystemEntries(source);
            foreach (var e in entries)
            {
                if (Directory.Exists(e))
                {
                    CopyDirectory(e, destination + Path.GetFileName(e));
                }
                else
                {
                    File.Copy(e, destination + Path.GetFileName(e), true);
                }
            }
        }

MoveDirectory is very simple when we have CopyDirectory. I know it’s not as fast as it can be ( if we use File.Move()) but still it gets the job done.

        public static void MoveDirectory(string source, string destination)
        {
            CopyDirectory(source, destination);
            Directory.Delete(source);
        }

SQL Server 2008 – FILESTREAM feature is disabled.

•August 15, 2008 • 9 Comments

Yesterday I have installed SQL Server 2008. I have downloaded the product samples from codeplex and I have tried to restore the Adventure Works 2008 Sample Database but I’ve this error :

System.Data.SqlClient.SqlError: FILESTREAM feature is disabled. (Microsoft.SqlServer.Smo)

OK the FILESTREAM is disabled but the question is how can I enable it ? The solution is very simple but it took me some time to find in on google. Here’s the link to the SQL Server 2008 Books Online on MSDN – How to: Enable FILESTREAM

Just fire SQL Server 2008 Management Studio and type

EXEC sp_configure filestream_access_level, 2
RECONFIGURE

I don’t know why Microsoft doesn’t provided this link as help. Instead of this they suggested m

ADDITIONAL INFORMATION:

System.Data.SqlClient.SqlError: FILESTREAM feature is disabled. (Microsoft.SqlServer.Smo)

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.0.1600.22+((SQL_PreRelease).080709-1414+)&LinkId=20476

which is useless.

The final result is that I have FILESTREAM enabled and I have my AdventureWorks 2008 database restored.

Now I can continue with my tests.

SQL Server 2008 Management Studio – Rename column & Intellisense

•August 8, 2008 • 3 Comments

Yesterday when I have played around with SQL Server 2008 Management Studio(SSMS) RC0. I have spotted a bug and I have filed a bug report. The new SSMS has Intellisense but it isn’t invalidated when you rename a column. When we fire SSMS and write a simple query everything is correct.

When I rename the column from Name to RoomName the Intellisense isn’t updated.

As you can see the column name is RoomName but Intellisense still proposes Name.

The Query editor is also not refreshed as shown above.

It says “Invalid column name” when the it’s perfectly valid. Note that the parse command completed successfully (as expected). The query runs with no problems.

I hope it will be fixed in the final release.

Usuful methods – 10 of N – Dictionary with unique values

•July 4, 2008 • Leave a Comment

The .NET Dictionary<TKey, TValue> is a great class.

MSDN:

The Dictionary<(Of <(TKey, TValue>)>) generic class provides a mapping from a set of keys to a set of values. Each addition to the dictionary consists of a value and its associated key. Retrieving a value by using its key is very fast, close to O(1), because the Dictionary<(Of <(TKey, TValue>)>) class is implemented as a hash table

I’m using this class very often. I’m not going to explain when to use a dictionary, an array, a sorted array or a tree or any other data structures – there is a lot of articles on this subject on the net. Instead I’ll extend the class and I’ll constraint the set of values to be unique which will give us a one-to-one mapping.It’s a very simple thing to do.

public class UniqueValuesDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
    public new void Add(TKey key, TValue value)
    {
        if (this.Values.Count > 0)
        {
            bool hasDuplicates = this.Values.Contains(value);
            if (hasDuplicates)
            {
                throw new ArgumentException("An element with the same value already exists.");
            }
        }
        base.Add(key, value);
    }
}

And here’s an example which demonstrates how this class will help us find errors

            var lookup = new Dictionary<int, string>();
            lookup.Add(1, "One");
            lookup.Add(2, "One");   // No exception as expected

            var uniqueLookup = new UniqueValuesDictionary<int, string>();
            uniqueLookup.Add(1, "One");
            uniqueLookup.Add(2, "One"); // Here we'll get an exception

Usuful methods – 9 of N – Count string occurences

•July 2, 2008 • Leave a Comment

One more extension method(hopefully useful) on String.  If we want to count how many times a string contains another string this method will help us.

    public static int CountOccurences(this string original, string value)
    {
        return original.CountOccurences(value, StringComparison.CurrentCulture);
    }

    public static int CountOccurences(this string original, string value, StringComparison comparisionType)
    {
        return GenericCountOccurences(original, value, comparisionType, value.Length);
    }

    public static int CountOverlapOccurences(this string original, string value)
    {
        return GenericCountOccurences(original, value, StringComparison.CurrentCulture, 1);
    }

    public static int CountOverlapOccurences(this string original, string value, StringComparison comparisionType)
    {
        return GenericCountOccurences(original, value, comparisionType, 1);
    }

    private static int GenericCountOccurences(string original, string value, StringComparison comparisionType, int step)
    {
        int occurences = 0;

        if (!string.IsNullOrEmpty(original))
        {
            int foundIndex = original.IndexOf(value, 0, comparisionType);
            while (foundIndex >= 0)
            {
                occurences++;
                foundIndex = original.IndexOf(value, foundIndex + step, comparisionType);
            }
        }

        return occurences;
    }

We have two versions – simple and overlapping.
When we use the simple version like this

            var input = "aaaa";
            var count = input.CountOccurences("aa");

we’ll have count = 2.
When we use the overlapping one on the same input

            var input = "aaaa";
            var count = input.CountOverlapOccurences("aa");

we’ll have count = 3.

That’s because the search of the next occurrence begins right after the start of the match and in the other version the search begins after the end of the previous match.

Note: I’m sure my colleague and friend Vlado will appreciate this ;)

Useful method – 8 of N – String Capitalize First (ToTitleCase)

•June 30, 2008 • 1 Comment

I’ve wanted to rename a lots of files. I’ve also wanted the name of the files to follow my convention to capitalize every first letter. I couldn’t find such functionality in the string class. I’ve googled and I’ve found the TextInfo class and ToTitleCase method. It gets the job done and perfectly suits me needs.

Here’s how we can use it

TextInfo ti = Thread.CurrentThread.CurrentCulture.TextInfo;
string name = "petar petrov - XML developer";
string properName = ti.ToTitleCase(name);
// properName = "Petar Petrov - XML Developer"

Note that the XML isn’t transformed to Xml which is the correct behavior for me.