Delegates in C# Basics and Advanced

Recently, I was reading C# In Depth, By Jon Skeet. It is one of the best books about learn advanced details about C#. While reading the book, I decided to prepare notes. So, that I can just go through the notes to revise, If I have to. Following are the points about the delegates that I read in the book.

1. Delegate is a strongly typed function pointer (Simple but vague)
2. Delegate term is often used for delegate type as well as instance. So, better to be clear is it delegate type or delegate instance.
3. Delegate type is like an interface with a method
4. Delegate type is just another type in C#. A delegate type inherits System.MulticastDelegate which in turn inherits from System.Delegate
5. Delegate instance has a list of actions/methods (Multicast Delegate). This is called invocation list.
6. Delegate type uses 2 methods of System.Delegate Class called “Combine” and “Remove” to add actions/methods as well as remove actions/methods
7. Delegate instance are immutable like string, each addition(+ or +=) causes creation of one more instance and actions are copied over. Same is true for removal using – or -= which in turn calls Remove.
8. “Invoke” method causes the invocation of all the actions/methods in the invocation list
9. All of the actions are executed in order. But the value returned is the value returned by the last action, or if you wish to have return value of each method/action then invoke using “Delegate.GetInvocationList”
10. If any one methods in invocation list throws an exception, Invocation is stopped and remaining methods/actions are not invoked/executed.

Learn Windows Phone 7 Development , Day-4 : Hello! World – Deep Dive 3

In this post I will start from where I left in the last post. So, I will be talking about various application level events in a Windows Phone Application. These events are pretty similar to events in Global.asax.cs in case of ASP.net and Application Object in case of Windows Application. These events are registered in “App.xaml”. If you open “App.xaml” in visual studio you will see following XAML.



    
    
    

    
        
        
    


Out of the above XAML if you look you will see following 4 events of “PhoneApplicationService” class

  1. Launching (event handler function is “Application_Launching”)
  2. Closing (event handler function is “Application_Closing”)
  3. Activated (event handler function is “Application_Activated”)
  4. DeActivated (event handler function is “Application_Deactivated”)

All of the above mentioned event handler functions are defined in ( you guessed it, right :) ) “App.xaml.cs”. if you open “App.xaml.cs” and look at the comments on these functions, there usage is explained to an extent.

// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e) {
}

// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e) {
}

// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e) {
}

// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e) {
}

Before, going into details of these events. One should know a few basic details about application life cycle of Windows Phone 7. 

  1. First is that an application closes when users clicks the back button, that looks like following icon in windows phone simulator. WP7Back
  2. Second is that an application goes to sleep mode or in Windows Phone Terminology application gets tombstoned, when users press start button, that looks like following icon in windows phone simulator. Application can get tombstoned, because of various events. for example, device got locked, an incoming phone call etc.  In this mode application’s process is killed, but the state of application is still maintained by the Windows Phone Operating System.WP7Home

All the above mentioned four events are related to these 2 basic states(closed and tombstoned) of an application. and it is pretty evident that the “Application_Launching” and “Application_Closing”  are the events that are raised when application starts(“Application_Launching”) and when application closes(“Application_Closing”). The other two events are related to application getting out of tombstone mode(“Application_Activated”)  and getting tombstoned(“Application_Deactivated”).

Next question that comes into mind as developer is what operations am I suppose to perform in these events. That I will cover in my next post Smile. See ya..

Mocking HttpContext, HttpResponse, HttpRequest, HttpSessionState etc. in ASP.Net

While developing web application using ASP.Net. If one wants to follow TDD, there are a lot challenges that one has to face. One of the challenge is to mock various web based objects like HttpContext, HttpRequest etc.. In this post I will talk about mocking following web based objects

  • HttpContext
  • HttpRequest
  • HttpResponse
  • HttpSessionState ( Page’s Session Property’s Type)
  • HttpApplicationState (Application Property’s Type)

To ease the unit testing of the components dependent, on above mentioned web based objects. Microsoft released System.Web.Abstractions.dll in .Net 3.5( in .Net 4.0 this dll was merged into System.Web.dll) all these classes were still under System.Web namespace. We will be using those classes only.

What Microsoft did was pretty simple. On the place of modifying existing classes. They created a “wrapper class” that inherits from an “abstract base class”. Wrapper classes have only one constructor to which one has to pass an object of the real class. For example HttpContext is the real class for that they created HttpContextBase that is the “abstract base class” and HttpContextWrapper is the “wrapper class” which has only one constructor that accepts the “real class” i.e. “HttpContext”.

