Monday 30 November 2009

How to Enable Debugging on an Activex component?

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

Solution:
  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

Preparation:
  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
Examples:
 [TestMethod]
       [Ignore]
       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}",
               @"""C:\Tfs\Project\Trunk\Project\bin\Debug\ProjectName.dll""",
               "Namespace.ClassName",
               @"C:\Test");
          
           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>
[STAThread]
static void Main()
{
try
{
// 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.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());

// when the form is closed, the mutext is released
mtex.ReleaseMutex();
}
else
{
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);
}

}

More:

Tuesday 24 November 2009

How to Know When A Person Logs on to Windows?

Problem:
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.

Solutions:
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

Problem:
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 = "name@domain.com"};

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

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.

Learning:

AOP Open Source Frameworks:
Benefits of AOP:
  • It decouples the business logic from the system plumbing
  • It simplifies long-term maintenance
Terminalogy:
  • 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:

image

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="http://schemas.microsoft.com/developer/msbuild/2003">
...
<Import Project="$(SolutionDir)\Lib\StyleCop\v4.4\Microsoft.StyleCop.targets" />
...
</Project>

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

$(MSBuildExtensionsPath32)\Microsoft\StyleCop\v4.4\Microsoft.StyleCop.targets

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:
image

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:

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

Customize StyleCop Violation Rules For Your Solution:

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

image

Thursday 12 November 2009

Application Scalability


Problem:
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

Problem:

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.

Solution:

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

QueuedBackgroundWorker:

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() { }

#endregion

#region Properties

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

object lockingObject1 = new object();

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

#endregion

#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)
{
((QueueItem)this.Queue.Peek()).RunWorkerAsync();
}
}
}

/// <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);
}
Queue.Dequeue();
lock (lockingObject1)
{
if (Queue.Count > 0)
{
((QueueItem)this.Queue.Peek()).RunWorkerAsync();
}
}
};
return bw;
}

#endregion
}

public class QueueItem
{
#region Constructors

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

#endregion

#region Properties

public object Argument { get; private set; }

public BackgroundWorker BackgroundWorker { get; private set; }

#endregion

#region Methods

public void RunWorkerAsync()
{
this.BackgroundWorker.RunWorkerAsync(this.Argument);
}

#endregion
}

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.

Perception:
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;

Conversion:

1)
dynamic d = 7; // implicit conversion

2)
int i = d; // assignment conversion

3)
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.

4)
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.

More:

... to be updated