Peter Petrov’s Weblog

var me = from practice in programming where practice.IsBestPractice && practice.UseLambda select practice.OptimalPerformance;

SQL Server 2008 Management Studio – Rename column & Intellisense August 8, 2008

Filed under: SQL — ppetrov @ 5:41 pm
Tags: , , ,

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

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


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

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)
                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

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.


Useful method – 7 of N – Ignore case on String.Replace() June 27, 2008

Filed under: .NET Framework,C# — ppetrov @ 3:51 pm
Tags: , , ,

I’ve posted a method to determine if a string contains another string ignoring the case. I’ve also looked all string methods and I’ve found Replace isn’t available in a ignore case variant. I’ve created the missing overload(using an extension methods).

public static string Replace(this string original, string oldValue, string newValue, StringComparison comparisionType)
 if (oldValue == null)
 throw new ArgumentNullException("oldValue");
 if (newValue == null)
 throw new ArgumentNullException("newValue");

 var result = original;

 if (oldValue != newValue)
 int index = -1;
 int lastIndex = 0;

 var buffer = new StringBuilder();

 while ((index = original.IndexOf(oldValue, index + 1, comparisionType)) >= 0)
 buffer.Append(original, lastIndex, index - lastIndex);

 lastIndex = index + oldValue.Length;
 buffer.Append(original, lastIndex, original.Length - lastIndex);

 result = buffer.ToString();
 return result;

UPDATE : I’ve updated the method to allow newValue to be string.Empty. It will perform like a remove method. WordPress source code posting is broken 😦


Useful method – 6 of N – Ignore case on String.Contains()

Filed under: .NET Framework,C# — ppetrov @ 12:39 pm
Tags: , , ,

The easiest way to see if a String contains another string is to use the method Contains().

The documentation has Remarks

This method performs an ordinal (case-sensitive and culture-insensitive) comparison. The search begins at the first character position of this string and continues through the last character position.

But what if we want a case-insensitive comparison? The answer is simple – we can use IndexOf(). The problem is the name of the method isn’t as intuitive as Contains() is(Contains calls IndexOf under the hood). To create a little comfort I’ve wrapped the IndexOf() call to an extension method which will determine if a string contains another string ignoring the case.

public static bool Contains(this string original, string value, StringComparison comparisionType)
    return original.IndexOf(value, comparisionType) >= 0;

In fact we pass StringComparison as parameter so it’s easy to specify the culture and the case.


Don’t use .ToUpper() or .ToLower()

Filed under: .NET Framework,C# — ppetrov @ 11:36 am
Tags: , , ,

I’ve seen on many code snippets and posts an inadequate use of ToUpper() and ToLower() methods of the string class. It’s a well know fact that string is immutable and these methods will return a copy of the original string.

A String object is called immutable (read-only) because its value cannot be modified once it has been created. Methods that appear to modify a String object actually return a new String object that contains the modification.

If you need to compare two strings ignoring the case, we must use the static method Equals()

string.Equals("abc", "ABC", StringComparison.OrdinalIgnoreCase)

or the instance one.

"abc".Equals("ABC", StringComparison.OrdinalIgnoreCase)

StartsWith(), EndsWith(), IndexOf() etc – all of these methods provide a way to specify the
StringComparison type.
An interesting method is Contains(). There’s no way to specify the StringComparison type or to say ignoreCase = true.
Actually it’s an alias for IndexOf(). In Reflector we can see the following implementation

public bool Contains(string value)
    return (this.IndexOf(value, StringComparison.Ordinal) >= 0);

To fill this gap I’ve decided to write an extension method with an additional parameter

        public static bool Contains(this string original, string value, StringComparison comparisionType)
            return original.IndexOf(value, comparisionType) >= 0;

Now we can use it like this

"abc".Contains("AB", StringComparison.OrdinalIgnoreCase)

I think it’s a useful method so I’ll post this extension method as a separate post.