This way all of the components that are dependent on “real class” should be made dependent on  “abstract base class”. So, that while unit testing one creates a mock of the “abstract base class”  and in real-time execution an object of the wrapper class is passed, that take the real class.

For HttpContext, HttpRequest, HttpResponse,HttpSessionState and HttpApplicationState following are the corresponding classes.

Class to be Mocked Wrapper Class Abstract Class
HttpContext HttpContextWrapper HttpContextBase
HttpResponse HttpResponseWrapper HttpResponseBase
HttpRequest HttpRequestWrapper HttpResponseBase
HttpSessionState HttpSessionStateWrapper HttpSessionStateBase
HttpApplicationState HttpApplicationStateWrapper HttpApplicationStateBase

For the sample below. We we will test a class that needs all four of these.The only thing is that class will use HttpContext to access all these classes.

Following is how a class might look like when it is using these objects without worrying about unit testing.

namespace TestWebApp.Web
{
    public class CreditCardProcessor
    {

        public void Save()
        {
            // Do some operation in database
            var currentContext = HttpContext.Current;
            currentContext.Application["UserCreditCardSaveCount"] =
                (int)(currentContext.Application["UserCreditCardSaveCount"]) + 1;
            currentContext.Session["EnteredCreditInfo"] = "Y";
            currentContext.Response.Redirect(currentContext.Request.QueryString["rUrl"]);
        }

    }
}

After changing context class to abstract base class, code will look like following, Enabling the injection context object. To use this class you have to add reference to System.Web.Abstractions as stated earlier no need to change “using”. Since classes are still in System.Web namespace.

using System.Web;
using System.Web.SessionState;

namespace TestWebApp.Web
{
    public class CreditCardProcessor
    {
        private HttpContextBase context;

        public CreditCardProcessor(HttpContextBase httpContext) {
            this.context = httpContext;
        }

        public void Save() {
            // Do some operation in database

            context.Application["UserCreditCardSaveCount"] =
                (int)(context.Application["UserCreditCardSaveCount"]) + 1;
            context.Session["EnteredCreditInfo"] = "Y";
            context.Response.Redirect(context.Request.QueryString["rUrl"]);
        }

    }
}

Now, following is one sample of the test. Following test uses nunit testing framework and Moq mocking framework.

using Moq;
using NUnit.Framework;
using TestWebApp.Web;
using System.Web;

namespace MockSampleWebApp.Tests
{
    [TestFixture]
    public class CreditCardProcessorTests
    {
        [Test]
        public void Can_Save()
        {
            //SetUp
            var mockContext = new Mock();
            var mockRequest = new Mock();
            var mockResponse = new Mock();
            var mockSessionState = new Mock();
            var mockApplication = new Mock();
            var processor = new CreditCardProcessor(mockContext.Object);

            mockRequest.SetupGet(req => req.QueryString).Returns(HttpUtility.ParseQueryString("?rUrl=BlahBlah"));

            mockContext.Setup(ctxt => ctxt.Request).Returns(mockRequest.Object);
            mockContext.Setup(ctxt => ctxt.Response).Returns(mockResponse.Object);
            mockContext.Setup(ctxt => ctxt.Session).Returns(mockSessionState.Object);
            mockContext.Setup(ctxt => ctxt.Application).Returns(mockApplication.Object);

            mockApplication.Setup(app => app["UserCreditCardSaveCount"]).Returns(2);
            mockApplication.SetupSet(app => app["UserCreditCardSaveCount"]=3).Verifiable();
            mockSessionState.SetupSet(sstat => sstat["EnteredCreditInfo"]="Y").Verifiable();
            mockResponse.Setup(resp => resp.Redirect("BlahBlah"));

            processor.Save();

            mockContext.VerifyAll();
            mockSessionState.VerifyAll();
            mockRequest.VerifyAll();
            mockResponse.VerifyAll();

        }
    }
}

And finally the production usage would be as following.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TestWebApp.Web;

namespace MockSampleWebApp
{
    public partial class CreditCardSave : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e) {

        }

        protected void Save_Clicked(object sender, EventArgs e)
        {
            var ccProcessor=new CreditCardProcessor(new HttpContextWrapper(HttpContext.Current));
            ccProcessor.Save();
        }
    }
}

Please click on following image to download complete code.

Learn Windows Phone 7 Development , Day-3 : Hello! World – Deep Dive 2

Today, we will talk about what happens when you compile a Windows Phone 7 application and what is the basic workflow of the application. There will be some concepts which may sound familiar to Silverlight developers.

