Find Active Directory Domain Controller

In case of needing to find name / IP address of the AD domain controller in a network:

On Command Prompt:

C:\>set type=all

Change <DOMAIN_NAME> with actual domain name.

What is Repository Pattern?

The repository pattern is a data access pattern that abstracts away data access code. With the repository pattern, the application can interact with a data source without knowing specific details of the data source. The application communicates to a repository objects and the repository objects responsible for getting, inserting, updating or deleting data. The application doesn’t know anything about the data access, the repository is in charge of that.

Why would you use Repository pattern:

  • Testability: easier unit test your application, specifically data access layer.
  • Maintainability: since all the data access logic resides in its own object, it’s easier to maintain.
  • Refactor: easier to change data access later. For example, switch from a local DB to a cloud based DB.

Further read: Martin Fowler’s Repository Pattern

What is Singleton Pattern?

The singleton pattern ensures a class has only one instance and provide a global point of access to it.

Example of Singleton pattern in real-world application:

  • Logging. Logger object instance needs only exist once across the application life cycle. Especially true when the log is written to a locking-mechanism store, such as a Windows file.
  • Load Balancer. A load balancer type of situation must only exist as a singleton object to direct which resource is available to a invoker. 
  • IoC Container. Underneath any IoC container, there’s singleton instance object that controls what class implementation to pass given the contract.

Further read: GOF’s Pattern: Singleton

Differences Between WCF and Web API

There are good reasons to use ASP.Net Web API instead of WCF. But, what are the differences?

Support SOAP and REST. Support only REST.
Protocols supported: TCP, HTTP, HTTPS, Named Pipes, MSMQ. Only HTTP / HTTPS protocols are supported. It uses full-feature of HTTP (URIs, request / response headers, caching, content formate, etc)
Data formats supported: XML, JSON, ATOM. Data formats supported are typically JSON and XML. But can be extended with Web API’s MediaTypeFormatter.
Required extensive configurations. Very little configurations. Development is similar to coding in ASP.Net MVC.
Passing parameters to WCF operations need configurations and must be specified in UriTemplate. Parameters are bound automatically, similar to ASP.Net MVC Model Binding feature.
Web API’s URI is by convention (controller / action name).
HTTP verbs supported: GET, POST. Other verbs are supported with more IIS configurations. Support full HTTP verbs. GET, POST, PUT, DELETE, PATCH, HEAD, etc.
Can be hosted on IIS, Windows Service, or with in a web application. Can be hosted on IIS or with in a web application.
WCF is bigger framework, allowing full customization, such as SOAP, REST or WS-*. To support MVC features, it requires heavy customization and configuration. Supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection, unit testing.

More reading about Web Service, WCF, WCF REST, Web API.

Global.asax Events

Global.asax contains the following events:

  • Application_Init: Fired when an application initializes or is first called. It’s invoked for all HttpApplication object instances.
  • Application_Disposed: Fired just before an application is destroyed. This is the ideal location for cleaning up previously used resources.
  • Application_Error: Fired when an unhandled exception is encountered within the application.
  • Application_Start: Fired when the first instance of the HttpApplication class is created. It allows you to create objects that are accessible by all HttpApplication instances.
  • Application_End: Fired when the last instance of an HttpApplication class is destroyed. It’s fired only once during an application’s lifetime.
  • Application_BeginRequest: Fired when an application request is received. It’s the first event fired for a request, which is often a page request (URL) that a user enters.
  • Application_EndRequest: The last event fired for an application request.
  • Application_PreRequestHandlerExecute: Fired before the ASP.NET page framework begins executing an event handler like a page or Web service.
  • Application_PostRequestHandlerExecute: Fired when the ASP.NET page framework is finished executing an event handler.
  • Applcation_PreSendRequestHeaders: Fired before the ASP.NET page framework sends HTTP headers to a requesting client (browser).
  • Application_PreSendContent: Fired before the ASP.NET page framework sends content to a requesting client (browser).
  • Application_AcquireRequestState: Fired when the ASP.NET page framework gets the current state (Session state) related to the current request.
  • Application_ReleaseRequestState: Fired when the ASP.NET page framework completes execution of all event handlers. This results in all state modules to save their current state data.
  • Application_ResolveRequestCache: Fired when the ASP.NET page framework completes an authorization request. It allows caching modules to serve the request from the cache, thus bypassing handler execution.
  • Application_UpdateRequestCache: Fired when the ASP.NET page framework completes handler execution to allow caching modules to store responses to be used to handle subsequent requests.
  • Application_AuthenticateRequest: Fired when the security module has established the current user’s identity as valid. At this point, the user’s credentials have been validated.
  • Application_AuthorizeRequest: Fired when the security module has verified that a user can access resources.
  • Session_Start: Fired when a new user visits the application Web site.
  • Session_End: Fired when a user’s session times out, ends, or they leave the application Web site.

Following events are triggered one time.

  • Application_Init: Triggered when application is initialized, before it’s started.
  • Application_Start: Triggered when application is started.
  • Session_Start: Triggered when a user enters the site.
  • Session_End: Triggered when a user leaves the site.
  • Application_Disposed: Triggered when application is terminated, before it’s ended.
  • Application_End: Triggered when application is ended.

