Imagine Cup 2008

28 01 2008

image_2.png

Looking to show out your talent? How far you can do wonders with Software and Technology? Then Imagine Cup should be in your list :)

If you are in University Of Otago and want to participate in this year’s Imagine Cup, please email me and I am happy to assist you.

I do have a Project in mind for Software Design competition and looking to form a team. You can read more about Software Design here. So please do email me if you want to jump in 8)

Before you leave, here is the theme for Imagine Cup 2008,

“Imagine a world where technology enables a sustainable environment.”





Microsoft Student Partners 2008 – University Of Otago

28 01 2008

Ok, Here are the Microsoft Student Partners 2008 for University Of Otago :)

david-msp.png

chaks-msp.png

8)





Survey for my blog readers

27 01 2008

FAQ

Hi Friends,

Its been a long time since I started blogging but I haven’t yet asked for any feedback about my blog to my friends and readers. So, I thought let me have a small survey conducted on my blog. I would be really happy if you can complete this small survey here and give your valuable inputs 8)

Thanks,

Regards,

Chakkaradeep (a.k.a Chaks)





Mock Objects

25 01 2008

tdd.png

So, you have started reading or doing more on Test Driven Development? Then am sure you would have now heard about Mocking or Mock Objects :D

Before getting started and seeing what is this Mock Object, let me quote the definition of Unit Test from Wikipedia

In computer programming, unit testing is a procedure used to validate that individual units of source code are working properly. A unit is the smallest testable part of an application.

The goal of unit testing is to isolate each part of the program and show that the individual parts are correct. A unit test provides a strict, written contract that the piece of code must satisfy.

So, Unit Testing covers testing each individual part in your program. In other words, when we say we are unit testing a Component A, we actually test the functions, properties etc., inside that component.

Below is a pictorial representation of what we do,

unit-test.png

For Component A , we write several unit test cases and test it. Since this component does not depend on anything else, it is fairly easy to test all the parts of the component and hence it satisfies the definition of Unit Testing.

Now we bring in another Component B, which depends on Component A and thus now we have something like this,

unit-test-2.png

How do we test Component B now?

Let me write down the scenario of where we are now,

1) We have Component A which is been tested

2) We have Component B which uses/depends on some of the functions of Component A

3) We have to test Component B such a way that its isolated from Component A, yet still use Component A

4) If we test along with Component A with Component B, its not Unit Test, rather its, Integration Testing!

What do we do now? Mock Component A 8)

Yes, here comes the use of Mock Objects. From Wikipedia,

In object-oriented programming, mock objects are simulated objects that mimic the behavior of real objects in controlled ways. A computer programmer typically creates a mock object to test the behavior of some other object, in much the same way that a car designer uses a crash test dummy to test the behavior of a car during an accident.

So, its kinda Fake Object, but a Mock Object has some expectations and results being set on it.

Now, to make use of Mock Objects, we change the Component A to implement an interface Interface A and Component B an interface Interface B .Using Interfaces helps us to have just the functions and properties of the Component being written which is what Mock needs ;)

Here we are now,

unit-test-3.png

TDD has hence allowed to make changes to your design now and you would have changed tests accordingly.

Introducing Mock Objects, we now have,

unit-test-mocking.png

So, we interact with Component A using our Mock Repository which holds the Mock Object – Interface A

We can now set expectations on Mock Objects, meaning that, you can say that – When a function named FunctionA is called, return the string “Hello World”

It may confuse you initially, but am sure you will get the whole picture once you start mocking yourself ;)

Here is a sample test case along with Mocking (Using NUnit and Rhino Mocks),

[TestFixture]
public class AdminTests
{
    private MockRepository mocks;
    private EduAdmin eduAdmin;
    private Bl.IBLAdmin mockAdmin;
    private delegate bool ValidRegisterDelegate(Db.Admin entity);

    [SetUp]
    public void Setup()
    {
         mocks= new MockRepository();

         mockAdmin = mocks.DynamicMock<Bl.IBLAdmin>();
    }