When you compile a Windows Phone 7 Silverlight application, for each “.xaml” file 2 files are generated one with name “Filename.g.cs” and another one for “Filename.i.cs” for example App.xaml would result in “App.g.cs” and “App.i.cs”, where “g” is for generated and “i” is intellisense, These files would be in “obj\Debug” if your project is compiled in debug mode. There are bunch of other files in “obj\Debug” as well these files are file containing list of all of the files, compiled assembly of code behind files, etc.

All “.cs” and “resources” files are compiled and merged into final output which is nothing but few dlls and resources, Final output is inside “Bin\Debug”. These dlls and resource files are then zipped into a one single file which has extension ”.xap”. This “.xap” file would be there in “Bin\Debug” as well.This is the file that is deployed to the Windows Phone.

Let us talk about the workflow of the program. If you open “App.xaml.cs” (This file is there in visual studio solution). You will see following code in the constructor.

        /// <summary>
        /// Constructor for the Application object.
        /// </summary>
        public App() {
            // Global handler for uncaught exceptions.
            UnhandledException += Application_UnhandledException;

            // Show graphics profiling information while debugging.
            if (System.Diagnostics.Debugger.IsAttached) {
                // Display the current frame rate counters.
                Application.Current.Host.Settings.EnableFrameRateCounter = true;

                // Show the areas of the app that are being redrawn in each frame.
                //Application.Current.Host.Settings.EnableRedrawRegions = true;

                // Enable non-production analysis visualization mode,
                // which shows areas of a page that are being GPU accelerated with a colored overlay.
                //Application.Current.Host.Settings.EnableCacheVisualization = true;
            }

            // Standard Silverlight initialization
            InitializeComponent();

            // Phone-specific initialization
            InitializePhoneApplication();
        }

First line of the constructor binds the error handler.Then there is a “if block” in which one can set values of some flags that control information shown to the developer while running the program in debugging mode. After that, constructor calls two methods first is “InitializeComponent()” and the other one is “InitializePhoneApplication()”“InitializeComponent()” is a standard Silverlight initialization method that would be defined in the “.g.cs” class and it would be called here in the constructor of the App class. Where as “InitializePhoneApplication()” is specific function used for the initialization specific to phone.

        private void InitializePhoneApplication() {
            if (phoneApplicationInitialized)
                return;

            // Create the frame but don't set it as RootVisual yet; this allows the splash
            // screen to remain active until the application is ready to render.
            RootFrame = new PhoneApplicationFrame();
            RootFrame.Navigated += CompleteInitializePhoneApplication;

            // Handle navigation failures
            RootFrame.NavigationFailed += RootFrame_NavigationFailed;

            // Ensure we don't initialize again
            phoneApplicationInitialized = true;
        }

As you can see in the method “InitializePhoneApplication()”  there is a flag that is maintained to ensure that this function would not be called twice. When application would be initialized for the first time it will create an Object of type “PhoneApplicationFrame” and assign that object to its property called “RootFrame” . Then, It will bind an event handler ”CompleteInitializePhoneApplication” to the event “Navigated” of the “RootFrame” , and at the end following code would be executed When this “RootFrame” would be Navigated to and that would be as soon as the application loads.

private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e) {
            // Set the root visual to allow the application to render
            if (RootVisual != RootFrame)
                RootVisual = RootFrame;

            // Remove this handler since it is no longer needed
            RootFrame.Navigated -= CompleteInitializePhoneApplication;
        }

 

Which will make sure that “RootVisual” Property of the “App” class is set to “RootFrame”  and then it will remove the handler bindings.

In the next post we will talk about handling the application level events that are registered in with “PhoneApplicationService”

Learn Windows Phone 7 Development , Day-2 : Hello! World – Deep Dive 1

Yesterday we build the “Hello! World” application. Today, we will have a look at the files that got created when we created the project.

