Wednesday, December 23, 2009

System Threading - Lamda Expression

I was writing a small little app and wanted to start threads without having to declare a standalone handles for the ThreadStart. Lamda Expression came in pretty handy.

new System.Threading.Thread( new System.Threading.ThreadStart(() =>
{
Code
})).Start();

Wednesday, April 15, 2009

Visual Studio Toolbox control issues

I was facing some weird issues with the Toolbox in Visual Studio 2008 running under Vista. I wanted to find out where it was storing the toolbox data. Finally after some research found the location. Just wanted want to throw it out there. In my case after deleting all the *.tbd files under the "C:\Users\\AppData\Local\Microsoft\VisualStudio\9.0 and let VS create new ones all the headaches got resolved.

In all the other operating systems it is located in the C:\Documents and Settings\\Local Settings\Application Data\Microsoft\VisualStudio\9.0 folder.

If you have different versions of Visual Studio like 2005 or 2003 (hope fully not this), the 9.0 will be 8.0 or below.

Friday, April 03, 2009

Breaking long running strings (line breaks)

I wrote this snip while ago for one of my oracle friends to break long running strings. Today I was in need of it again and I had to go through my library to find it. I am sure there is huge room for improvement. The job of the below code is to snip each paragraph using the max length into smaller strings.

public static string WrapText(string text, int maxLength)

{

// validate the incoming text

if (string.IsNullOrEmpty(text))

return text;



// break the string into smaller parts

string[] StringArray = System.Text.RegularExpressions.Regex.Split(

text,

"[\n]",

RegexOptions.Compiled RegexOptions.Multiline RegexOptions.Singleline RegexOptions.IgnoreCase);



// holds the string lines

List<string> StringLines = new List<string>();



// iterate through the array

foreach (string s in StringArray)

{

// the line is less then the allowed length

// add to the StringLines colleciton

if (s.Length <= maxLength)

StringLines.Add(s);

else

{

// longer string, so we use the start index to do our work

int StartIndex = 0;



// while loop breaking the long string

while (StartIndex <= s.Length)

{

// end index

int EndIndex = StartIndex + maxLength;



// trap for end index becoming longer than start index

if (EndIndex > s.Length)

{

// add to the StringLines colleciton

StringLines.Add(s.Substring(StartIndex, s.Length - StartIndex - 1));

break;

}

else

{

// character at end index position

string CharAtPosition = s[EndIndex].ToString();



// the character is not a space and not a (.) period

if (CharAtPosition != " " && CharAtPosition != ".")

{

// back track to find a space

// it is expected there will be a space at the end of a sentence

while (CharAtPosition != " " && EndIndex >= 0)

{

// trap in case it is a long word/url or something

if (EndIndex == 0)

break;



EndIndex = EndIndex - 1;

CharAtPosition = s[EndIndex].ToString();

}



// if end index becomes 0, then we need to take

// whatever is available

if (EndIndex == 0)

EndIndex = s.Length - 1;

}



// calculate the length we are going to take the snip and make the snip

int SubEndLenth = EndIndex - StartIndex;

StringLines.Add(s.Substring(StartIndex, SubEndLenth));



// increment the start index for the next request

StartIndex += SubEndLenth;



// if char at the position was a space, increment the start index by 1

// this is necessary becuase the next line will end up with a space as the starting charcter

if (CharAtPosition == " ") StartIndex += 1;

}

}

}

}

return string.Join("\r\n", StringLines.ToArray());

}

Thursday, January 10, 2008

Using ArrayList and Generic List<> in .NET 2.0 Framework (Part 1)

There are several articles in the web regarding Generics (System.Collections.Generics). Being I use these objects extensively, I thought I would put my two cents and blog on these objects.

The objects we are going to do a quick look at are "System.Collections.ArrayList" and "System.Collections.Generics.List<>". These two objects are very similar in nature, except for the Generics List which is strongly typed objects. Between the two objects, the biggest advantage List object is that it do not require type casting being it is declared with a specific type. This allows us to simply skip the type casting of objects which is required in the "ArrayList". Lets us look at the objects more in detail below.

Lets create a simple class called “MyClass”. We will use this class for our type declarations.

class MyClass
{
public string FirstName;
public string LastName;
public int Age;

public MyClass() { }

public MyClass(string firstName, string lastName, int age)
{
FirstName = firstName;
LastName = lastName;
Age = age;
}
}

ArrayList to create the collection, and see how we could use it normally in code. As you see below, to retrieve the value of the "FirstName" from the instance, we will have to first cast the object and then request the value from the "FirstName" field.

// Init
ArrayList MyList = new ArrayList();

// Add items to collection
MyList.Add(new MyClass("Bob", "Know", 25));
MyList.Add(new MyClass("John", "Doe", 30));
MyList.Add(new MyClass("Bill", "Masters", 25));

// using the object
// retrieve First Name from the second instance of the object
string FirstName = ((MyClass)MyList[1]).FirstName;

With Generics, we can retrieve the value of the "FirstName" from the instance directly. This would avoid any performance issues that may be involved during type casting of the object. Generics also provide the same advantages as the "ArrayList," and several additional advantages that normally requires additional coding if we wish to perform common tasks. Below are several simple tasks using in-built methods.

// Init
List<MyClass> MyClassList = new List<MyClass>();