    [Test]
    public void Check_Method_Register()
    {
        AdminEntity inputEntity = new AdminEntity();
        inputEntity.AdminId = "admin";
        inputEntity.AdminPassword = "admin";

        Db.Admin dbAdmin=new Educator.DataAccess.Admin
        {
            AdminId = "admin",
            AdminPwd = "admin"
        };

        With.Mocks(mocks).Expecting(() =>
        {
            Expect
                .Call(mockAdmin.Translate(inputEntity))
                .Return(dbAdmin);

            Expect
                .Call(delegate { mockAdmin.Insert(dbAdmin); })
                .Callback((ValidRegisterDelegate)
                               ((entity) => { return entity.AdminId == "admin" && entity.AdminPwd == "admin"; }));

        }).Verify(delegate
       {
           eduAdmin = new EduAdmin(mockAdmin);

           eduAdmin.RegisterAdmin(inputEntity);
       });
    }
}

More resources on Mock Objects,

1) All about Mock Objects

2) Mock aren’t Stubs

3) Rhino Mocks





Summer road trip Update

23 01 2008

winvista-button_rgb.jpg vs08_v_rgb_web.jpg ms_net_rgb_web.jpg

Darryl has posted an update for the Summer road trip 8)

So, to sum it up, here is the schedule

  • Feb 4, Auckland – AIT, Ground Floor, Write Stevenson House, 585 Great South Road, Auckland
  • Feb 5, Tauranga – Bureta Park Motor Inn, Redwood Room, Vale Street, Otumoetai, Tauranga
  • Feb 7, Hamilton – Wintec, Room C1.18, Gate 5, Tristram Street, Hamilton
  • Feb 8, New Plymouth – Quality Hotel, Blenheim room, Cnr Courtenay and Leach Streets, New Plymouth
  • Feb 11, Napier – East Pier, 50 Nelson Quay, Ahuriri, Napier
  • Feb 12, Palmerston North – PN Convention Centre, The Conference Room, 1st Floor, 354 Main Street, Palmerson North
  • Feb 13, Wellington – Paramount Theatre, 25 Courtney Place, Wellington
  • Feb 14, Nelson – Tahuna Beach Function Rooms, Tui Room, 70 Beach Road, Tahunanui, Nelson
  • Feb 15, Christchurch – Christchurch convention centre, Cambridge Room, 1st Floor, 86 Kilmore Street, Christchurch
  • Feb 18, Dunedin – Town Hall, 1 Harrop Street, Dunedin
  • Feb 19, Invercargill – Ascot Park Hotel, Oreti Room, Corner of Tay Street and Racecourse Road, Invercargill

Session gathering @ 1.00 p.m

Session starts @ 1.30 p.m

Maximum duration upto 2 hours :D

Cool 8)





This is really awesome – The Best movie for now – CloverField

21 01 2008

Here is a four minute preview

8)





Windows Vista Facts

20 01 2008

winvista-button_rgb.jpg

I am not sure whether this page is there from the beginning, but I found this today via NeowinWindows Vista: Facts 

I do agree with those Facts 8)





Generic Delegates and Lambda Expressions

19 01 2008

.NET 3.5 now provides Generic Delegates which can be used in place of Anonymous Methods

The Generic delegates always encapsulate a method which can accept 1 or more inputs and return a value. So, currently we have,

1) Func<TResult>

2) Func<T,TResult>

3) Func<T1,T2,TResult>

4) Func<T1,T2,T3,TResult>

5) Func<T1,T2,T3,T4,TResult>

Well enough to cater our needs ;)

Lets take an example

Problem: Given an array of words, and a desired length, return me all the words which satisfy that length

Let me give the solution straight away,

function-delegates.jpg

As you can see we have used the Func<T1,T2,TResult> generic delegate where our first parameter is an array of strings and the second parameter is an integer and third parameter which is the return type is ArrayList

If you look closely, we have also used the Lambda operator too in building the function ;)

Now, let us fire our Reflector and see what is there

reflector-function-delegates.jpg

