<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Code Merlin</title>
	<atom:link href="http://www.codemerlin.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.codemerlin.com</link>
	<description>Tricks of code trade</description>
	<lastBuildDate>Tue, 01 May 2012 22:55:42 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>BackgroundWorker&#8217;s RunWorkerCompleted event&#8217;s weird behavior in Outlook Add In developed using VSTO 4.0</title>
		<link>http://www.codemerlin.com/2012/02/backgroundworkers-runworkercompleted-events-weird-behavior-in-outlook-add-in-developed-using-vsto-4-0/</link>
		<comments>http://www.codemerlin.com/2012/02/backgroundworkers-runworkercompleted-events-weird-behavior-in-outlook-add-in-developed-using-vsto-4-0/#comments</comments>
		<pubDate>Sat, 11 Feb 2012 16:53:47 +0000</pubDate>
		<dc:creator>Mohit Thakral</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.codemerlin.com/?p=217</guid>
		<description><![CDATA[If one uses &#8220;BackgroundWorker&#8221; class in an application.Then, as per the documentation and the discussion found online. It is suppose to raise &#8220;RunWorkerCompleted&#8221; and &#8220;ProgressChanged&#8221; on the same thread. On which the object of &#8220;BackgroundWorker&#8221; was created. Which in case of Windows form application would be UI Thread. But, if one uses &#8220;BackgroundWorker&#8221; class in [...]]]></description>
			<content:encoded><![CDATA[<p>If one uses &#8220;<a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx" title="BackgroundWorker">BackgroundWorker</a>&#8221; class in an application.Then, as per the documentation and the <a href="http://stackoverflow.com/questions/2806814/backgroundworker-runworkercompleted-event">discussion</a> found online. It is suppose to raise &#8220;<a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.runworkercompleted.aspx">RunWorkerCompleted</a>&#8221; and &#8220;<a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.progresschanged.aspx">ProgressChanged</a>&#8221;  on the same thread. On which the object of &#8220;<a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx" title="BackgroundWorker">BackgroundWorker</a>&#8221; was created. Which in case of Windows form application would be UI Thread. </p>
<p>But, if one uses &#8220;<a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx" title="BackgroundWorker">BackgroundWorker</a>&#8221; class in an Outlook Add In developed using VSTO 4.0. Then &#8220;<a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.runworkercompleted.aspx">RunWorkerCompleted</a>&#8221; works differently and it is raised on different thread then UI Thread. </p>
<p>One of the possible explanation of this behavior can be found <a href="http://stackoverflow.com/questions/7822784/backgroundworker-runworkercompleted-and-threading">here</a>. What it states that only in case of GUI Windows Forms it is suppose to behave that way. Since, <a href="http://stackoverflow.com/questions/7822784/backgroundworker-runworkercompleted-and-threading">BackgroundWorker uses the synchronization model provided by SynchronizationContext.Current to dispatch events. </a></p>
<p>In that case the only thing to rescue is <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired.aspx">InvokeRequired</a> and <a href="http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx">Invoke </a>. Details of How to use these can be found <a href="http://weblogs.asp.net/justin_rogers/pages/126345.aspx">here</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.codemerlin.com/2012/02/backgroundworkers-runworkercompleted-events-weird-behavior-in-outlook-add-in-developed-using-vsto-4-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Delegates in C# Basics and Advanced</title>
		<link>http://www.codemerlin.com/2012/01/delegates-in-c-basics-and-advanced/</link>
		<comments>http://www.codemerlin.com/2012/01/delegates-in-c-basics-and-advanced/#comments</comments>
		<pubDate>Wed, 18 Jan 2012 21:40:19 +0000</pubDate>
		<dc:creator>Mohit Thakral</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.codemerlin.com/?p=214</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, I was reading <a href="http://www.amazon.com/C-Depth-Second-Jon-Skeet/dp/1935182471" title="C# In Depth">C# In Depth, By Jon Skeet</a>. 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.</p>
<p>	1. Delegate is a strongly typed function pointer (Simple but vague)<br />
	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.<br />
	3. Delegate type is like an interface with a method<br />
	4. Delegate type is just another type in C#. A delegate type inherits System.MulticastDelegate which in turn inherits from System.Delegate<br />
	5. Delegate instance has a list of actions/methods (Multicast Delegate). This is called invocation list.<br />
	6. Delegate type uses 2 methods of System.Delegate Class called &#8220;Combine&#8221; and &#8220;Remove&#8221; to add actions/methods as well as remove actions/methods<br />
	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 &#8211; or -= which in turn calls Remove.<br />
	8. &#8220;Invoke&#8221; method causes the invocation of all the actions/methods in the invocation list<br />
	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 &#8220;Delegate.GetInvocationList&#8221;<br />
	10. If any one methods in invocation list throws an exception, Invocation is stopped and remaining methods/actions are not invoked/executed.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codemerlin.com/2012/01/delegates-in-c-basics-and-advanced/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Learn Windows Phone 7 Development , Day-4 : Hello! World &#8211; Deep Dive 3</title>
		<link>http://www.codemerlin.com/2011/07/learn-windows-phone-7-development-day-4-hello-world-deep-dive-3/</link>
		<comments>http://www.codemerlin.com/2011/07/learn-windows-phone-7-development-day-4-hello-world-deep-dive-3/#comments</comments>
		<pubDate>Sun, 17 Jul 2011 20:49:27 +0000</pubDate>
		<dc:creator>Mohit Thakral</dc:creator>
				<category><![CDATA[Windows Phone 7]]></category>
		<category><![CDATA[WP7 Learn-WP7-Series]]></category>

		<guid isPermaLink="false">http://www.codemerlin.com/?p=203</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>In this post I will start from where I left in the <a href="http://www.codemerlin.com/?p=160" target="_blank">last post</a>. 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 <strong>“App.xaml”</strong>. If you open <strong>“App.xaml” </strong>in visual studio you will see following XAML. </p>
<pre class="brush: xml; toolbar: false"><?XML:NAMESPACE PREFIX = [default] http://schemas.microsoft.com/winfx/2006/xaml/presentation NS = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" /><application xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" x:class="WindowsPhoneApplication1.App">

    <!--Application Resources-->
    <application.resources>
    </application.resources>

    <application.applicationlifetimeobjects>
        <!--Required object that handles lifetime events for the application-->
        <shell:phoneapplicationservice launching="Application_Launching" closing="Application_Closing" activated="Application_Activated" deactivated="Application_Deactivated" />
    </application.applicationlifetimeobjects>

</application>
</pre>
<p>Out of the above XAML if you look you will see following 4 events of <strong>“PhoneApplicationService”</strong> class</p>
<ol>
<li>Launching (event handler function is “Application_Launching”)
<li>Closing (event handler function is “Application_Closing”)
<li>Activated (event handler function is “Application_Activated”)
<li>DeActivated (event handler function is “Application_Deactivated”)</li>
</ol>
<p>All of the above mentioned event handler functions are defined in ( you guessed it, right <img src='http://www.codemerlin.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  ) <strong>“App.xaml.cs”</strong>. if you open <strong>“App.xaml.cs” </strong>and look at the comments on these functions, there usage is explained to an extent. </p>
<pre class="brush: c-sharp; toolbar: false">// 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) {
}
</pre>
<p>Before, going into details of these events. One should know a few basic details about application life cycle of Windows Phone 7.&nbsp; </p>
<ol>
<li>First is that an application closes when users clicks the back button, that looks like following icon in windows phone simulator. <img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="WP7Back" border="0" alt="WP7Back" src="http://www.codemerlin.com/wp-content/uploads/2011/07/WP7Back_thumb.png">
<li>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.&nbsp; In this mode application’s process is killed, but the state of application is still maintained by the Windows Phone Operating System.<img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="WP7Home" border="0" alt="WP7Home" src="http://www.codemerlin.com/wp-content/uploads/2011/07/WP7Home_thumb.png"></li>
</ol>
<p> 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 <strong>“Application_Launching”</strong> and <strong>“Application_Closing”</strong>&nbsp; are the events that are raised when application starts(<strong>“Application_Launching”</strong>) and when application closes(<strong>“Application_Closing”</strong>). The other two events are related to application getting out of tombstone mode(<strong>“Application_Activated”</strong>)&nbsp; and getting tombstoned(<strong>“Application_Deactivated”</strong>). </p>
<p>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 <img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://www.codemerlin.com/wp-content/uploads/2011/07/wlEmoticon-smile.png">. See ya.. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.codemerlin.com/2011/07/learn-windows-phone-7-development-day-4-hello-world-deep-dive-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mocking HttpContext, HttpResponse, HttpRequest, HttpSessionState etc. in ASP.Net</title>
		<link>http://www.codemerlin.com/2011/07/mocking-httpcontext-httpresponse-httprequest-httpsessionstate-etc-in-asp-net/</link>
		<comments>http://www.codemerlin.com/2011/07/mocking-httpcontext-httpresponse-httprequest-httpsessionstate-etc-in-asp-net/#comments</comments>
		<pubDate>Sat, 09 Jul 2011 20:13:32 +0000</pubDate>
		<dc:creator>Mohit Thakral</dc:creator>
				<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[ASP.Net Moq UnitTesting]]></category>

		<guid isPermaLink="false">http://www.codemerlin.com/?p=181</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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</p>
<ul>
<li>HttpContext
<li>HttpRequest
<li>HttpResponse
<li>HttpSessionState ( Page’s Session Property’s Type)
<li>HttpApplicationState (Application Property’s Type) </li>
</ul>
<p>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. </p>
<p>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”.</p>
<p>This way all of the components that are dependent on “real class” should be made dependent on&nbsp; “abstract base class”. So, that while unit testing one creates a mock of the “abstract base class”&nbsp; and in real-time execution an object of the wrapper class is passed, that take the real class.</p>
<p>For HttpContext, HttpRequest, HttpResponse,HttpSessionState and HttpApplicationState following are the corresponding classes.</p>
<table style="width: 100%">
<tbody>
<tr>
<td><strong><u>Class to be Mocked</u></strong> </td>
<td><strong><u>Wrapper Class</u></strong> </td>
<td><strong><u>Abstract Class</u></strong></td>
</tr>
<tr>
<td>HttpContext</td>
<td>HttpContextWrapper</td>
<td>HttpContextBase</td>
</tr>
<tr>
<td>HttpResponse</td>
<td>HttpResponseWrapper</td>
<td>HttpResponseBase</td>
</tr>
<tr>
<td>HttpRequest</td>
<td>HttpRequestWrapper</td>
<td>HttpResponseBase</td>
</tr>
<tr>
<td>HttpSessionState</td>
<td>HttpSessionStateWrapper</td>
<td>HttpSessionStateBase</td>
</tr>
<tr>
<td>HttpApplicationState</td>
<td>HttpApplicationStateWrapper</td>
<td>HttpApplicationStateBase</td>
</tr>
</tbody>
</table>
<p>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.</p>
<p>Following is how a class might look like when it is using these objects without worrying about unit testing.</p>
<pre class="brush: c-sharp; toolbar: false">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"]);
        }

    }
}
</pre>
<p>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.</p>
<pre class="brush: c-sharp; toolbar: false">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"]);
        }

    }
}
</pre>
<p>Now, following is one sample of the test. Following test uses <a href="http://nunit.org/" target="_blank">nunit</a> testing framework and <a href="http://code.google.com/p/moq/" target="_blank">Moq</a> mocking framework.</p>
<pre class="brush: c-sharp; toolbar: false">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<httpcontextbase>();
            var mockRequest = new Mock<httprequestbase>();
            var mockResponse = new Mock<httpresponsebase>();
            var mockSessionState = new Mock<httpsessionstatebase>();
            var mockApplication = new Mock<httpapplicationstatebase>();
            var processor = new CreditCardProcessor(mockContext.Object);

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

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

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

            processor.Save();

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

        }
    }
}
</pre>
<p>And finally the production usage would be as following.</p>
<pre class="brush: c-sharp; toolbar: false" style="padding:10px;">
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();
        }
    }
}
</pre>
<p>Please click on following image to download complete code.</p>
<p><iframe style="padding-bottom: 0px; background-color: #fcfcfc; padding-left: 0px; width: 98px; padding-right: 0px; height: 115px; padding-top: 0px" title="Preview" marginheight="0" src="https://skydrive.live.com/embedicon.aspx/CodeMerlin/MockSample?cid=301ab8c691b0f1a8&amp;sc=documents" frameborder="0" marginwidth="0" scrolling="no"></iframe></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codemerlin.com/2011/07/mocking-httpcontext-httpresponse-httprequest-httpsessionstate-etc-in-asp-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Learn Windows Phone 7 Development , Day-3 : Hello! World &#8211; Deep Dive 2</title>
		<link>http://www.codemerlin.com/2011/04/learn-windows-phone-7-development-day-3-hello-world-deep-dive-2/</link>
		<comments>http://www.codemerlin.com/2011/04/learn-windows-phone-7-development-day-3-hello-world-deep-dive-2/#comments</comments>
		<pubDate>Tue, 26 Apr 2011 04:44:24 +0000</pubDate>
		<dc:creator>Mohit Thakral</dc:creator>
				<category><![CDATA[Windows Phone 7]]></category>
		<category><![CDATA[WP7 Learn-WP7-Series]]></category>

		<guid isPermaLink="false">http://devtalk.in/?p=160</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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. </p>
