Thursday, 29 October 2009

Cool Generic Delegates in C#

Here are some cool generic delegates (.NET 3.5) I find useful in my day to day coding.

  • Action Delegate
    • Action
    • Action(T)
    • Action(T1, T2)
    • Action(T1, T2, T3)
    • Action(T1, T2, T3, T4)
  • Predicate Delegate
    • Predicate<T>(T obj)
  • Func Delegate
    • Func<T, TResult>
    • Func<T1, T2, T3, T4, TResult>
    • Func<T1, T2, T3, TResult>
    • Func<T1, T2, TResult>
    • Func<TResult>

ACTION DELEGATE

The Action delegate encapsulates a method that has no return value and accepts up to four parameters. Action alone represents no parameter, Action(T), Action(T1, T2) etc… represents the number of parameters.

Simple example: using Action to replace Console.WriteLine, because Console.WriteLine accepts a single string parameter, we can simply assign it to the Action<string> and call action(“ABC”) which is equivalent to the Console.WriteLine(“ABC”)

static void Main(string[] args)

{

Action<string> action = Console.WriteLine;

action("ABC");

Console.ReadLine();

}

Or you can pass the action as a parameter and use it as such, using lambda, which will print “stringA1” to the console:

static void Main(string[] args)

{

DoSomething((s, n) =>

{

Console.WriteLine(s + n);

});

Console.ReadLine();

}

private static void DoSomething(Action<string, int> action)

{

string rawString = "stringA";

int rawNumber = 1;

action(rawString, rawNumber);

}

PREDICATE DELEGATE

The Predicate(T) delegate encapsulates a method that returns a Boolean value and accepts a single parameter.

A simple example:

static void Main(string[] args)

{

Predicate<byte> predicate = bit =>

{

return bit == 1 ? true : false;

};

// This will return true

Console.WriteLine(predicate(1));

// This will return false

Console.WriteLine(predicate(0));

Console.ReadLine();

}

In fact, most LINQ Queries uses this predicate delegate, one simple example is the .Find method:

static void Main(string[] args)

{

var list = new List<string>()

{

"a",

"b"

};

string a = list.Find(i => i == "a");

Console.WriteLine(a);

Console.ReadLine();

}

Another useful usage is in LINQ statements like so:

var list = new List<int>()

{

1,

2

};

Predicate<int> p = val => val == 1;

var i = from item in list

where p(item)

select item;

FUNC DELEGATE

The Func delegate is the most powerful of the lot. A Func can return any type (TResult) and accepts zero or up to four input parameters.

var list = new List<string>

{

"one",

"two",

"three"

};

// This indicates a return type of boolean, and accepts

// two input parameters of IEnumerable<string> and string

// respectively.

Func<IEnumerable<string>, string, bool>

funcPredicate = (collection, item) =>

{

if (collection != null && collection.Count() > 6)

{

return collection.Contains("one");

}

return false;

};

var i = from item in list

where funcPredicate (list, item)

select item;

There you have it, the useful delegates you will definitely find handy!

Other delegates I will cover in a later post will include Expression<T>, EventHandler<TEventArgs>, Converter<TInput, TOutput> and Comparison<T>.

Have fun coding!

Tuesday, 20 October 2009

Customised Search Results in Visual Studio

Are you constantly annoyed by the very long File path in the Find Results Window when searching through the File/Project/Solution in Visual Studio?

I found a registry hack to shorten the display path:

1) Type Regedit in "Run"
2) Navigate to HKCU\Software\Microsoft\VisualStudio\9.0\Find
3) Add a new string item called Find result format with a value of $f$e($l,$c):$t\r\n

And here’s the full list of items you can specify in the registry

Files
$p path
$f filename
$v drive/unc share
$d dir
$n name
$e .ext

Location
$l line
$c col
$x end col if on first line, else end of first line
$L span end line
$C span end col

Text
$0 matched text
$t text of first line
$s summary of hit
$T text of spanned lines

Char
\n newline
\s space
\t tab
\\ slash
\$ $

Modify at your own risk! Please back up your registry before making any changes.

How to create a throwaway project in Visual Studio

If you need to create a temp project to try things out in Visual Studio without auto saving it into the Projects directory, go to
1) Tools
2) Options
3) Projects and Solutions
4) General
5) Uncheck (Save new project when created)

Thats it!