// Add items to collection
MyClassList.Add(new MyClass("Bob", "Know", 25));
MyClassList.Add(new MyClass("John", "Doe", 30));
MyClassList.Add(new MyClass("Bill", "Masters", 25));

// using the object
// retrieve First Name from the second instance of the object
string FirstName = MyClassList[1].FirstName;


1. Creating a new collection using another collection

This option is available in both "ArrayList" and generic "List". Let us start by creating a simple array of "MyClass" called "MyClassArray".

// Init
MyClass[] MyClassArray = new MyClass[3];

// Add items to collection
MyClassArray[0] = new MyClass("Bob", "Know", 25);
MyClassArray[1] = new MyClass("John", "Doe", 30);
MyClassArray[2] = new MyClass("Bill", "Masters", 25);
System.Collections.ArrayList
// Init
ArrayList MyClassList = new ArrayList(MyClassArray);
System.Collections.Generics.List<>
// Init
List<MyClass> MyClassList = new List<MyClass>(MyClassArray);

As we notice above, we are passing in the "MyClassArray" as a parameter in the object's constructor, which will automatically copy the the items in the array to the "ArrayList" or the generic "List" object. The constructor also has the same option to declare the objects with the capacity by passing in the integer.



2. Using the "AddRange" method

This method allows you to append a collection into an already instantiated object.

System.Collections.ArrayList
// Init
ArrayList MyClassList = new ArrayList();
MyClassList.AddRange(MyClassArray);
System.Collections.Generics.List<>
// Init
List<MyClass> MyClassList = new List<MyClass>();
MyClassList.AddRange(MyClassArray);


3. Using the "BinarySearch" method


This method allows you to find the index of first available item that matches the criteria. In this scenario, I want to compare the FirstName. Below is the simple ICompare class that I will use in my scenario.

// compare class
public class FirstNameCompare : IComparer
{

public int Compare(object x, object y)
{

MyClass S1 = (MyClass)x;
MyClass S2 = (MyClass)y;
return -string.Compare(S1.FirstName, S2.FirstName);

}

}
// create search class
MyClass SearchObject = new MyClass();
SearchObject.FirstName = "Bill";
// create compare
ICompare CompareObject = new FirstNameCompare();

System.Collections.ArrayList
// Init
ArrayList MyClassList = new ArrayList(MyClassArray);
int Index = MyClassList.BinarySearch(SearchObject, CompareObject);
// Index will be 2
System.Collections.Generics.List<>
// Init
List<MyClass> MyClassList = new List<MyClass>(MyClassArray);
int Index = MyClassList.BinarySearch(SearchObject, CompareObject);
// Index will be 2
BinarySearch also provides another overload where you can search using start index, and number of objects. This is useful if one wants to search in a specific range of objects.



4. Using the "Contains" method

"Contains" can only be used if our collection is solemnly based of primitives. When using custom classes, these methods internally use "Equals" methods to perform the comparison, and the HashCode in the objects will always give the wrong output. (If some one can give me a better explanation, I will really appreate it.)



5. Using the "ConvertAll" method

Allows us to convert all items into another type and is only available in a generic List. This provide us several uses, and one such use is displayed in the code.
// Init
List MyClassList = new List<MyClass>(MyClassArray);

// convert
List<String> NameList = MyClassList.ConvertAll(
delegate(MyClass value)
{
return value.FirstName;
}
);

// final Result contain "Bob,John,Bill"
string Result = string.Join(",", NameList.ToArray());

6. Using the "Find" method

Allows us to find the first instance of the object based on a criteria. In the code below, I am going to find first available "Bill" in the "MyClass.FirstName" field in the collection.
// Init
List<MyClass> MyClassList = new List<MyClass>(MyClassArray);

// search text that will be used to perform filter
string SearchText = "Bill";

// find the instance
MyClass MyClassInstance = MyClassList.Find(
delegate(MyClass value)
{
return value.FirstName.Equals(SearchText);
}
);

7. Using the "FindAll" method

Allows us to find all instances of the object that match the criteria. Please note, we should not use any the Object.Equal feature to perform the validation. This will always return "false" value unless you are overriding the "Equal" method and performing custom validation.
// Init
List<MyClass> MyClassList = new List<MyClass>();
// add same collection three times
MyClassList.AddRange(MyClassArray);
MyClassList.AddRange(MyClassArray);
MyClassList.AddRange(MyClassArray);
// search text that will be used to perform filter
string SearchText = "Bill";
// find all instance that contain FirstName of "Bill"
// result will be three instances
List<MyClass> FilteredMyClassCollection = MyClassList.Find(
delegate(MyClass value)
{
return value.FirstName.Equals(SearchText);
}
);

8. Using the "ToArray" method

This method allows us to convert the collection into object array.

System.Collections.ArrayList

// Init
ArrayList MyClassList = new ArrayList(MyClassArray);

// convert to array
MyClass[] MyClassArray = (MyClass[])MyClassList.ToArray(typeof(MyClass));


System.Collections.Generics.List<>
// Init
List<MyClass> MyClassList = new List<MyClass>(MyClassArray);
// convert to array
MyClass[] MyClassArray = MyClassList.ToArray();
As you notice that, type casting is required in converting items in theArrayList collection to an Array. Whereas, the strongly typed generic"List". This is one such location where best judgment needs to be madein choosing the type of collection. Type casting from ArrayList whenthere several items in its collection might become a performance hog.