Category Archives: Quickbytes

QuickBytes: ASP.NET InProc Session and Multiple Workers (don’t go well together)

Last week I hit an unusual roadblock while testing an ASP.NET MVC application. The application started behaving unpredictably and session state went haywire (returned null, flipped values etc. etc.).

Since it was happening after deployment, it was a bit of a bother to debug, but I realized it was a configuration issue more than anything else. So while digging through the web.config I discovered state management was set to InProc. This of course implies your session is alive as long as AppPool is alive and as soon as it is recycled your session is gone.

Still unable to see what’s wrong with InProc and what was possibly recycling the app pool, I decided to redeploy the same application in a new website on the same machine using a new Application Pool. Voila! Everything started working. Couldn’t repro the state corruption (state variables were going null) issue anymore.

Next we assigned the new site the existing AppPool (that was being used by the site where things were getting corrupted). The issues came back. This narrowed it down to AppPool settings issue. After a side by side comparison of the settings, we found that the Number of Workers was 5 for the site where things were goofing up, while the new deployment’s AppPool has the value set to 1. That’s when we struck gold.

At this point a quick search revealed how Number of Workers work and it was amply clear why things were going south.

Multiple Workers, Web Garden and InProc State management

Number of Workers > 1 basically creates a ‘Web Garden’ scenario on your server where there are multiple worker processes handling requests for your site. Each worker process is essentially an instance of the same executable with independent static references and also obviously, independent state management (when state management is InProc). As a result of this two requests to the same server may or may not be served by the same worker process. Since state is not shared between the worker processes you are going to get unpredictable behavior when the second request goes to a different worker as compared to the first request.

This is actually correct behavior because Web Garden setup of a Web Server implies that you are managing state out of process via a reliable backing store like SQL Server. So if you don’t have an out of Proc state manager, don’t use more than one Worker Processes in your App Pool. Alternatively if you want multiple worker processes (better scaling) you have to use out of process state management.


Tagged , , ,

QuickBytes: Decimal to Indian Numeric formatting


Recently I came across the need to format Decimal as Currency, but force it down to Indian/Vedic/South Asian numeric formatting (thousands, lacs, crores etc.) instead of the standard Arabic/Metric system (thousands, hundred thousands, million, billion etc.).

The answer was easily found in this StackOverflow thread. The code snippet is reproduced here:

