Recent Posts

Weekly digest #2

June 23, 2012

SignalR – Group Notifications, Dane-Garrin Balia: The aim of what we will be trying to accomplish in this tutorial is to create a sample Broadcast Notification System using SignalR where specific groups can receive “notifications” in real time, from an external application.

ExecutionContext vs SynchronizationContext, Stephen Toub: I’ve been asked a few times recently various questions about ExecutionContext and SynchronizationContext, for example what the differences are between them, what it means to “flow” them, and how they relate to the new async/await keywords in C# and Visual Basic.  I thought I’d try to tackle some of those questions here.

The Three Models of ASP.NET MVC Apps, Dino Esposito: When you use the standard project template for creating ASP.NET MVC 3 applications in Visual Studio 2010, the newly created project comes with a predefined folder named Models. The Models folder goes hand-in-hand with two other predefined folders called Views and Controllers. Models, Views, and Controllers form the triad of roles that underlie any application that conforms to the popular MVC (Model-View-Controller) design pattern.

C# 5.0 Async Tips and Tricks Part 1, Jérôme Laban: This article is a discussion about how C#5.0 async captures the executing context when running an async method, which allows to easily stay on the UI Thread to access UI elements, but can be problematic when running CPU-bound work. Off of the UI thread, an async method may jump from thread to thread, breaking thread context dependent code along with it.

IIS Best Practices, CenkIscan: For a very long time, I have been asked for a document on IIS best practices. There are some blogs/articles on the Internet but I could not find a complete one. Actually, the main problem here is that there can not be “best practices” for a web server. A web server is just a hosting platform for applications, and, each and every application has its own needs. Therefore, in many cases, you will not have one universal best practice.

A Gentle Reintroduction to the Reactive Extensions for JavaScript Part 1, Matthew Podwysocki: In the previous post, I briefly covered that yes, the Reactive Extensions for JavaScript is alive, with two releases to show for it.  Before going into the depths of what’s in the box for V1 and V2, I want to step back and cover some of the basics and why you might care about this library.  It’s great to talk about APIs and general capabilities, but let’s first cover asynchronous and event-based programming in JavaScript today.

Getting started with Lucene.NET–Searching, Ricci Gian Maria: In the previous part I’ve showed how easy is to create an index with lucene.net, but in this post I’ll start to explain how to search into it, first of all what I need is a more interesting example, so I decided to download a dump of stack overflow, and I’ve extracted the Posts.Xml file (10 GB of XML file), then I wrote this simple piece of text to create the lucene index.

The theory behind covariance and contravariance in C# 4, Tomáš Petříček: In C# 4.0, we can annotate generic type parameters with out and in annotations to specify whether they should behave covariantly or contravariantly. This is mainly useful when using already defined standard interfaces. Covariance means that you can use IEnumerable in place where IEnumerable is expected. Contravariance allows you to pass IComparable as an argument of a method taking IComparable.

Weekly digest: 9 June, 2012

June 09, 2012

A gentle introduction to Backbone with jQuery, Rocky Jaiswal:Backbone is a great JavaScript framework, I am sure most developers would have heard about it. I spent some time learning Backbone and want to share the little I have learned so far.

Types of Duplication in Code, John Sonmez:One of the biggest reasons to refactor code is to eliminate duplication.  It is pretty easy to introduce duplication in our code either unintentionally or because we don’t know how to prevent or get rid of it.

AspectMap – Aspect Oriented Programming for Complete Beginners, Chris Surfleet:In computing, aspect-oriented programming (AOP) is a programming paradigm which aims to increase modularity by allowing the separation of cross-cutting concerns

ASP.NET for Mobile, One ASP.NET and Realtime ASP.NET with Signalr - Video of Scott Hanselman’s talks in Russia:The English versions of my three talks (plus one open Q&A sesssion) are now all up for your viewing pleasure.

Differences Between NHibernate and Entity Framework, Ricardo Peres:NHibernate and Entity Framework are two of the most popular O/RM frameworks on the .NET world. Although they share some functionality, there are some aspects on which they are quite different. This post will describe this differences and will hopefully help you get started with the one you know less. Mind you, this is a personal selection of features to compare, it is by no way an exhaustive list.

How to create list of anonymous types

August 07, 2011

I was writing a method and I needed to loop through a collection of objects, collecting a couple of fields of those objects based on some business conditions and store them into a temporary data structure. Anonymous type came into my mind right away. But how to store those anonymous types into a list? I googled without giving much thought and guess what – there is indeed a way and i liked it.

var listOfAnonymoustTypes = new[] { new { Id=1, Name="Name" }}.ToList();
That’s it. It is that easy and intuitive. Following contains the detailed discussion on this topic.
[http://kirillosenkov.blogspot.com/2008/01/how-to-create-generic-list-of-anonymous.html](http://kirillosenkov.blogspot.com/2008/01/how-to-create-generic-list-of-anonymous.html)

Firebird server (Fbserver) command line switches

April 12, 2011

Following table contains most common Firebird server command line switches.

-a run as **a**pplication. Applicable only if Firebird runs as application.  -n **n**o icon in the system tray. Applicable if Firebird runs as application.  -b run with high (**b**oosted) priority.  -r run with normal priority. This is default priority.  -p specify **p**ort number/name or named pipe.  -i accept tcp/**i**p connections.   -l accept **l**ocal connections  -w accept NETBEUI connections. 

Reference - http://www.volny.cz/iprenosil/interbase/fbserver_switches.htm

How to use gfix on Windows

April 05, 2011

gfix -user SYSDBA -password masterkey localhost:C:\MyDatabase.fdb -v -f gfix is Firebird’s command line tool for administration issues like data repair, sweeping etc. Above is the syntax for how to use this tool on a Windows machine.

  • gfix.exe is located in your Firebird installation directory.

  • -v option in the above example specifies that we want to validate the database.

  • -f options means full to mean all records and pages and release unassigned record fragments.

  • localhost specifies that database is located on this machine only.

Following page has details of all the options that can be used with gfix.

http://www.destructor.de/firebird/gfix.htm

PresentationFontCache issue – IndexOutOfRangeException when running WPF application

March 20, 2011

A few days back, I came across this IndexOutOfRangeException with PresentationFontCache when running our WPF application on a Windows 7 machine. I tried disabling and enabling .NET framework from Add/Remove components but nothing seemed to fix this.

PresentationFontCache service optimizes performance of WPF applications by caching commonly used font data.

One of the following two fixes seem to work for different peoples.

  1. PresentationFontCache data is stored at [Windows]\ServiceProfiles\LocalService\AppData\Local\FontCache*.dat. Some of the guys have fixed this problem after deleting this file from here and restarting Windows Presentation Font Cache service. Disabling Windows Presentation Font Cache service worked for me. I don’t know why but just stopping the service did not work for me.

Refer to following thread for some more discussions -

http://social.msdn.microsoft.com/Forums/en/wpf/thread/2e47b80a-1423-466f-873a-8536a64ebe3c

Large file transfer in WCF in IIS 7 - There was no endpoint listening at xxx that could accept the message

March 10, 2011

I had hosted a WCF web service on IIS 7 that needed to transfer large files (~100 MB) to and from the service. I had all of **maxReceivedMessageSize, maxBufferSize, maxItemsInObjectGraph, maxRequestLength **configured to sufficiently large values, but still i was getting above mentioned exception when transferring greater than 30 MB files.

In IIS 7, there is one more setting called maxAllowedContentLength which is by default 30000000 byte (just over 28 MB). You need to tweak this value according to your need. Following snippet shows where it should be placed in the web.config file.


  
    
      
        
      
    
  

  This setting is not directly available from IIS manager, so if you need to change this using GUI tool you can download IIS 7.0 Admin Pack. You will find this setting from selecting your website and then going to Request Filtering –> Edit Feature Settings –> Maximum allowed content length (Bytes).

ThreadAbortException:Thread was being aborted in IIS 7

March 06, 2011

Recently i was developing a WCF web service in IIS 7 on Windows Server 2008 and started getting this exception quite weirdly. Weirdly in the sense that the exception was not consistently being reported at the same call stack.

My web service was using App_Data to store some application specific data which was also being added/modified/deleted during runtime.

After doing a lot of searching and study, the behavior of writing to the App_Data turned out to be the culprit. It is really hard to guess what may be wrong. In fact, I learnt that heavily modifying application subdirectory shuts down the appdomain.

Following are two references that explain this thing -

http://blogs.msdn.com/b/toddca/archive/2005/12/01/499144.aspx

http://forums.iis.net/t/1121400.aspx

It seems that it has nothing to do with IIS 7 though and can happen even with IIS 6.

What Firebird assemblies to ship with embedded Firebird .NET App?

January 30, 2011

For a .NET application that uses embedded Firebird, I would suggest to ship all of the following with you .NET app.

  1. All the *.dll in the embedded Firebird directory. Downloaded Firebird embedded zip file from Firebirdsql.org if you have not already downloaded. To be precise, following are the assemblies with respect to v2.5 of Firebird.
  2. **intl **and **udf **directory. Both of these directory should be there in Firebird embedded zip file you downloaded.

Note that all of these files/folders mentioned above should be at the exe location of your .NET application. Some of these assemblies might not be used at all in the application, but i found issues when i only shipped fbembedd.dll. Shipping all of the stuff mentioned above has been quite stable.

Adding custom display value to Enum fields

January 15, 2011

Most of the times, display value for our custom enums are different from actual field value. We usually want to have different display string than actual field of the enum.

Thanks to extension method, we can extend Enum to add functionality to it. You can now add methods to an enum which was previously not possible. Here i am going to show two approaches of extending Enums to support display value for Enum fields.

Following is the 1st approach.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SampleWinApplication
{
    public enum LoginStatus
    {
        LoggedIn,
        LoggedOut,
        Idle,
        Away
    }

    public static class LoginStatusExtensions
    {
        public static string GetDisplayName(this LoginStatus loginStatus)
        {
            switch (loginStatus)
            {
                case LoginStatus.Away:
                    return "Away";
                case LoginStatus.Idle:
                    return "Idle";
                case LoginStatus.LoggedIn:
                    return "Logged in";
                case LoginStatus.LoggedOut:
                    return "Logged out";
            }
            return loginStatus.ToString();
        }
    }

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            // this will "Logged out"
            MessageBox.Show(LoginStatus.LoggedOut.GetDisplayName());
        }
    }

    
}

Here we add an extension method GetDisplayName to enum LoginStatus. The method returns display string depending on the given value of LoginStatus. Note that here you have full control over what display value to have for the given LoginStatus. This also has the advantage that you have consistent display value for LoginStatus throughout you application. There is one problem with this approach that you have to add an extension method for every enum that you want to add custom display string to. Following approach is a more generic solution to this problem using Attributes and extension methods.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SampleWinApplication
{
    [Serializable]
    [AttributeUsage(AttributeTargets.Field, Inherited = false)]
    public class EnumDisplayInfoAttribute : Attribute
    {
        public string DisplayString { get; private set; }

        public EnumDisplayInfoAttribute(string displayString)
        {
            this.DisplayString = displayString;
        }
    }

    public enum LoginStatus
    {
        [EnumDisplayInfo("Logged in")]
        LoggedIn,

        [EnumDisplayInfo("Logged out")]
        LoggedOut,

        [EnumDisplayInfo("Idle")]
        Idle,

        [EnumDisplayInfo("Away")]
        Away
    }

    public static class EnumExtensions
    {
        public static string GetDisplayName(this Enum targetEnumValue)
        {
            object displayInfoAttribute = targetEnumValue.GetType().GetField(targetEnumValue.ToString()).GetCustomAttributes(typeof(EnumDisplayInfoAttribute), false).FirstOrDefault();
            if (displayInfoAttribute != null)
            {
                return (displayInfoAttribute as EnumDisplayInfoAttribute).DisplayString;
            }
            return targetEnumValue.ToString();
        }
    }

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            // this will "Logged out"
            MessageBox.Show(LoginStatus.LoggedOut.GetDisplayName());
        }
    }

    
}

Here we add extension method to the base Enum class and thus it is available to every Enum. We also define an Attribute EnumDisplayInfoAttribute that you need to apply to enum fields that you want to support display string for. Note that for any new enums that you add in your application, you just need to decorate its fields with EnumDisplayInfoAttribute and they will start supporting display string feature. Also, if there is no attribute applied to given enum field, we just return the ToString(). You can use either of the two approaches. I personally find 2nd approach more elegant and readable because the display string is defined just where the enum is.