<p>When you compile a Windows Phone 7 Silverlight application, for each <strong>“.xaml”</strong> file 2 files are generated one with name <strong>“Filename.g.cs”</strong> and another one for <strong>“Filename.i.cs”</strong> for example App.xaml would result in <strong>“App.g.cs”</strong> and <strong>“App.i.cs”</strong>, where <strong>“g”</strong> is for generated and <strong>“i”</strong> is intellisense, These files would be in <strong>“obj\Debug”</strong> if your project is compiled in debug mode. There are bunch of other files in <strong>“obj\Debug” </strong>as well these files are file containing list of all of the files, compiled assembly of code behind files, etc. </p>
<p>All <strong>“.cs”</strong> and <strong>“resources”</strong> files are compiled and merged into final output which is nothing but few dlls and resources, Final output is inside <strong>“Bin\Debug”</strong>. These dlls and resource files are then zipped into a one single file which has extension <strong>”.xap”.</strong> This <strong>“.xap”</strong> file would be there in <strong>“Bin\Debug”</strong> as well.This is the file that is deployed to the Windows Phone.</p>
<p>Let us talk about the workflow of the program. If you open <strong>“App.xaml.cs” </strong>(This file is there in visual studio solution). You will see following code in the constructor.</p>
<pre class="brush: c-sharp; toolbar: false">
        /// &lt;summary&gt;
        /// Constructor for the Application object.
        /// &lt;/summary&gt;
        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();
        }</pre>