Events are triggered in the following order (per user’s request):

  • Application_BeginRequest
  • Application_AuthenticateRequest
  • Application_AuthorizeRequest
  • Application_ResolveRequestCache
  • Application_AcquireRequestState
  • Application_PreRequestHandlerExecute
  • Application_PreSendRequestHeaders
  • Application_PreSendRequestContent
  • <<code is executed>>
  • Application_PostRequestHandlerExecute
  • Application_ReleaseRequestState
  • Application_UpdateRequestCache
  • Application_EndRequest

Mode details can be read on Working with ASP.NET Global.asax.

October 1, 2013 Update :

There is also the following Global.asax events:

  • Application_PostAuthenticateRequest

Certificate Files: .Cer x .Pvk x .Pfx

So, what are the differences between .cer, .pvk and .pfx certificate files?

In Windows platform, these file types are used for certificate information. Normally used for SSL certificate and Public Key Infrastructure (X.509).


CER file is used to store X.509 certificate. Normally used for SSL certification to verify and identify web servers security. The file contains information about certificate owner and public and private certificate keys. A CER file can be in binary (ASN.1 DER) or encoded with Base-64 with header and footer included (PEM), Windows will recognize either of these layout.

This file can be generated using Certificate Creation Tool (makecert.exe) as shown in the link below.


Beside CER, there’s also SPC file, which is Software Publisher Certificate. It’s a different representation of certificate in PKCS #7 format.

You can generate a SPC file from a CER file.


Stands for Private Key. Windows uses PVK files to store private keys for code signing in various Microsoft products. PVK is proprietary format.

You can create a CER file based on a PVK file.


Or Personal Exchange Format, is a PKCS12 file. This contains a variety of cryptographic information, such as certificates, root authority certificates, certificate chains and private keys. It’s cryptographically protected with passwords to keep private keys private and preserve the integrity of the root certificates. The PFX file is also used in various Microsoft products, such as IIS.

PFX file can be created from a CER, SPC, or PVK file.

Source and further reading:
Software Publisher Certificate
Make Cert Command
IBM Certificate File Types

ASP.Net MVC Pipeline (Lifecycle)

ASP.Net MVC pipeline (or lifecycle, if you prefer) consists of the following:

  • Application Initialization
  • Routing
  • Instantiate and execute Controller
  • Locate and render View

Steven Sanderson also has complete diagram depicting the ASP.Net MVC Pipeline that can be downloaded on his site.

More details on each can be read on Steven Sanderson’s ASP.NET MVC Pipeline

Do Not Use Database Trigger

Or rather, use database trigger carefully.

Trigger is convenient and easy to write, but wrong implementation of database trigger can cause serious performance issue.

Basic rule is to avoid database trigger at all cost, find alternative way to achieve same result. Below is a video from Pluralsight showing usage of a database trigger that performs poorly. The slow performance caused by overhead that comes with database trigger, in this case the operation reads more table that necessary. When alternative approach is used (setting default constraint on a column), the difference is significant.

Try it for yourself.

-- Create our demo
CREATE TABLE [dbo].[charge_demo](
    [charge_no] [dbo].[numeric_id] NOT NULL PRIMARY KEY CLUSTERED,
    [charge_no] [dbo].[numeric_id] NOT NULL,
    [provider_no] [dbo].[numeric_id] NOT NULL,
    [category_no] [dbo].[numeric_id] NOT NULL,
    [charge_dt] [datetime] NOT NULL,
    [charge_amt] [money] NOT NULL,
    [statement_no] [dbo].[numeric_id] NOT NULL,
    [charge_code] [dbo].[status_code] NOT NULL,
    [insert_dt] [datetime] NULL;

-- Create our trigger
CREATE TRIGGER [trg_i_charge_demo]
    ON [dbo].[charge_demo]
    UPDATE [dbo].[charge_demo]
    SET [insert_dt] = GETDATE()
    FROM [dbo].[charge_demo] AS [c]
    INNERT JOIN inserted AS [i] ON
        [c].[charge_no] = [i].[charge_no];

Source: Hidden Side Effect of Trigger

HttpContext vs HttpContextBase vs HttpContextWrapper


Good ol’ HttpContext in ASP.Net. HttpContext has no base class and isn’t virtual, thus, is unusable for testing and unmockable. Strongly recommended to not pass it around as arguments. Instead, pass around variables of type HttpContextBase.


New to C# 3.5 and meant to replace HttpContext. HttpContextBase is abstract, thus, it is now mockable. Concretely implemented by HttpContextWrapper.


Also new in C# 3.5 – this is the concrete implementation of HttpContextBase. To instantiate in a normal webpage:

var webContext = new HttpContextWrapper(HttpContext.Current)

The whole idea is to make your code test-able by allowing your test framework to mock the HttpContext.

More detail explanation on here.

.Net 4.5 Claims and Tokens as Standard Model

Notes from Dominick Baier’s .Net 4.5 Claims and Tokens Become the Standard Model.

You can also download Guide to Claims-Based Identity and Access Control book from Microsoft Patterns & Practices.

ClaimsPrincipal & ClaimsIdentity Class

MSDN source for ClaimsPrincipal
MSDN source for ClaimsIdentity


ClaimsPrincipal Inheritance


ClaimsIdentity Inheritance


Identity Specialization


Processing Pipeline (Per Request)


ClaimsAuthorizationManager Class

MSDN source for ClaimsAuthorizationManager


Authorization Context (CheckAccess)

Using ClaimsPrincipalPermission to restrict access. MSDN source for ClaimsPrincipalPermission.