ah..so this has been transformed into an Anonymous Method and the delegate is nothing but our Func<T1,T2,TResult>

Lets again take a look at how Func<T1,T2,TResult> is declared,

public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);

Well, I think that explains it ;)

So, what about directly using Lambda expressions..mmm…like this,

function-delegates-lambda-expressions.jpg

That does reduce our lines of code and the way we interpret things :D . I feel the above method is lot more easier than our generic function delegates. So what does our Reflector say about this,

relector-lambda-expressions.jpg

So what is that CS$<>9__CachedAnonymousMethodDelegate2

My Reflector says it is nothing but,

[CompilerGenerated]

private static
     Func<string, bool> CS$<>9__CachedAnonymousMethodDelegate2;

So, again we are back to our generic delegates 8)

Yes, so as we can see it transforms the lambda expressions into delegates :D

From MSDN,

A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

I think that explains our Reflector was indeed correct 8)





Arriving to LINQ

18 01 2008

As everybody know, LINQ is one of the new feature in .NET 3.5 framework

I thought let me take you a small ride on how I arrived in using LINQ :D

I will take you from the common approach and then a step ahead and finally arrive to LINQ

(I am taking very very generic example to showcase this)

Problem : Given a array which has some words, find the words that end with letter “s”

1) Normal old style approach

Normal method would be just to write a function, pass the array of strings and return back our result

ArrayList arrList;
String[] strName = { "this", "is", "at" };

//plain old method
Console.WriteLine("Using plain old method - Calling a function");
arrList=OldMethod(strName);
for(int i=0;i<arrList.Count;i++)
{
    Console.WriteLine("String = {0}",arrList[i]);
}
arrList.Clear();

And our OldMethod function is as follows,

static ArrayList OldMethod(string[] strName)
{
    ArrayList arrList = new System.Collections.ArrayList();

    for (int i = 0; i < strName.Length; i++)
    {
        string name = strName[i];

        if (name.EndsWith("s"))
        {
            arrList.Add(name);
        }
    }

    return arrList;
}

2) Using Delegates

Now, you feel like providing a delegate and we shift to Named methods now

1) We declare a delegate

internal delegate ArrayList MyDelegate(string[] strName);

2) Our function

static ArrayList UsingNamedMethods(string[] strName)
{
    ArrayList arrList = new System.Collections.ArrayList();

    for (int i = 0; i < strName.Length; i++)
    {
        string name = strName[i];

        if (name.EndsWith("s"))
        {
            arrList.Add(name);
        }
    }

    return arrList;
}

3) Assign the function to the delegate object

//using named methods
Console.WriteLine("Using Named Methods - Using Delegates");
MyDelegate MyFunction = UsingNamedMethods;

4) Invoke the delegate

arrList=MyFunction(strName);

5) Display our results

for (int i = 0; i < arrList.Count; i++)
{
    Console.WriteLine("String = {0}", arrList[i]);
}
arrList.Clear();

3) Using Anonymous Methods

Now, we can use Anonymous Methods in C# and overcome some of the complexities that we have in Named Methods. With Anonymous methods, we have access to local variables too.

Again we have a delegate and then use that delegate object to create our anonymous method

internal delegate void AnonymousDelegate();

You can see the change in previous delegate declaration and the one above.As we have access to local variables, we need not pass or return, and manipulate things locally itself. So we don’t create a new method for our delegate.

//using anonymous methods
Console.WriteLine("Using Anonymous Methods - Welcome to C# 3.0");
AnonymousDelegate AnonymousMethod = delegate()
                            {
                                foreach(string s in strName)
                                {
                                    if (s.EndsWith("s"))
                                        arrList.Add(s);
                                }
                            };
AnonymousMethod();
for (int i = 0; i < arrList.Count; i++)
{
    Console.WriteLine("String = {0}", arrList[i]);
}
arrList.Clear();

4) Using Generic Function Delegates

Still, we can eliminate delegate declaration and instantiation with the generic Function delegates that are available

