Wednesday, 30 December 2009

Options for Building Your Data Access Layer Using .NET

Thinking of building the data access layer of your next application?
What are your options?
What is most important to you; performance, scalability, security, flexibility, rapid development, etc?


  • Use this option if performance is your main contain. No other solution would have higher performance than this as all tools will use plain ADO.NET internally.
  • It's not rapid for development

ADO.NET Entity Framework




Microsoft Enterprise Library Data Access Block



Other references:

Wednesday, 23 December 2009

Download Files from Web Using Wget Tool

Wget is a tool which helps you download web pages.

Download One Page:


Monday, 14 December 2009

JavaScript - Naming Conventions and Coding Standards

Naming Conventions:

I am going to write naming conventions for JavaScript. This will be inspired by ASP.NET AJAX Library.

Target Convention Example

js file name

Pascal Casing



Pascal Casing



Pascal Casing



Camel Casing


Input Parameters

Camel Casing

parse(text); // text is in camel case

Private Class Variables

use _ with camel casing

var _firstName;

Public Class Variables

this.<Camel Casing>

this.isStrong = true; // this is used to define a member as public

Class Properties

// properties are public

get_<camel casing>


set_<camel casing> 

this.get_firstName: function(){
return _firstName;

this.set_firstName: function(value){
this._firstName = value;
Method Variables Camel Casing var index = 0;

Coding Standards:

Friday, 11 December 2009

All About WatiN

Get a RadioButton


Click a Button:


Click a LinkButton:

Type in a TextBox:

Wednesday, 9 December 2009

Approaches to Unit Testing JavaScript

1. Create your JavaScript functions

2. Create and Host Tests

Create an HTML file to host your tests using QUnit

3. Provide Test Runner

You need a test runner which can be integrated with CruiseControl.NET and Visual Studio.NET:

Tuesday, 8 December 2009

JavaScript – Create Singleton… No… Static Class

The following class is a normal javascript class:

function Calculator() {

// public functions
this.Add = add;
this.Subtract = subtract;

// private functions
function add(a, b)
{ return a + b; }

function subtract(a, b)
{ return a - b; }

// private variable
var name = "pooya";

// public variable
this.Name = name;


And this is how you use it:

var calculatorObject = new Calculator();
calculatorObject.Add(1, 2);

The following class is a static version of the same class:

var Calculator = (function() {

// private variable
var name = "pooya";

// private static functions
function add(a, b)
{ return a + b; }

// all the public members should be added to return (comma separated)
return {
// public function using delegate
Add: add
// public function embedding the implementation
Subtract: function(a, b)
{ return a - b; }
// public variable
Name: name

Now you can simply use the following:

Calculator.Add(1, 2);


I have seen many people saying this is how you create a Singleton class which is incorrect.

Please note that in the second Calculator class, no instance member can be defined which means "this" doesn't work, the following is invalid: "this.Name = name"

All members are considered static because of the way it has been defined.

The difference is that in Singleton class you can define instance members, however, in static class like this one you can’t.

You can argue that Singleton in C# is different from Singleton in JavaScript but in my view Singleton is Singleton no matter what language, so this is how you define a static class in JavaScript.

Monday, 7 December 2009

Networking - What is SAN?

What is SAN?
A storage area network (SAN) is a high-performance subnet (or shared storage bus) whose primary purpose is the transfer of data between computer systems and storage elements.

Benefits / Motivation?
  • Availability
  • Reliability
  • Scalability
  • Performance
  • Manageability

How to implement?


Friday, 4 December 2009

How to Use JSON in JavaScript and .NET?

It's very easy to use JSON, believe me!

JSON is a lightway format of sending messages from one place to another.

From JavaScript:

Use JavaScriptSerializer class to serialize into JSON and deserialize from JSON:

To use this you should add ScriptManager on your aspx page.

Examples: ...

From .NET 3.5 and above:

1) Use JavaScriptSerializer class:

This class is located in System.Web.Extensions.dll.

2) Use DataContractJsonSerializer class:

This class in located in System.ServiceModel.Web.dll.

DataContractJsonSerializer Example:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;

namespace CompanyName.ApplicationName.Model
public class CMMessage
public string ClientIndividual;

public string JobFunction;

public string LastTeamActivity;

public string ClientCompany;

public List CMPhoneList;

/// This method is responsible to json serialize this object
public string ToJson()
var serializer = new DataContractJsonSerializer(typeof (CMMessage));
using (var memoryStream = new MemoryStream())
serializer.WriteObject(memoryStream, this);
return Encoding.Default.GetString(memoryStream.ToArray());

/// This method is responsible to deserialize a json text to a CMMessage object
/// json text
public static CMMessage GetByJson(string json)
var serializer = new DataContractJsonSerializer(typeof(CMMessage));
using (var memoryStream = new MemoryStream(Encoding.Default.GetBytes(json)))
return serializer.ReadObject(memoryStream) as CMMessage;


From .NET 2.0:

I am afraid Microsoft didn't create any class for JSON Serialization in .NET 2.0, however, there are some workarounds for you:

1) Use

2) Create your own JSONSerializer for .NET 2.0 using .NET Reflector on either JavaScriptSerializer class or DataCotnractJsonSerializer class in .NET 3.5:

More resources:

Tuesday, 1 December 2009

JavaScript - ReplaceAll Function

JavaScript ReplaceAll Function:
String.prototype.ReplaceAll = function(stringToFind, stringToReplace) {

if (stringToFind == null stringToFind == '') return this;

var result = "";
var temp = this;

var index = temp.indexOf(stringToFind);

if (index == -1) return this;

do {
var targetLength = index + stringToReplace.length;
temp = temp.replace(stringToFind, stringToReplace);
result += temp.substring(0, targetLength);
temp = temp.substring(targetLength, temp.length);
index = temp.indexOf(stringToFind);
} while (index != -1);

// to add any remaining data
result += temp;

return result;


How to use it:

function Test() {

var data = "Hi, my name is Pooya Khamooshi; I am expert in everything (potentially)!";
var replaceMe = 'Pooya';
var replaceWith = "<b>" + replaceMe + "<\b>";

if (data.indexOf(str) == -1)
document.writeln("no match found");
document.write(data.ReplaceAll(replaceMe, replaceWith));

Use regular expression

This approach is easier and shorter but it requires that you know exactly what your regular expression is.

var str = "My name is Pooya Khamooshi and I have understood that there are many things I am not expert in";
var pattern = /\s/g;
str.replace(pattern, ''); // this removes all the spaces from the text above.

Monday, 30 November 2009

How to Enable Debugging on an Activex component?

I had an Activex component which was created using C# Class Library Project template. and the debugger couldn't debug it.

  1. Execute the page on IE.
  2. Once you have the page up and can see your ActiveX control, switch to Visual Studio and click on the 'Debug' menu item. Click on 'Attach to Process'.
  3. On the Attach to Process screen, click on 'Select...' next to the Attach to: label. Select Managed Code and click on 'OK'.
  4. In the Available Processes section, select 'iexplore.exe' and click on 'Attach'.
  5. You can now debug the code

Sunday, 29 November 2009

Network Monitoring Tools

A Network Monitoring tool is a tool which monitors all your network traffic messages.

Thursday, 26 November 2009

Xml Serialization and Deserialization using XSD

  1. Get an XSD file
  2. Generate the Classes from XSD using xsd.exe tool
Xml Serialization Process:
  1. Create a new instance of the object from the XSD e.g. login object
  2. Use XmlSerializer class to serialize the object and get the result back; you would just need some Factory methods
  3. Use the serialized data
Xml Deserialization Process:
  1. Get the xml as string
  2. Specify the type e.g. login
  3. Deserlialize the xml to the type specified using XmlSerializer class
  4. Use the deserialized object
       public void Should_Generate_Xsd_For_Class()
           const string Xsd = @"""C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\xsd.exe""";
           // /t:{2}  /outputdir:{3}
           var arguments = string.Format("{0} /t:{1}  /outputdir:{2}",
           Process.Start(Xsd, arguments);

Wednesday, 25 November 2009

WinForms - Use Mutex to Ensure Only One Instance

The following code enforces that only one instance of your WinForms application runs at every time:

/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
// this is true only if the namedMutex created newly in the context of the current application
bool namedMutexCreated = false;

using (Mutex mtex = new Mutex(true, "BeaconClientService", out namedMutexCreated))
if (namedMutexCreated)
Application.Run(new Form1());

// when the form is closed, the mutext is released
MessageBox.Show("An instance of Beacon Client Service is already running.", "Service Is Running", MessageBoxButtons.OK, MessageBoxIcon.Error);
catch (Exception ex)
MessageBox.Show("An error occured when running the Beacon Client Service, message: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);



Tuesday, 24 November 2009

How to Know When A Person Logs on to Windows?

Imagine you have a Windows Service application which runs automatically when Computer starts.

You want to find out when a Person Logs on and Logs off in Windows so that you take further action against it.

1. Winlogon Notification Packages

If your Client PCs are in Windows XP and Windows 2003, you can use this option. It doesn't work for Windows Vista and later.

2. Windows Management Instrument
Windows Management Instrumentation (WMI) is the infrastructure for management data and operations on Windows-based operating systems.

To be continued...

How to Fire and Forget a Method Asyncronously

Fire and forget the following method:

public void SendEmail(string message, string to)
// logic

Approach 1: using BackgroundWorker class

public class SendEmailArgument
public string Message { get; set; }

public string To { get; set; }

var argument = new SendEmailArgument() {Message = "My message", To = ""};

var bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);

static void bw_DoWork(object sender, DoWorkEventArgs e)
var argument = (SendEmailArgument) e.Argument;
SendEmail (argument.Message, argument.To);

Approach 2: Using ThreadPool class

Approach 3: Using Thread class

Tuesday, 17 November 2009

All About AOP (Aspect Oriented Programming)

AOP or Policy Injection is a complement to OOP (Object Oriented Programming) which addresses modularity problems such as Tracing, Exception Handling, Security, Transaction Management, Caching, Thread Management, Performance Counters, Parameter Checks, Event Subscriptions, etc.


AOP Open Source Frameworks:
Benefits of AOP:
  • It decouples the business logic from the system plumbing
  • It simplifies long-term maintenance
  • AOP
  • Aspect
  • Cross-cutting Concerns
  • Advice
  • Pointcut
  • Join Points
  • AOSD

Saturday, 14 November 2009

All About StyleCop

To download StyleCop click here.

If you use Resharper, you can configure it to use StyleCop rules; click here to download.

To know more about setting up StyleCop with MSBuild integration click here.

Run StyleCop Automatically After a Project Build:
  1. Add all StyleCop files into your solution

1.1. Create a new folder called “Lib” inside your solution directory

1.2. From %Program Files%\MSBuild\Microsoft\StyleCop Copy all files to your “Lib” directory:


Why would you do that:

The reason you should copy the files into your solution is that:

  • You may want to customize the default StyleCop violation rules for your specific solution using Settings.StyleCop file
  • Other developers who would like to benefit from StyleCop, won’t need to install StyleCop locally. They can get the latest version from source control such as MSS or TFS

2. Open your project file(e.g. myProject.csproj) and import StyleCop project into it

<Project DefaultTargets="Build" xmlns="">
<Import Project="$(SolutionDir)\Lib\StyleCop\v4.4\Microsoft.StyleCop.targets" />

If you don't want to copy the file in your solution, you can point to the default location which is:


Another way is to use this environmental variable: Project="$(MSBuildStyleCop)". This way, it will look at where your StyleCop has been installed in Windows.

Set Violations as Errors:

By default when StyleCop runs it gives you the violations as Warnings:

You can set the violations to appear as Errors:
  1. Open your project file in notepad e.g. myProject.csproj
  2. Add StyleCopTreatErrorsAsWarnings to the Debug PropertyGroup tag:

    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    Then you will get violations as errors:

Customize StyleCop Violation Rules For Your Solution:

  1. Locate Settings.StyleCop file and double click on it
  2. Check or uncheck a rule


Thursday, 12 November 2009

Application Scalability

When we have an application which would need to support a large number of users (such as Google Search) or would require to do intensive processes (such as NASA Space programs), we see that one Server is not able to handle the workload because of limitation in its resources; memory, CPU or disk-space.

Scalability Solutions:
Scalability solutions provide approaches to distribute the application workload so that your application can remain responsive in a timely manner in those situations.

1.1 Load Balancers:

1.1.1 LBC: Load Balancer Components

1.1.2 NLB: Network Load Balancers

1.2. Load Balancer Algorithms:

1.2.1 DNS Round-Robin Load Balancer
To balance server loads using DNS, the DNS server maintains several different IP addresses for a site name. The multiple IP addresses represent the machines in the cluster, all of which map to the same single logical site name.

If there are 3 machines in the cluster, when the first request arrives at the DNS server, it returns the IP address of the first machine. On the second request, it returns the second IP address. And so on. On the fourth request, the first IP address is returned again.

Using the above DNS round robin, all of the requests to the particular site have been evenly distributed among all of the machines in the cluster. Therefore, with the DNS round robin method of load balancing, all of the nodes in the cluster are exposed to the net.

Session state can be stored on the server (using cookie) or in database; cookies can expire so not very reliable.

No support for high availability.

Hardware Load Balancers:

The load balancer exposes the IP address of the entire cluster to the world.

Hardware load balancer redirects the user requests to a node in the cluster based on the information in the header, cookies or URL data.

Hardware load balancers provide request-level failover; when the load balancer detects that a particular node has gone down, it redirects all subsequent requests to that dead node to another active node in the cluster. However, any session information on the dead node will be lost when requests are redirected to a new node.

Dispatcher-Based Load Balancers:

2. MCSC: Microsoft Cluster Server

Load Balancing:

There are 2 types of load balancing solutions:
  1. Software-based such as Windows Network Load Balanacing
  2. Hard-based
Software-based Load Balancer:
  • Can be configured for Sticky IP - for TCP
  • Can be configured for Sticky Sessions - for HTTP

HTTP load balancing techniques:

Key Terms:
  • Cluster
  • Cluster IP Address
  • Cluster Node
  • Cluster Node IP Address
  • Load Balanced Farm
  • DNS Round-Robin Load Balancing
  • DNS Lookup
  • Load Balancing Cluster
  • Hardware Load Balancer
  • Network Load Balancing (NLB)
  • Web Server Farm
to be continued...

Wednesday, 11 November 2009

Create an Intelligent Thread-Safe Queued BackgroundWorker


If you run the RunWorkerAsync method of normal BackgroundWorker class when a previous RunWorkerAsync has not yet been completed, then you will get an exception. What this means is that before calling the RunWorkerAsync again, you must be sure that the Completed event of the previous call has been reached.


Features of my QueuedBackgroundWorker:

  • Run different methods asynchronously and get the result back if you would want to.
  • All the works will be queued and will run one by one.
  • You can have complex input or output arguments.
  • It’s thread-safe


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;

/// <summary>
/// This is thread-safe
/// </summary>
public class QueuedBackgroundWorker
#region Constructors

public QueuedBackgroundWorker() { }


#region Properties

Queue<object> Queue = new Queue<object>();

object lockingObject1 = new object();

public delegate void WorkerCompletedDelegate<K>(K result, Exception error);


#region Methods

/// <summary>
/// doWork is a method with one argument
/// </summary>
/// <typeparam name="T">is the type of the input parameter</typeparam>
/// <typeparam name="K">is the type of the output result</typeparam>
/// <param name="inputArgument"></param>
/// <param name="doWork"></param>
/// <param name="workerCompleted"></param>
public void RunAsync<T,K>(Func<T, K> doWork, T inputArgument, WorkerCompletedDelegate<K> workerCompleted)
BackgroundWorker bw = GetBackgroundWorker<T,K>(doWork, workerCompleted);

Queue.Enqueue(new QueueItem(bw, inputArgument));

lock (lockingObject1)
if (Queue.Count == 1)

/// <summary>
/// Use this method if you don't need to handle when the worker is completed
/// </summary>
/// <param name="doWork"></param>
/// <param name="inputArgument"></param>
public void RunAsync<T,K>(Func<T, K> doWork, T inputArgument)
RunAsync(doWork, inputArgument, null);

private BackgroundWorker GetBackgroundWorker<T, K>(Func<T, K> doWork, WorkerCompletedDelegate<K> workerCompleted)
BackgroundWorker bw = new BackgroundWorker();
bw.WorkerReportsProgress = false;
bw.WorkerSupportsCancellation = false;

bw.DoWork += (sender, args) =>
if (doWork != null)
args.Result = (K)doWork((T)args.Argument);

bw.RunWorkerCompleted += (sender, args) =>
if (workerCompleted != null)
workerCompleted((K)args.Result, args.Error);
lock (lockingObject1)
if (Queue.Count > 0)
return bw;


public class QueueItem
#region Constructors

public QueueItem(BackgroundWorker backgroundWorker, object argument)
this.BackgroundWorker = backgroundWorker;
this.Argument = argument;


#region Properties

public object Argument { get; private set; }

public BackgroundWorker BackgroundWorker { get; private set; }


#region Methods

public void RunWorkerAsync()


1) How to use it:

public partial class _Default : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
var worker = new QueuedBackgroundWorker();

worker.RunAsync<int, int>(Calculate, 2);

worker.RunAsync<MultiplyArgument, int>(Multiply, new MultiplyArgument() { A = 1, B = 2 }, MultiplyCompleted);

private int Calculate(int a)
return a*2;

private int Multiply(MultiplyArgument calculateArgument)
return calculateArgument.A * calculateArgument.B;

private void MultiplyCompleted(int result, Exception error)
Response.Write("worker completed, result: " + result.ToString());


public class MultiplyArgument
public int A { get; set; }

public int B { get; set; }


Saturday, 7 November 2009

Export To PDF

PDF Convertors and Mergers:
You can convert different type of files such as .doc into PDF.

Export Page to PDF using evopdf.

IT Organizational Skills

  • Taking good notes from meetings, conference calls, etc
  • Setting goals and deadlines
  • Having projects done on time.
  • Communicate regularly about the progress and strategy improvements
  • Reporting to your manager weekly about the progress
  • Knowing where everything in the office is located.
  • Making good use of time.
  • Keeping work area stocked and neat.
  • Documenting results
  • If you have responsibility of other people as well, you should be maintaining their tasks list and chase them up to do their tasks
  • Be aware constantly about what you are saying, to whom and what impact it could have; for instance if you say to your non-technical manager that the Server is down and I am working on it, he might be frightened though you know that it's a 1 minute job to make it work!!!
Project Planning
If you're responsible to write a project plan and task list of your team, you can use the following tools:
  1. Microsoft Project
  2. Microsoft Excel
  3. Microsoft Word
Then this should be maintained throughout the project and should be reported to your Manager e.g. weekly.

Personal Daily Agenda
Have a personal daily agenda for yourself which includes your own works; check the items as you finish them.

You can simply use NotePad for this.

How your managers are perceiving you?
Are they constantly aware about your progress and hard work?
Do they FEEL confident in you and about your ability to do your job?
Do they FEEL that you have your tasks under control and they are progressing?
What messages are you sending with your words?

Thursday, 5 November 2009

C# 4.0 New Features

C# 4.0 Major new features - 4 major groups:
  1. Dynamic lookup
  2. Named and optional parameters
  3. COM specific interop features
  4. Variance
1. Dynamic lookup
It's a new feature which allows you to write the following at runtime: method, operator, property and object invocations.
  • The validation of operations of a dynamic object is made at runtime not compile time. So if you have written an incorrect expression, you will only get the error message at runtime.
  • DLR (Dynamic Language Runtime) is a new component which runs on top of CLR (Common Language Runtime) and provides dynamic services to C# 4.0.
Create a dynamic object:

dynamic d = GetDynamicObject();
d.M(4); // call a method
d.P = 2; // setting a property
d[1] = 3 // setting through indexers
int i = d + 3; // calling operators
string s = d(5,7); // invoking as a delegate
d = new Employee(); // assigning a static type to a dynamic type
var testInstance = new ExampleClass(d); // testInstance is a static type of ExampleClass not a dynamic type

M will be examined at runtime not compiletime. if d doesn't have a method called M, compiler ignores the error and it indeed at runtime an exception will occur.

What is a dynamic type anyway?
dynamic is a static type an instance of which bypasses the compile-time type checking. In other words, type checking will be defered to runtime.

So, you can use "is" and "as" with a dynamic type:

int i = 8;
dynamic d;
// With the is operator.
// The dynamic type behaves like object. The following
// expression returns true unless someVar has the value null.
if (someVar is dynamic) { }

// With the as operator.
d = i as dynamic;


dynamic d = 7; // implicit conversion

int i = d; // assignment conversion

In C# 3.0:

((Excel.Range)excel.Cells[1, 1]).Value2 = "Name";

whereas in C# 4.0:

excel.Cells[1, 1].Value = "Name";

run-time COM binder in DLR will handle the conversion.

In C# 3.0 this raises an exception at compile time:

object obj = 1;
obj = obj + 3;

Whereas in C# 4.0, this raises an exception neither in compile-time nor in run-time:

dynamic dyn = 1;
dyn = dyn + 3;

Passing a dynamic object to a static method:

Foo foo = new Foo();
dynamic d = new Bar();
var result = foo.M(d);

foo is a static object whereas d is a dynamic object. result would be a dynamic object itself because d which is a dynamic object has been passed to M method of foo.


... to be updated

Thursday, 29 October 2009

All About Batch Files

I can't explain how much I love batch files. You can write your commands in a .bat file, then you can run them. It's great for automation which saves a lot of time.

Ok, what can you do with it?

Start Applications

SET fromFolder=C:\Projects\Beacon\v1.0\code

START %fromFolder%\BrokerService\bin\Debug\BeaconServer.BrokerService.exe

START http://localhost/BeaconClientService.WebUI/Default.aspx

Copy Files

SET fromFolder=C:\Projects\Beacon\v1.0\code

SET toFolder=D:\Projects\Beacon\v1.0\code

xcopy /E /Y %fromFolder% %toFolder%

Build Solutions

SET msBuildFolder= C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

CD %msBuildFolder%

SET rootFolder=C:\SharedFolder\Beacon\v1.0\code\

MSBUILD %rootFolder%BeaconClient\src\BeaconClient.sln

MSBUILD %rootFolder%BeaconServer\src\BeaconServer.sln


Start IE with a Specific Url

SET iexplore=C:\"Program Files"\"Internet Explorer"\IEXPLORE.EXE

SET url=

START %iexplore% %url%

Kill All IE Instances

taskkill /f /im iexplore.exe

Open Chrome in a New Window

start "Chrome" chrome --new-window

Start Chrome with 2 Specific Urls

SET appPath=C:\Users\[Username]\AppData\Local\Google\Chrome\Application\chrome.exe

START %appPath%

Empty a File
To empty any file, such as .log, .txt, .cs, you can use the following command:

set filePath1=FolderName\filename.log
type NUL > %filePath1%

Reset IIS

Kill Current Web Server Processes

Taskkill /IM WebDev.WebServer40.EXE /F

Kill Chrome

Taskkill /IM WebDev.WebServer40.EXE /F

Build and Publish a Solution

msbuild C:\\AppFolder\AppProject.csproj /p:DeployOnBuild=true /p:PublishProfile=C:\\AppFolder\Properties\PublishProfiles\localhost.pubxml /p:VisualStudioVersion=12.0

Delete a File

DEL c:\folder\filename.sql

SVN Get Latest

CD C:\Program Files\TortoiseSVN\bin\

START TortoiseProc.exe /command:update /path:"C:\Svn\mediacenter\" /closeonend:1