Visual Studio 2010 & .Net 4 Beta 2 is Out

Visual Studio 2010 is out and will be made available for download starting Wednesday, and immediately for MSDN Subscriber.

As per Scott Gu's blog, here is an overview of the product lineup specifications:

VS 2010 Product Line SKU Simplifications

With VS 2010 we are simplifying the product lineup and pricing options of Visual Studio, as well as adding new benefits for MSDN subscribers. With VS 2010 we will now ship a simpler set of SKU options:

  • Visual Studio Express: Free Express SKUs for Web, VB, C#, and C++
  • Visual Studio 2010 Professional with MSDN: Professional development tools as you are used to today with the addition of source control integration, bug tracking, build automation, and more. It also includes 50 hours/month of Azure cloud computing.
  • Visual Studio 2010 Premium with MSDN: Premium has everything in Professional plus advanced development tools (including richer profiling and debugging, code coverage, code analysis and testing prioritization), advanced database support, UI testing, and more. Rather than buying multiple “Team” SKUs like you would with VS 2008, you can now get this combination of features in one box with VS 2010. It also includes 100 hours/month of Azure cloud computing.
  • Visual Studio 2010 Ultimate with MSDN: Ultimate has everything in Premium plus additional advanced features for developers, testers, and architects including features like Intellitrace (formerly Historical Debugging), the new architecture tools (UML, discovery), test lab management, etc. It also includes 250 hours/month of Azure cloud computing.
Additionally, Silverlight Toolkit October 2009 has be released with main changes for better Visual Studio 2010 integration. Click here to get it http://silverlight.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=30514#ReleaseFiles

Monday, 19 October 2009

How to implement a merge sort on a Doubly Linked List using C#

I have been working on a custom linked list recently and required a sorting algorithm to sort the doubly linked list.

Mergesort works better on linked lists than it does on arrays. It avoids the need for the auxiliary space, and becomes a simple, reliably O(N log N) sorting algorithm. And as an added bonus, it's stable too.

Here is a quick merge sort algorithm in C#.Net 3.5 (Note - T is my custom node interface) :

private T Merge_Sort(T first)

{

if (first == null || first.Next == null)

return first;


T second = Split(first);

first = Merge_Sort(first);

second = Merge_Sort(second);

return Merge(first, second);

}

private T Split(T item)

{

if (item == null || item.Next == null)

return null;

T second = item.Next;

item.Next = second.Next;


second.Next = Split(second.Next);

return second;

}

private T Merge(T first,

T second)

{

if (first == null)

return second;


if (second == null)

return first;

// If both are not null, we will run the comparer

// If first is less than second

if (first.CompareTo(second) < 0)

{

first.Next = Merge(first.Next, second);

first.Next.Previous = first;

first.Previous = default(T);


return first;

}

else

{

second.Next = Merge(first, second.Next);

second.Next.Previous = second;

second.Previous = default(T);

return second;

}

}

For the full implementation of the Custom Doubly Linked List, look at this post.

Wednesday, 19 August 2009

Native VHD Boot for Windows 7

With Windows 7 and Windows Server 2008 R2, you can configure a VHD(virtual hard disk) file and boot from it, without the need to repartition your existing drive.

i) Native boot means you can fully utilize all hardwares connected to the system.
ii) You cannot use BitLocker when booting from VHD.
iii) Hibernate is not supported when booting from VHD.
iv) Native boot supports all 3 types of VHD files : Fixed, Dynamic and Differencing Disk. Note: Should you not have enough physical storage space as compared to the size of the VHD file, you might get a BSOD.

Simplified instructions for booting from VHD.
1) Start Windows 7 DVD Installation.
2) Press Shift+F10 for the command prompt.
3) Type "diskpart"
4) Type "create vdisk file=Path\Filename.vhd type=fixed maximum=xxxxxx". eg. (create vdisk file=D:\Win7.vhd type=fixed maximum=100000)<-- 100000 Megabytes, type can be dynamic, fixed, etc...
5) Type "select vdisk file=Path\Filename.vhd" to select the created vhd.
6) Type "attach vdisk", and you should get a confirmation that it is attached.
7) Type "exit" and continue installation, and select the attached vhd drive as the installation drive.
8) Boot and it should work.

Alternatively, you can use the disk management tools to create a vhd in Windows 7 via the Windows 7 GUI should you require another vhd copy.