string fare = “123000.0000”;
decimal parsed = decimal.Parse(fare,
CultureInfo hindi = new CultureInfo(“hi-IN”);
string text = string.Format(hindi, “{0:c}”, parsed);

The above code gives us the following string

₹ 1,23,000.00

However, the next requirement was to keep the decimals and formatting but remove the Currency symbol. Another quick search gave us this little gem from Jon Skeet on StackOverflow. Essentially he extracted the NumberFormatInfo from the CultureInfo and reset the Currency Symbol to an empty string. Then use the NumberFormatInfo instance to format the decimal value. So the above code can be modified as follows:

string fare = “123000.0000”;
decimal parsed = decimal.Parse(fare,
CultureInfo hindi = new CultureInfo(“hi-IN”);
NumberFormatInfo hindiNFO =
hindiNFO.CurrencySymbol = string.Empty;

string text = string.Format(hindiNFO, “{0:c}”, parsed);

This gives us the following string. It’s difficult to see here but there is a leading space that you might want to trim if you need to.


A Sample Application

I thought it would be a fun project to write some code that gives you the above code for any Culture Code you want, so I setup a basic ASP.NET project and deployed it for free on the AzureWebsites. You can see it in action here – Currency Formatter on Azure WebSites

  • I spun up Visual Studio 2013 and setup a default MVC project.
  • Next I updated KnockoutJS to the latest version

PM> update-package KnockoutJS

  • Added an Entity to encapsulate the culture information. I referred to this list on MSDN as my source.

public class IsoCultureInfo
    public int Id { get; set; }
    public string LanguageCultureName { get; set; }
    public string DisplayName { get; set; }
    public string CultureCode { get; set; }
    public string ISO639xValue { get; set; }

  • Scaffolded up an EntityFramwork controller: CultureInfoController
  • Added two methods to the CultureInfoController that return JsonResults
  • The first one simply returns the entire list of IsoCultureInfo objects in the DB

public JsonResult List()
    return Json(db.IsoCultureInfoes.ToList(), JsonRequestBehavior.AllowGet);

  • The second one formats the predefined text based on the incoming Culture Name and returns the formatted text as a JSON object.

public JsonResult FormattedText(string id)
         string fare = "123000.0000";
         decimal parsed = decimal.Parse(fare, CultureInfo.InvariantCulture);
         CultureInfo cultureInfo = new CultureInfo(id);
         NumberFormatInfo cultureNFO = (NumberFormatInfo)
         //cultureNFO.CurrencySymbol = string.Empty;
         string text = string.Format(cultureNFO, "{0:c}", parsed);
         return Json(new { formattedCurrency = text });
      catch (Exception ex)
          return Json(new { formattedCurrency = "N/A" });

  • Both these methods are invoked from the Index HTML. The UI is databound to a Knockout ViewModel. This is defined in the script formatCurrency.js

/// <reference path="_references.js" />

var isoCultureInfo = {
    LanguageCultureName : ko.observable(“”)

var viewModel = {
    dataList: ko.observableArray([]),
    formattedString: ko.observable(“Test”),
    selectedCulture: ko.observable(isoCultureInfo)

$(document).ready(function () {
            type: “GET”,
            contentType: “text/json”
        }).done(function (data) {
            viewModel.dataList = ko.mapping.fromJS(data);

                if (newValue.LanguageCultureName() != ”) {
                    var data = { “id”: newValue.LanguageCultureName() };
                            type: “POST”,
                            contentType: “application/json”,
                            data: JSON.stringify(data)
                        }).done(function (data) {
                        }).error(function (args) {
        }).error(function () {


  • Finally I updated the Index.cshtml of the Home Controller to show the dropdown with the list of culture info.

        Select Culture: <select id="cultureOptions"
                                data-bind="options: dataList(), optionsText: 'LanguageCultureName', value: selectedCulture, optionsCaption: 'Choose...'"></select>

  • Added a <ul> to show all the property values of the selected Culture

    <li>Language Culture Name: <b><span data-bind="text: LanguageCultureName"></span></b></li>
    <li>Display Name: <b><span data-bind="text: DisplayName"></span></b></li>
    <li>Culture Code: <b><span data-bind="text: CultureCode"></span></b></li>
    <li>ISO 639x Value: <b><span data-bind="text: ISO639xValue"></span></b></li>

  • Next we have a <pre> section which contains the code that changes as per the selected Culture.

string fare = “123000.0000”;
decimal parsed = decimal.Parse(fare, CultureInfo.InvariantCulture);
CultureInfo cultureInfo = new CultureInfo(<b><span id=”currentCulture” data-bind=”text: LanguageCultureName”></span></b>);
NumberFormatInfo cultureNFO = (NumberFormatInfo)cultureInfo.NumberFormat.Clone();
// If you don’t want the CurrencySymbol, uncomment the following line
// cultureNFO.CurrencySymbol = string.Empty;
string text = string.Format(cultureNFO, “{0:c}”, parsed);

  • Finally we have a span to show the formatted string returned after we have selected the Culture Info

Formatted String: <b><span data-bind="text: $parent.formattedString"></span></b>


The code snippet changes as you select the Culture Info in the dropdown and you can copy paste it directly. I deployed it on a free Azure Website, how? That’s for another day Smile.

Tagged , ,

QuickBytes: Who’s afraid of Github? (Downloading code without cloning)

I often get mails requesting for code in zip files, even though almost all my code is in Github. The articles I wrote of and are pretty much all in their respective Github Repositories. Often newbies are a little confused/scared of Github and leave the sample alone assuming they have to do ‘complex’ things like have Github account/client to get the code.

However this is not the case. The nice folks at Github already thought of this and provide a very handy ‘Download ZIP’ button. You don’t have to login or create a Github account to download the zip of an OSS project (which is to say if you can access the project you can download the zip).


As you can in the screenshot above, I am not logged in, and yet I can download the zip file of the code of one of my articles.

Hopefully, now you won’t be ‘scared’ of Github code repositories any more! Have fun!

Tagged ,

QuickBytes: Visual Studio 2013 and JavaScript Debugging

Yesterday I found out something new about Visual Studio. Documentation indicates that it has been with us since VS 2012 (maybe earlier) but I encountered it yesterday.

I have a MVC4 project created in VS2010 and some CSHTML files have accrued some JavaScript crud in form of inline <script>…</script>. I usually refactor them out whenever I can but yesterday I was doing something else and wasn’t in a position to refactor the code at that point. So I tried to put in a breakpoint inside one of these script chunks and I couldn’t. So far, I’ve put breakpoints in the runtime page that comes up in Visual Studio’s Solution Explorer and they were are hit when executing in the browser, but yesterday I couldn’t even set a breakpoint.

After a little bit of ducking around I found that you could add the following line in the JavaScript to force the debugger where you want to start debugging and then continue with F10/F11 as usual


I was initially indignant at Visual Studio that it ‘made’ me do this by default instead of allowing me to set the breakpoint. Looks a step backward, but then I realized that it was likely some setting in my Dev Setup is not right. I haven’t had a chance to investigate what’s not right, and I used the above hack to resolve my current issues. If you know of a way that kicks VS2013 into enabling breakpoints in inline JS code, do let me know.

Inline JS code is BAD and shouldn’t be used, period. But at times when you are prototyping you tend to take liberties, also not everyone in the team has 15 years of experience writing code, so cruft sometimes comes in. If VS is forcing my hand by making me write clean JavaScript code by default, that’s good, but I also want to know the ‘evil’ way to workaround Winking smile, Cheers!

Tagged , ,

QuickBytes: Hacking up the color of a WinRT ProgressBar

WinRT never ceases to throw a curveball at the you. I was trying to change the default ‘Violet’ color of the ProgressBar and ProgressRing to something more ‘in tune’ with my app’s style, but the only ‘violet’ color visible was the Foreground property, but changing it did nothing to change the color of the ‘running dots’.

After ‘ducking’ around I found a Brush called ProgressBarIndeterminateForegroundThemeBrush. There are two ways to override it.

1. Create a resource with the same name and assign a different color. You can do it in your App.xaml or in the XAML of the screen you need it updated in as follows:


2. Update the color at runtime in code. I found this article that might come in handy.

Hope this helps someone, it’s a note for me anyway!

Tagged ,
%d bloggers like this: