Sunday, December 26, 2010

Calendar Control for Windows Phone 7 (WP7)

For my first WP7 application, Diabetes Manager, I needed a calendar control that would give users an easy way to enter their daily data. Unfortunately WP7 does not provide any calendar control; it does provide a Date and Time picker. But the picker control did not work for me as far as user experience is concerned. And since I did not find anything on the internet, I decided to write my own.

My calendar control gives users a view of the entire month and  they can click on any day to enter data for that day. The control is made up of two sections :

a) Month and Year selector at the top and
b) Grid of days at the bottom.

Users can navigate between months by clicking on left/right buttons and selecting a day would launch a data entry form.
The calendar control also provides visual cues via color scheme. For instance dates with no data are indicated with default white color; whereas dates with data are indicated with yellow color. Current date is indicated by Orange color.
The rounded rectangles are achieved by using a combination of Rectangle Shape with rounded borders and transparent button (which makes it click able).

IMPORTANT:  To display the different color schemes (white, yellow, orange) for different states, I initially set the Foreground property of the Button. But it would always revert back to the original color (White in this case). The workaround is to define button styles for various states in XAML as shown here and use it in the code as follows:

btn.Style = this.Resources["HasDataButtonStyle"] as Style;

I posted the entire source code for this control on Codeplex:

Monday, November 29, 2010

My first Windows Phone 7 App

Diabetes Manager is my first Windows Phone 7 App. It allows users to set target, track their daily blood glucose levels and also monitor progress.

WP7: Diabetes Manager App from Collective Wisdom on Vimeo.

Friday, September 10, 2010

Using WinDBG to debug .NET 2.0+ applications

To analyze memory dumps of applications using .NET 2.0 and above use the following command:
".loadby sos mscorwks"

This command loads SOS for .NET Framework 2.0.

WinDBG/SOS Cheat Sheet

Update 06/10/2011:

For .NET 4 use ".loadby sos clr"
(source :

Friday, September 03, 2010

WCF InstanceManagement Summary

In WCF, the service instance is a product of binding, contract configuration (SessionMode property on ServiceContract) and service behavior (InstanceContextMode on ServiceBehavior).

The following table summarizes this:

BindingServiceContractAttribute.SessionModeInstanceContextModeAsync Dispose()Service Instance Mode

(behavior of service instance)
TCP, IPCAllowed/RequiredPerCallNoPerCall
WS (no security,no reliability)Allowed/NotAllowedPerCall/PerSessionYesPerCall
WS (with security or reliability)Allowed/RequiredPerSessionYesPerSession
WS (with security or reliability)NotAllowed (setting valid because WS implements application level session)PerCall/PerSessionYesPerCall


Saturday, May 12, 2007

The underlying connection was closed: The request was canceled.

The Problem:
Couple of weeks back I was investigating a problem with an ASP.NET web application. During the course of normal day and under normal load the server would suddenly stop responding, shooting up the response time and ultimately causing timeouts for the end users. ASP.NET performance counters showed that at this time all the requests were getting queued up and the CPU usage dropped to zero!

Now request queuing is not a bad thing if the CPU is being utilized properly - it just means that the server has reached it's capacity and we need to add more servers to scale the application. But in my case the CPU was not being used at all. This suggested that there was some kind of "thread locking". All the threads were waiting on something to get released. This symptom lasted for 20-30 seconds and then the server recovered with request Queue reducing to 0 and CPU utulization going back to it's original 30%-40%.

A little background on our web application: It consists of a page made up of 4-5 sections which displays content from a variety of external sources (all web services). So on every request it was making about 4-5 XML/HTTP calls to external web services and then applied XSLT to generate HTML snippets and finally assemble the page. As it involved multiple remote calls, the developer used asynchronous delegates to execute these calls in parallel and then waited for these calls to return using the "WaitHandle.WaitAll()". So this piece of code was my prime suspect for the following reasons: Asynchronous delegates use thread from the worker thread pool to make the async call and in case of our application it was making 4-5 async calls, which means each request has the potential for using 4-5 more threads from the thread pool. And if the web services were slow in responding, as more requests come in more worker threads will be used from the queue and ultimately lead to request queuing. (BTW Fritz Onion has written an excellent article about asynchronous delegates and it's pitfalls)

To test this theory I modified the code and made all the calls synchronous in an attempt to reduce the usage of threads from the worker thread pool per request. But when I perf tested this code I saw the same behavior!! The CPU dropped again!

I did another perf testing and this time I was watched the socket connections opened from our app to the external systems using the "netstat -ap TCP" command. And I saw this interesting behavior; at the beginning of the perf test, as I was slowly ramping up the virtual users (total 30 vusers, ramping 1 per sec), even with 10 vusers there were only 3-4 outgoing socket connections. This means that the web services were responding so fast that 3 socket connections were sufficient to serve 10 users. The CPU was being properly utilized at this time (10%-15%). When the ramp reached 20 vusers everything just froze!! The CPU suddenly dropped, requests started queuing and the number of socket connections were still 3! Then the next instant the number of socket connections suddenly jumped to 20, the CPU went back to normal 20% utilization and there were no request queuing!

The Cause:
My theory based on the above observation is that when the application first starts there are very few threads available in the pool to service remote requests. As load increases the few threads cannot handle the requests and so ASP.NET runtime tries to create more threads and when this happens it freezes all other threads (don't know why) and you see the CPU drop.

The Solution : "minFreeThreads"!
I searched a lot on the internet without much success until at last I found this Microsoft Knowledge Base Article 821268 which confirmed my theory. The solution is to add a new attribute called "minWorkerThreads" to the section of machine.config
 // minWorkerThreads = maxWorkerThreads/2

ASP.NET by default has only 1 thread allocated for remote calls! So even if you configured your machine.config with the recommended settings of "maxConnections=24" and "maxWorkerThreads=100" (see my post below for more info) you are just setting the maximum value! It doesn't mean the pool starts with 24 threads ready for making outgoing calls! And the most surprising thing is that by default this entry is missing from the machine.config!

So if you are facing with a similar problem with your ASP.NET app that makes remote calls try adding this entry. This simple fix may just solve your problem!

P.S : There are different kinds of "The underlying connection was closed: " errors. Here's a link to a Microsoft blog ( that explains most of these errors and how to fix them. Unfortunately it doesn't cover the error message that I encountered ("the request was canceled").

Wednesday, December 07, 2005

Tuning ASP.NET thread settings for optimum performance

To get an optimum performance out of ASP.NET Web Application you may need to change the following settings in machine.config. The following text has been reproduced from MSDN article on ASP.NET preformance optimizations

maxconnection. If your application makes calls to a remote Web service and the requests are waiting for the call to complete, you can increase the CPU utilization and your application performance by changing the maxconnection attribute.

maxWorkerThreads and maxIoThreads. These attributes define the maximum number of worker and I/O threads that the ASP.NET worker process is allowed to create. These values do not reflect the actual number of threads that are created by the worker process. The maximum value for these attributes is 100 per processor.

minFreeThreads. This attribute defines the number of threads that can be used for work other than processing incoming requests to the worker process. This attribute prevents the ASP.NET process from using a thread from the thread pool to handle a new HTTP request if this would mean that the free thread count drops below this limit. The attribute is specified on the element and has a default value of 8.

You can use this attribute to help prevent deadlocks by ensuring that a thread is available to handle callbacks from pending asynchronous requests. A deadlock can occur if all of the threads in the thread pool are currently in use handling incoming HTTP requests, and one or more of those requests are waiting for asynchronous callbacks. In this situation, there are no available threads to service the callback. You can set minFreeThreads to ensure that some free threads are available to process the callbacks.

  • maxconnection = 24 (threads used to make remote web service calls)
  • minFreeThreads = 176 (threads kept reserved for serving non-request calls)
  • minLocalRequestFreeThreads = 152
  • maxWorkerThreads = 100 (Maximum number of worker threads per CPU in the thread pool)
  • maxIoThreads = 100 (Maximum number of IO threads per CPU in the thread pool)

No of threads for processing incoming requests : (#CPU * maxWorkerThreads) – (#CPU * minFreeThreads)

Wednesday, November 23, 2005

XSLT for trimming RSS results

Recently I was working on a project where there was a requirement to display only a specified number of items returned by a RSS Feed (instead of all the items).

This XSLT will trim the results of an RSS Feed. Set appropriate value to "resultcount" parameter.

<?altova_samplexml C:\junk\rss.xml?>
<xsl:stylesheet version="1.0" xmlns:xsl="">

<xsl:param name="resultcount">2</xsl:param>
<!-- Identity transform, passes nodes through untouched -->
<xsl:template match="@*|node()|text()">
<xsl:apply-templates select="@*|*|text()"/>
<!-- Match the item nodes. -->
<xsl:template match="item">
<position><xsl:value-of select="count(preceding::item)"/></position>
<xsl:if test="count(preceding::item) < $resultcount">
<xsl:apply-templates select="@*|*|text()"/>