//using generic function delegates
Console.WriteLine("Using Generic Function Delegates");
Func<ArrayList> FunctionGenericDeletgateCall = delegate()
                                        {
                                            foreach (string word in strName)
                                            {
                                                if (word.EndsWith("s"))
                                                    arrList.Add(word);
                                            }

                                            return arrList;
                                        };
arrList=FunctionGenericDeletgateCall();
foreach(string word in arrList)
{
    Console.WriteLine("String = {0}",word);
}
arrList.Clear();

Certainly that doesn’t look that good. So what do we have next?

5) Using Extension Methods

Yes, Extension Methods! This makes life easier for others who start using your framework or API or Program. Extension Methods enables you to add “your own” methods to the existing types. So we will add a method that returns us the words ending with “s” to the data type string[]

First, Extension methods should be always static methods inside a static class. Let us create them

public static class ExtensionMethods
{
    public static ArrayList ContainsMyCharacter(this string[] strName)
    {
        ArrayList arrList = new System.Collections.ArrayList();

        for (int i = 0; i < strName.Length; i++)
        {
            string name = strName[i];

            if (name.EndsWith("s"))
            {
                arrList.Add(name);
            }
        }

        return arrList;
    }

}

Next, we just use it as how you use inbuilt methods;)

//using Extension Methods
Console.WriteLine("Using Extension Methods");
arrList=strName.ContainsMyCharacter();
foreach (string word in arrList)
{
    Console.WriteLine("String = {0}", word);
}
arrList.Clear();

This has made our life easier than our earlier methods :D

6) Using Generic LINQ (System.Linq) with Lamda Expressions

Now we get into the usage of Lambda Expressions and the Generic LINQ. Well, we haven’t still arrived at the most easiest way of programming ;)

We can use System.Linq.Enumerable to make the above process a bit simpler

//using LINQ Generic Methods
Console.WriteLine("Using Generic Linq with Lambda Expressions");
IEnumerable<string> collection=System.Linq.Enumerable.Where(strName, s => s.EndsWith("s"));
foreach (string word in collection)
{
    Console.WriteLine("String = {0}", word);
}

7) Using LINQ with Lambda Expressions

So, how can we make the above process even more simpler? :D

With C# 3.0 and LINQ and Extension Methods, the query operators are implemented as extension methods ;)

Yes, you guessed it right, we can directly query on the variable strName

//using LINQ Lambda Expressions
Console.WriteLine("Finally - Here is LINQ with Lambada expressions without Generic Functions");
collection = strName.Where(s => s.EndsWith("s"));
foreach (string word in collection)
{
    Console.WriteLine("String = {0}", word);
}

8 ) Finally, last but not the least – Using Queries

You can also query instead of directly using the extended query operators methods like Where – the one we used above

//using LINQ Query
Console.WriteLine("Using LINQ Queries");
var query = (from s in strName
              where s.EndsWith("s")
              select s);
foreach (string word in query)
{
    Console.WriteLine("String = {0}", word);
}

If you look into Reflector, the last 3 methods will be interpreted as same. So using any of them would be fine. Only that, using the Generic LINQ as in 6 will result to 7 when compiled, so we could directly use method 7

You can download the source code of the above application here

8)





.NET Source Code (not all, but few) released!

18 01 2008

vs08_v_rgb_web.jpg

Yes, as promised earlier, here comes the .NET Source Code :)

Read here on how to enable source code debugging from the person who made this possible :D

And for a screencast, Daniel Moth has an excellent screencast. Watch it here 

One notable change is in the licensing of the source code which can be read here at Scott Gu’s blog

Here is the excerpt  from the above link,

The .NET Framework source is being released under a read-only reference license. When we announced that we were releasing the source back in October, some people had concerns about the potential impact of their viewing the source. To help clarify and address these concerns, we made a small change to the license to specifically call out that the license does not apply to users developing software for a non-Windows platform that has “the same or substantially the same features or functionality” as the .NET Framework. If the software you are developing is for Windows platforms, you can look at the code, even if that software has “the same or substantially the same features or functionality” as the .NET Framework.

:)








Follow

Get every new post delivered to your Inbox.