Following is the list of files that are visible in Solution Explorer Visual Studio

  • AppManifest.xml – This is a file used by Silverlight , primary purpose for Silverlight is to store Entry Point assembly name, Entry Point type name and assemblies that are there in “.xap” file(I will explain what is “.xap” file in the next post). For more details (http://www.codeproject.com/KB/silverlight/QuestionsOnSilverlight.aspx#_Toc263879427)
  • AssemblyInfo.cs – This is standard file of any .Net project. It contains Assembly related info like version, title, company etc..
  • WMAppManifest.xml – This is also called Application Manifest File for Windows Phone. This is an important file for Windows Phone Development, and description of this file in full, will need a post. But, basically it contains the Author Name, Application Title, phone capabilities(like location,dialer etc.) used by the application, various images, tasks etc. for more details (http://msdn.microsoft.com/en-us/library/ff769509%28v=vs.92%29.aspx)
  • App.xaml – This is the XAML markup file that is starting point of the application.If you have a look at the project properties( You can do that by right clicking on the project in solution explorer and then choosing properties). you will see that it is listed as a start up object.  This file contains the markup that lists Application Lifetime Objects( objects that are available through out the life time of the application) and its events bindings
  • App.xaml.cs -  This is kind of code behind file for “App.xaml”. It contains a partial class called “App” that is specified in App.xaml’s markup as well.  This class inherits from “System.Windows.Application”, Base class for a Silverlight application, and it also has the code for event handler specified in the “App.xaml”.
  • ApplicationIcon.png – This is the image file that is used as icon when application is shown in windows phone in list of installed applications. This is also specified in “WMAppManifest.xml” .
  • Background.png – This file is used when user pins one application to the start. Will get into details of, what do I mean by “when user pins application to the start” later.This file is also specified in “WMAppManifest.xml”.
  • MainPage.xaml – This file contains XAML(eXtensilble Application Markup Language) for the first page shown to the user, the form that contains “Hello! World in our care”. (windows developer consider this to be the first form of the application),(web developers consider this to be the default form).  This file is also specified in “WMAppManifest.xml”.
  • MainPage.xaml.cs – This file is the code behind file of “MainPage.xaml”, and as you can see it is partial class with just one constructor and call to a method “InitializeComponent”.
  • SplashScreenImage.jpg – This is image that would be shown to the user when your application would be loaded by Windows Phone 7. Developer can’t change the name of the file. To use this feature file name has to same “SplashScreenImage.jpg” and Build Action that is specified in the file properties must be “Content”
  •  

    In next post I will explain the Markup of “App.xaml” and  “MainPage.xaml”, and basic working of the application.

    Learn Windows Phone 7 Development , Day-1 : Hello! World

    Disclaimer ::  This series is for people who are already comfortable with Microsoft.Net development doesn’t matter web or windows. Even though Windows Phone Development requires one to know Silverlight. But, Silverlight is not must for this series of tutorials.Since, we will be learning that as well, and this series is only focused on windows phone development in Silverlight, not XNA Framework 4.

    Task ::  Write a window phone 7 app that shows “Hello! World”.

    First and foremost one need to know about the tools that he will be using . So, following are the tools that you will be using for the day one

    • Visual Studio 2010
    • Windows Phone 7 Emulator

    You can download one integrated package of tools from this link(http://create.msdn.com/en-us/home/getting_started) . 

    Let us get started. After installing tools Open Visual Studio or Visual Studio Express. Press Ctrl + Shift + N or go to  File –> New –> Project Choose “Silverlight for Windows Phone”( If the options is not there that means either you haven’t installed the tools, or there is something wrong).

    Let us keep the project name as it is(WindowsPhoneApplication1) only. New project dialogue should look like following

    New_Project

    Visual Studio will take some time to set up the project for you. After that you will see XAML Editor as shown in following screen shot ( This is how visual studio looks if you using it in Full Screen Mode [ Use Alt+Shift+Enter to toggle between full screen mode])

    MainScreen

    On the left you can see the design screen on the right is XAML source editor. We will get into details of XAML editor later.

    Press F5 now to run the project in debugging mode.  Visual Studio will make a build of the project and show you the Windows Phone 7 Emulator which will look like following.

    WinPhone7Emulator

    It will take some time in loading your application for the first time, then you will see your application running in emulator.

    Now go back to Visual Studio with out closing the emulator. Press( Shift + F5) or Debug –> Stop Debugging.  Go to XAML Source View(the one in the right) . Try finding text ‘Text=”page name”’ Change ‘page name’ to ‘Hello! World’.

    Press F5 again. This time it should load faster (If you didn’t close the emulator first time and followed the steps as I explained). 

    Final Output

    WinPhone7Emulator-2

    This is it your first Windows Phone 7 App ‘Hello World’. Tomorrow, I will get into details of what is going on, What are the classes being Used, XAML Markup and all

    Feel free to ask question via comment section.

    Correct Usage of Finalize and Dispose

    Couple of day back I was reading an article by Jimmy Bogard Dependency Injection in ASP.NET MVC: Views. Over there I found an interesting thing that is correct usage of finalize and dispose. There are articles that discuss finalize, discuss and garbage collector. So, I will just give a small overview after the correct usage. correct usage is

     public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    
        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
                return;
    
           /* This is where you should write the code to dispose your custom objects */
    
            _disposed = true;
        }
    

    How is this code gone help.This is how you should implement dispose, if you are interested in details like why then search for dispose and finalize in google and you will find explanations everywhere

    IEnumerable and Datareader ‘Yield return’ issue

    Recently, while working on one of my organization’s project. We wrote a generic extension method on the data reader class that returns the IEnumerable of the generic type.So, essentially what this does is returns an IEnumberable of the objects after reading various values from the datareader.(Dont ask me why are we doing this, why aren’t we using any ORM. We still want to use legacy data layer(organization’s decision). Since, this blog is not about why this decision was made, I will try to focus on the issue, that we faced while writing this for the first time. Am, planning to post this on stackoverflow.com as well to receive feedback to understand better way to resolve this.So, Initial code was

    public static IEnumerable<T> MapTo<T>(this IDataReader reader) where T : new()
    {
        return reader.MapTo<T>(null);
    }
    
    public static IEnumerable<T> MapTo<T>(this IDataReader reader, Action<IDataReader, T> customMappingFunction) where T : new()
    {
        using (reader)
            while (!reader.IsClosed && reader.Read())
            {
                var nextItem = new T();
                nextItem.InjectFrom<DataReaderInjection>(reader);
                if (customMappingFunction != null)
                    customMappingFunction(reader, nextItem);
                yield return nextItem;
            }
    }

    As you can see one method is just an overload of the real method. Issue with this method is that if try doing something like following,

    // In case of lazy loading call to first count would return the correct value and the second call would return 0
    var listOfEmployee = datareader.MapTo<Employee>();
    Console.WriteLine(listOfEmployee.Count());
    Console.WriteLine(listOfEmployee.Count()); 

    It will not work since next call is not resetting datareader, even though this would not work, chainabilty (fluent Interface) on first call will still work, Since this is how yield return works.

                                                     This is inherent problem of the data reader, Since you cann’t reset a data reader. So, because of that you can’t use lazy loading with data readers. and if you enable lazy loading then you have to call ToList() after call to MapTo<T>(). otherwise you can lose the IEnumerable<T>.

    Code of DataReader Injection Class (This class is based on OMU Value Injector)

    public class DataReaderInjection : KnownSourceValueInjection<IDataReader>
    {
        protected override void Inject(IDataReader source, object target, PropertyDescriptorCollection targetProps)
        {
            for (var i = 0; i < source.FieldCount; i++)
            {
                var activeTarget = targetProps.GetByName(source.GetName(i), true);
                if (activeTarget == null) continue;
    
                var value = source.GetValue(i);
                if (value == DBNull.Value) continue;
    
                activeTarget.SetValue(target, value);
            }
        }
    } 

    MugBug Day 1

    I searched a lot, But was not able to find a bug tracking system based on ASP.Net MVC. So, I decided to build this as my learning project. I decided to use Sharp Architecture to start with.So, first thing is to download it SharpArchitecture_1.5_Beta1.zip. I am using Windows 7 , VS 2010 with ASP.net MVC 2 installed . So, instructions are specific to that only. After downloading unzip the file in “C:\Users\mthakral\Documents\Visual Studio 2010\Templates\ProjectTemplates\Visual C#\Web” . If “Web” Directory is not there then create it . Zipped File would contain another zip file and one dll. Unblock the zip file as well(Right click and then unblock). Add the dll to GAC. For Visual 2008 you can follow the instruction given at :: Setup Sharp Architecture.

    Then go to VS 2010 new Project-> Visual C# -> Web -> Choose “Sharp Architecture” ,
    Project Name MugBug and It will start creating bunch of projects for you. It will show you some database related dialog box, Just cancel those. You will see 2 errors in tt templates.(Atleaset, I was getting those). But, I ignored those and tried making a build. It build successfully.But, out of 9 projects 3 were skipped by default. Then, I tried running and it failed with some Global.asax error on “NHibernateSession.Init(“. I think this was because of database. So, I went ahead created a database and it user. Placed those values in Y:\MugBug\app\MugBug.Web\NHibernate.config. After this, I was able to run my app for the first time. and then as the page suggested, I executed the unit tests. After that, I could see two errors in T4 templates something like
    Error 19 Compiling transformation: Metadata file ‘Inflector.Net.dll’ could not be found
    Error 20 Compiling transformation: Metadata file ‘SharpArch.Core.dll’ could not be found

    Thats if for day 1, time to go for a shower and then office. C ya

    Now, I am facing some random issues with tt generator.