<p><strong></strong></p>
<p>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 <strong>“InitializeComponent()”</strong> and the other one is <strong>“InitializePhoneApplication()”</strong>.&#160; <strong>“InitializeComponent()”</strong> 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 <strong>“InitializePhoneApplication()” </strong>is specific function used for the initialization specific to phone. </p>
<pre class="brush: c-sharp; toolbar: false">        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;
        }</pre>
<p>As you can see in the method <strong>“InitializePhoneApplication()”</strong>&#160; 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 <strong>“PhoneApplicationFrame”</strong> and assign that object to its property called <strong>“RootFrame”</strong> . Then, It will bind an event handler <strong>”CompleteInitializePhoneApplication”</strong> to the event <strong>“Navigated”</strong> of the <strong>“RootFrame”</strong> , and at the end following code would be executed When this <strong>“RootFrame” </strong>would be Navigated to and that would be as soon as the application loads. </p>
<pre class="brush: c-sharp; toolbar: false">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;
        }</pre>
<p>&#160;</p>
<p>Which will make sure that <strong>“RootVisual” </strong>Property of the <strong>“App” </strong>class is set to <strong>“RootFrame”</strong>&#160; and then it will remove the handler bindings. </p>
<p>In the next post we will talk about handling the application level events that are registered in with <strong>“PhoneApplicationService”</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codemerlin.com/2011/04/learn-windows-phone-7-development-day-3-hello-world-deep-dive-2/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Learn Windows Phone 7 Development , Day-2 : Hello! World &#8211; Deep Dive 1</title>
		<link>http://www.codemerlin.com/2011/04/learn-windows-phone-7-development-day-2-hello-world-deep-dive-1/</link>
		<comments>http://www.codemerlin.com/2011/04/learn-windows-phone-7-development-day-2-hello-world-deep-dive-1/#comments</comments>
		<pubDate>Mon, 25 Apr 2011 04:39:23 +0000</pubDate>
		<dc:creator>Mohit Thakral</dc:creator>
				<category><![CDATA[Windows Phone 7]]></category>
		<category><![CDATA[WP7 Learn-WP7-Series]]></category>

		<guid isPermaLink="false">http://devtalk.in/2011/04/learn-windows-phone-7-development-day-2-hello-world-deep-dive-1/</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday we build the “Hello! World” application. Today, we will have a look at the files that got created when we created the project.</p>