How to remove vhd file.
1) Run elevated command prompt and type "bcdedit /delete {guid} /cleanup"

Saturday, 25 July 2009

Windows 7 RTM

Windows 7 and Windows 2008 R2 has been RTM. Here are the relevant dates:

* Two days after official RTM: OEMs
* August 6: Downloadable for ISVs, IHV's, TechNet subscribers, MSDN subscribers
* August 7: Downloadable for Volume Licence with Software Assurance (English only)
* August 16: Downloadable for Partner Program Gold / Certified members (English-only)
* August 23: Downloadable for Action Pack subscribers (English Only)
* September 1: Purchasing for Volume License without Software Assurance (no mention of specific language availability)
* By October 1: Downloadable for Partner Program Gold / Certified members, Action Pack subscribers, TechNet subscribers, MSDN subscribers (remaining languages)
* October 22: Purchasing at retail locations

Friday, 24 July 2009

Concatenating multiple rows as a single column in a row in SQL Server 2005/2008 (TSQL)

Assuming we have a one to many table, and we need to list all children items per parent in a single row, here is a quick way of doing it in SQL Server 2005/2008 (TSQL)

The following will concatenate all children names belonging to the parent with a ',' delimiter.

 SELECT DISTINCT parent.id, parent.name, CA, CB
FROM ParentTable parent
CROSS APPLY
(
SELECT child.name + ','
FROM ChildA child
WHERE child.parentId = parent.id
ORDER BY child.name
FOR XML PATH('')
) childA(CA)
CROSS APPLY
(
SELECT child2.name + ','
FROM ChildB child2
WHERE child2.parentId = parent.id
ORDER BY child2.name
FOR XML PATH('')
) childB(CB)

Monday, 6 July 2009

IE 8 $10K Challenge

Microsoft is hosting an online treasure hunt (Started 19th June 09), and the first person to find the hidden webpage using the clues provided from time to time will be awarded with $10,000 dollars! But the catch is, you have to use IE 8 to access some of the clues.

Check it out here

Good Luck and happy hunting!

Parameter constraint on dynamic type

It can be accomplished by using the new() keyword.
"new()" indicates the Type T's constructor must not contain any parameters.

Example:

public class A<T> where T : B, new()

Hierarchy Table SQL Statement using CTE (Common Table Expressions)

Assuming a table with fields id, name, parent_id where parent_id is self referencing.

We can use the T-SQL Common Table Expression to easily loop through all children items.

Example Table:
(categories)
id | name | parent_id
1 | CatA | NULL
2 | CatB | 1
3 | CatC | 1
4 | CatD | 2
5 | CatE | 3

 -- This will select all children belonging to CatA where id = 1
;With Hierarchy
As
(
SELECT id, name, parent_id
FROM categories
WHERE id = 1 -- CatA Id
UNION ALL
SELECT child.id, child.name, child.parent_id
FROM categories child
INNER JOIN Hierarchy parent on child.parent_id = parent.id
)
-- This will select all children from the Hierarchy
Select * from Hierarchy

Thursday, 23 April 2009

Attaching Inline Event using Lambda

textBox.TextChanged += (o, e) => { SomeMethod(); };

Friday, 17 April 2009

Coalesing in C#

// numberAfterCoalescing will be equals to 100 in this case
int? number = null; int numberAfterCoalescing = (number ?? 100);

Tuesday, 14 April 2009

Dynamic Class Instantiation

public void DynamicInstantiation(string fullname)

{  

    // Assign the fully qualified name to a string variable  

    // fullname = "Namespace.ClassName";  

    // Or to get the namespace dynamically  

    // string fullname = object.GetType().Namespace + ".ClassName";   

    // Then Create the object  

    SampleClass dynclass = (SampleClass)System.Activator.CreateInstance(Type.GetType(fullname));

}

Free e-books

Microsoft has published a free ebook on Silverlight 3 Beta
Silverlight 2.0, LINQ, ASP.NET 3.5 free E-Books are also available here. MS SQL Server 2008 free E-Book available here. ASP.NET MVC Tutorial with Sample application available here : Microsoft Learning Snacks : here .
Download the cheatsheet for Visual Studio C# 2008.

Wednesday, 1 April 2009

MIX 09 Sessions

MIX 09 Videos available online at http://sessions.visitmix.com/