<p>Following is the list of files that are visible in Solution Explorer Visual Studio</p>
<li><strong><u>AppManifest.xml</u></strong> – 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 (<a href="http://www.codeproject.com/KB/silverlight/QuestionsOnSilverlight.aspx#_Toc263879427">http://www.codeproject.com/KB/silverlight/QuestionsOnSilverlight.aspx#_Toc263879427</a>) </li>
<li><strong><u>AssemblyInfo.cs</u></strong> – This is standard file of any .Net project. It contains Assembly related info like version, title, company etc.. </li>
<li><strong><u>WMAppManifest.xml</u></strong> – 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 (<a href="http://msdn.microsoft.com/en-us/library/ff769509%28v=vs.92%29.aspx">http://msdn.microsoft.com/en-us/library/ff769509%28v=vs.92%29.aspx</a>) </li>
<li><strong><u>App.xaml</u></strong> – 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.&#160; 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 </li>
<li><strong><u>App.xaml.cs</u></strong> -&#160; This is kind of code behind file for <strong><u>“App.xaml”</u></strong>. It contains a partial class called “App” that is specified in App.xaml’s markup as well.&#160; 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 <strong><u>“App.xaml”</u></strong>. </li>
<li><strong><u>ApplicationIcon.png</u></strong> – 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 <strong><u>“WMAppManifest.xml”</u></strong> .</li>
<li><strong><u>Background.png</u></strong> – 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 <strong><u>“WMAppManifest.xml”</u></strong>. </li>
<li><strong><u>MainPage.xaml</u></strong> – 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).&#160; This file is also specified in “<strong><u>WMAppManifest.xml”</u></strong>.</li>
<li><strong><u>MainPage.xaml.cs</u></strong> – This file is the code behind file of <strong><u>“MainPage.xaml”</u></strong>, and as you can see it is partial class with just one constructor and call to a method “InitializeComponent”.</li>
<li><strong><u>SplashScreenImage.jpg</u></strong> – 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”</li>
<p>&#160;</p>
<p>In next post I will explain the Markup of <strong><u>“App.xaml”</u></strong> and&#160; <strong><u>“MainPage.xaml”</u></strong>, and basic working of the application.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codemerlin.com/2011/04/learn-windows-phone-7-development-day-2-hello-world-deep-dive-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Learn Windows Phone 7 Development , Day-1 : Hello! World</title>
		<link>http://www.codemerlin.com/2011/04/learn-windows-phone-7-development-d1-hello-world/</link>
		<comments>http://www.codemerlin.com/2011/04/learn-windows-phone-7-development-d1-hello-world/#comments</comments>
		<pubDate>Sun, 24 Apr 2011 05:08:35 +0000</pubDate>
		<dc:creator>Mohit Thakral</dc:creator>
				<category><![CDATA[Windows Phone 7]]></category>
		<category><![CDATA[WP7 Learn-WP7-Series]]></category>

		<guid isPermaLink="false">http://devtalk.in/2011/04/learn-windows-phone-7-development-d1/</guid>
		<description><![CDATA[Disclaimer ::&#160; 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 [...]]]></description>
			<content:encoded><![CDATA[<p><strong><u>Disclaimer ::</u></strong>&#160; 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.</p>
<p><strong><u>Task ::</u></strong>&#160; Write a window phone 7 app that shows “Hello! World”.</p>
<p>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</p>
<ul>
<li>Visual Studio 2010 </li>
<li>Windows Phone 7 Emulator </li>
</ul>
<p>You can download one integrated package of tools from this link(<a href="http://create.msdn.com/en-us/home/getting_started">http://create.msdn.com/en-us/home/getting_started</a>) .&#160; </p>
<p>Let us get started. After installing tools Open Visual Studio or Visual Studio Express. Press Ctrl + Shift + N or go to&#160; File –&gt; New –&gt; 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).</p>
<p>Let us keep the project name as it is(WindowsPhoneApplication1) only. New project dialogue should look like following </p>
<p><a href="http://devtalk.in/wp-content/uploads/2011/04/New_Project.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="New_Project" border="0" alt="New_Project" src="http://devtalk.in/wp-content/uploads/2011/04/New_Project_thumb.png" width="570" height="327" /></a></p>
<p>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])</p>
<p><a href="http://devtalk.in/wp-content/uploads/2011/04/MainScreen.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="MainScreen" border="0" alt="MainScreen" src="http://devtalk.in/wp-content/uploads/2011/04/MainScreen_thumb.png" width="580" height="328" /></a></p>
<p>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. </p>
<p>Press F5 now to run the project in debugging mode.&#160; Visual Studio will make a build of the project and show you the Windows Phone 7 Emulator which will look like following.</p>
<p><a href="http://devtalk.in/wp-content/uploads/2011/04/WinPhone7Emulator.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="WinPhone7Emulator" border="0" alt="WinPhone7Emulator" src="http://devtalk.in/wp-content/uploads/2011/04/WinPhone7Emulator_thumb.png" width="149" height="274" /></a></p>
<p>It will take some time in loading your application for the first time, then you will see your application running in emulator. </p>
<p>Now go back to Visual Studio with out closing the emulator. Press( Shift + F5) or Debug –&gt; Stop Debugging.&#160; Go to XAML Source View(the one in the right) . Try finding text ‘Text=”page name”’ Change ‘page name’ to ‘Hello! World’.</p>
<p>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).&#160; </p>
<p>Final Output</p>
<p><a href="http://devtalk.in/wp-content/uploads/2011/04/WinPhone7Emulator-2.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="WinPhone7Emulator-2" border="0" alt="WinPhone7Emulator-2" src="http://devtalk.in/wp-content/uploads/2011/04/WinPhone7Emulator-2_thumb.png" width="171" height="307" /></a></p>
<p>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 </p>
<p>Feel free to ask question via comment section. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.codemerlin.com/2011/04/learn-windows-phone-7-development-d1-hello-world/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Performance Tips for ASP.Net</title>
		<link>http://www.codemerlin.com/2011/01/performance-tips-for-asp-net/</link>
		<comments>http://www.codemerlin.com/2011/01/performance-tips-for-asp-net/#comments</comments>
		<pubDate>Fri, 28 Jan 2011 05:02:35 +0000</pubDate>
		<dc:creator>Mohit Thakral</dc:creator>
				<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[Performance ASP.Net]]></category>

		<guid isPermaLink="false">http://devtalk.in/?p=69</guid>
		<description><![CDATA[Performance Tips from Microsoft Consulting Team UK.. http://blogs.msdn.com/b/mcsuksoldev/archive/2011/01/19/common-performance-issues-on-asp-net-web-sites.aspx]]></description>
			<content:encoded><![CDATA[<p>Performance Tips from Microsoft Consulting Team UK..</p>
<p><a href="http://blogs.msdn.com/b/mcsuksoldev/archive/2011/01/19/common-performance-issues-on-asp-net-web-sites.aspx">http://blogs.msdn.com/b/mcsuksoldev/archive/2011/01/19/common-performance-issues-on-asp-net-web-sites.aspx</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codemerlin.com/2011/01/performance-tips-for-asp-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Correct Usage of Finalize and Dispose</title>
		<link>http://www.codemerlin.com/2010/10/correct-usage-of-finalize-and-dispose/</link>
		<comments>http://www.codemerlin.com/2010/10/correct-usage-of-finalize-and-dispose/#comments</comments>
		<pubDate>Mon, 18 Oct 2010 04:42:20 +0000</pubDate>
		<dc:creator>Mohit Thakral</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://devtalk.in/?p=62</guid>
		<description><![CDATA[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. [...]]]></description>
			<content:encoded><![CDATA[<p>Couple of day back I was reading an article by Jimmy Bogard <a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2010/05/19/dependency-injection-in-asp-net-mvc-views.aspx"> Dependency Injection in ASP.NET MVC: Views</a>. 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 </p>
<pre class="brush: csharp; title: ; notranslate">
 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;
    }
</pre>
<p>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</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codemerlin.com/2010/10/correct-usage-of-finalize-and-dispose/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>IEnumerable and Datareader &#8216;Yield return&#8217; issue</title>
		<link>http://www.codemerlin.com/2010/10/ienumerable-and-datareader-yield-return-issue/</link>
		<comments>http://www.codemerlin.com/2010/10/ienumerable-and-datareader-yield-return-issue/#comments</comments>
		<pubDate>Mon, 18 Oct 2010 04:35:03 +0000</pubDate>
		<dc:creator>Mohit Thakral</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://devtalk.in/?p=70</guid>
		<description><![CDATA[Recently, while working on one of my organization&#8217;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&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, while working on one of my organization&#8217;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&#8217;t we using any ORM. We still want to use legacy data layer(organization&#8217;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 </p>
<pre class="brush: csharp;">public static IEnumerable&lt;T&gt; MapTo&lt;T&gt;(this IDataReader reader) where T : new()
{
    return reader.MapTo&lt;T&gt;(null);
}

public static IEnumerable&lt;T&gt; MapTo&lt;T&gt;(this IDataReader reader, Action&lt;IDataReader, T&gt; customMappingFunction) where T : new()
{
    using (reader)
        while (!reader.IsClosed &amp;&amp; reader.Read())
        {
            var nextItem = new T();
            nextItem.InjectFrom&lt;DataReaderInjection&gt;(reader);
            if (customMappingFunction != null)
                customMappingFunction(reader, nextItem);
            yield return nextItem;
        }
}</pre>
<p>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, </p>
<pre class="brush: csharp;">// 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&lt;Employee&gt;();
Console.WriteLine(listOfEmployee.Count());
Console.WriteLine(listOfEmployee.Count()); </pre>
<p>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.</p>
<p align="left">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; 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&lt;T&gt;(). otherwise you can lose the IEnumerable&lt;T&gt;.</p>
<p>Code of DataReader Injection Class (This class is based on <a href="http://valueinjecter.codeplex.com/">OMU Value Injector</a>)</p>
<pre class="brush: csharp;">public class DataReaderInjection : KnownSourceValueInjection&lt;IDataReader&gt;
{
    protected override void Inject(IDataReader source, object target, PropertyDescriptorCollection targetProps)
    {
        for (var i = 0; i &lt; 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);
        }
    }
} </pre>
]]></content:encoded>
			<wfw:commentRss>http://www.codemerlin.com/2010/10/ienumerable-and-datareader-yield-return-issue/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

