Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand

Archive for November, 2011

Windows Azure – BlockBlob PutBlock Method

Posted by JP on November 30, 2011

In this article we are discussing about uploading blob using PutBlock method. I would like to give a note that there are two types of blob in Windows Azure:

· Block Blob

· Page Blob

The Block Blob uploading is discussed here as Block Blobs are used for large file uploads. The associated code was developed to upload large files to Windows Azure Blob. The large file will be splitted into 4 MB chunks and then uploaded.

Method

Following are the important methods used:

· CloudBlockBlob.PutBlock()

· CloudBlockBlob.PutBlockList()

The PutBlock method is called for each 4MB file chunk and PutBlockList method is called at the end passing the file chunk ids.

Code

Following is the code of AzureBlobUtil.cs

public class AzureBlobUtil

{

private const int MaxBlockSize = 4000000; // Approx. 4MB chunk size

public Uri UploadBlob(string filePath, CloudStorageAccount account, string containerName)

{

byte[] fileContent = File.ReadAllBytes(filePath);

string blobName = Path.GetFileName(filePath);

return UploadBlob(fileContent, account, containerName, blobName);

}

public Uri UploadBlob(byte[] fileContent, CloudStorageAccount account, string containerName, string blobName)

{

CloudBlobClient blobclient = account.CreateCloudBlobClient();

CloudBlobContainer container = blobclient.GetContainerReference(containerName);

container.CreateIfNotExist();

CloudBlockBlob blob = container.GetBlockBlobReference(blobName);

HashSet<string> blocklist = new HashSet<string>();

foreach (FileBlock block in GetFileBlocks(fileContent))

{

blob.PutBlock(

block.Id,

new MemoryStream(block.Content, true),

null

);

blocklist.Add(block.Id);

}

blob.PutBlockList(blocklist);

return blob.Uri;

}

private IEnumerable<FileBlock> GetFileBlocks(byte[] fileContent)

{

HashSet<FileBlock> hashSet = new HashSet<FileBlock>();

if (fileContent.Length == 0)

return new HashSet<FileBlock>();

int blockId = 0;

int ix = 0;

int currentBlockSize = MaxBlockSize;

while (currentBlockSize == MaxBlockSize)

{

if ((ix + currentBlockSize) > fileContent.Length)

currentBlockSize = fileContent.Length - ix;

byte[] chunk = new byte[currentBlockSize];

Array.Copy(fileContent, ix, chunk, 0, currentBlockSize);

hashSet.Add(

new FileBlock()

{

Content = chunk,

Id = Convert.ToBase64String(System.BitConverter.GetBytes(blockId))

});

ix += currentBlockSize;

blockId++;

}

return hashSet;

}

public Stream DownloadBlobAsStream(CloudStorageAccount account, string blobUri)

{

Stream stream = new MemoryStream();

CloudBlobClient blobclient = account.CreateCloudBlobClient();

CloudBlockBlob blob = blobclient.GetBlockBlobReference(blobUri);

if (blob != null)

blob.DownloadToStream(stream);

return stream;

}

public string DownloadBlobAsFile(CloudStorageAccount account, string blobUri)

{

Stream stream = DownloadBlobAsStream(account, blobUri);

string fileName = "Blob.file"; // Please change file name based on your need

if (stream != null)

{

FileStream fileStream = File.Create(fileName);

stream.Position = 0;

stream.CopyTo(fileStream);

fileStream.Close();

return fileName;

}

return string.Empty;

}

}

internal class FileBlock

{

public string Id

{

get;

set;

}

public byte[] Content

{

get;

set;

}

}

Testing Code

For uploading blob into the container use the following code:

// Upload

Uri blobUri = _blobUtil.UploadBlob(

filePathHere,

CloudStorageAccount.DevelopmentStorageAccount,

"files");

// Download

Stream stream = _blobUtil.DownloadBlobAsStream(

CloudStorageAccount.DevelopmentStorageAccount,

blobUri.ToString()

);


Associated Example

On running the example, after opening and uploading an image file, you can see the following result. The first box shows the source image. The second box shows the uploaded image from Azure.

clip_image002

Pre-Requisites

Please ensure the Storage Emulator is running while testing the example

Reference

You can find more information on Block and Page blob using following link:

http://msdn.microsoft.com/en-us/library/windowsazure/ee691964.aspx

Summary

In this article we have seen the usage of Block Blob upload as chunks. The source code can be used to upload large files to Azure Blob. The associated example can be downloaded along with this article. The utility method was verified with 100MB file upload and download.

Advertisements

Posted in Azure | Tagged: , , , , , , , , , | 2 Comments »

Windows Azure – WCF in Worker Role

Posted by JP on November 29, 2011

In this article I am going to demonstrate the creation of WCF service in Worker Role and deployment to the cloud.

The attributes of WCF service on Worker role are:

  • Self Hosted
  • More Flexibility Attained
  • More Configurations Needed

Following are the steps involved.

Step 1: Create the WCF Service

Create a new Windows Azure project in Visual Studio 2010 and name it as WCFInWorkerRole as shown below

clip_image002

In the appearing dialog add one Worker Role project as shown below.

clip_image004

Add reference to the System.ServiceModel assembly.

clip_image006

Add the following 2 files

  • Interface named IMessengerService
  • Class named MessengerService

Replace the contents of above files with the following:

// IMessengerContract.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace WorkerRole1

{

[ServiceContract]

public interface IMessengerService

{

[OperationContract]

string SendMessage(string name);

}

}

// MessengerService.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace WorkerRole1

{

public class MessengerService : IMessengerService

{

public string SendMessage(string name)

{

return “Hello ” + name + “. How do you do?”;

}

}

}

Remove the app.config from the worker role project as we are going to do manual configuration of WCF service. Now the solution explorer looks like below:

clip_image008

In the case of web role, the context and port was automatically identified. But in the worker role, we need to update the properties manually. The host name will be different in the development and deployment servers.

Modify the ServiceDefinition.csdef file as below.

<?xml version=”1.0″ encoding=”utf-8″?>

<ServiceDefinition name=”WCFInWorkerRole” xmlns=”http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition”&gt;

<WorkerRole name=”WorkerRole1″ vmsize=”Small”>

<Imports>

<Import moduleName=”Diagnostics” />

</Imports>

<Endpoints>

<InputEndpoint name=”port” protocol=”tcp” port=”9001″ />

<InputEndpoint name=”mexport” protocol=”tcp” port=”8001″ />

</Endpoints>

</WorkerRole>

</ServiceDefinition>

The content defines the port and metadata port for our WCF service. Now we can modify the OnStart() method of the Worker role class as given below.

public override bool OnStart()

{

// Set the maximum number of concurrent connections

ServicePointManager.DefaultConnectionLimit = 12;

// Create the host

ServiceHost host = new ServiceHost(typeof(MessengerService));

// Read config parameters

string hostName = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints[“port”].IPEndpoint.Address.ToString();

int port = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints[“port”].IPEndpoint.Port;

int mexport = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints[“mexport”].IPEndpoint.Port;

// Create Metadata

ServiceMetadataBehavior metadatabehavior = new ServiceMetadataBehavior();

host.Description.Behaviors.Add(metadatabehavior);

Binding mexBinding = MetadataExchangeBindings.CreateMexTcpBinding();

string mexendpointurl = string.Format(“net.tcp://{0}:{1}/MessengerServiceMetadata”, hostName, 8001);

host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, mexendpointurl, new Uri(mexendpointurl));

// Create end point

string endpointurl = string.Format(“net.tcp://{0}:{1}/MessengerService”, hostName, 9001);

host.AddServiceEndpoint(typeof(IMessengerService), new NetTcpBinding(SecurityMode.None), endpointurl, new Uri(endpointurl));

// Open the host

host.Open();

// Trace output

Trace.WriteLine(“WCF Listening At: ” + endpointurl);

Trace.WriteLine(“WCF MetaData Listening At: ” + mexendpointurl);

return base.OnStart();

}

The code performs the following:

  • Create Service Host
  • Read the Port number
  • Add the Metadata behaviour
  • Add the endpoints
  • Opens the Host

Note: The attached source code contains the working application.

Step 2: Test the application

Now we can test the application by executing it. If successfully executed we can see the trace from the Output window.

clip_image010

You can see two addresses from the above screen:

  • The actual service end point
  • The metadata end point

We can also see the trace from the load development machine. The Windows Azure Compute Emulator can be used for this purpose.

clip_image012

On invoking the Show Computer Emulator UI we can see the following window.

clip_image014

The above window contains the same trace output with the end point urls. You may try adding reference to the metadata end point using the metadata url. We are going to deploy the service to cloud and test it.

Step 3: Deploy to the cloud

Now our application is working fine and we can deploy it to the online cloud. For this right click on the project and click Package menu item.

clip_image016

In the appearing dialog box, choose the default options and click the Package button.

clip_image018

Now sign in to the Windows Azure portal and click on the New Hosted Service button from the top ribbon.

clip_image020

In the appearing dialog box enter the details as shown below.

clip_image022

Choose the option “Deploy to production environment”

Locate the package and configuration files from your application bin folder.

(Eg: ..\WCFInWorkerRole\bin\Debug\app.publish)

Please note that the URL prefix should be a unique name. If the URL prefix entered is already in use you need to change it.

After that click the Ok button of the dialog box. (You have to scroll down to see the button)

If any warning box appears, click Yes button to continue. Wait for a few minutes and your deployment will be ready in a few minutes as shown below.

clip_image024

Select the Deployment 2 row and from the properties window you can get the url of the worker role. Now we just need the host name. In this case wcfinworkerrole.cloudap.net

clip_image026

Step 3: Create the Client

Now we are ready to create the client application and test the deployed online cloud WCF service.

Create a new console application into the existing Azure project and name it as TestClient.

Use the add service reference option of the console application and in the appearing dialog enter the constructed service url as shown below.

Constructed Url: net.tcp://wcfinworkerrole.cloudapp.net:8001/MessengerServiceMetadata

Please note that we added the following:

  • Protocol as net.tcp
  • Host Name from previous step
  • Port number as 8001
  • Metadata Context Name

clip_image028

Click the Go button and after seeing the MessengerService item populated, Click the Ok button to continue.

Modify the main method in the Program.cs as following:

static void Main(string[] args)

{

ServiceReference1.MessengerServiceClient client = new ServiceReference1.MessengerServiceClient();

string result = client.SendMessage(“Kent”);

Console.WriteLine(string.Format(“Invoking WCF Service Result: {0}”, result));

Console.ReadKey(false);

}

Modify the configuration file with the url of the Messenger Service. Please note that the messenger service url is having different port number and context.

<client>

<endpoint

address=”net.tcp://wcfinworkerrole.cloudapp.net:9001/MessengerService

binding=”netTcpBinding”

bindingConfiguration=”NetTcpBinding_IMessengerService”

contract=”ServiceReference1.IMessengerService”

name=”NetTcpBinding_IMessengerService” />

</client>

Now set the console application as the start project and execute the application.

You can see the following results.

clip_image030

You can see the result Hello Kent. How do you do? from the WCF service.

This concludes our article on WCF service deployment as worker role and the testing.

Multiple End Point

I would like to add a note on the 2 end points we created for the WCF service.

net.tcp://wcfinworkerrole.cloudapp.net:8001/MessengerServiceMetaData

net.tcp://wcfinworkerrole.cloudapp.net:9001/MessengerService

You can see that there are 2 differences in the above urls:

  • Port
  • Context

Note: WCF with HTTP Port 80 endpoint configuration done as explained here.

Summary

In this article, we have seen how to host a WCF service using the Worker Role and deploy it to the cloud. This service is self hosted and experiments the service creation, hosting, metadata end point adding, deploying and testing with the client. The source code is attached and the application name in the url has to be changed according to your application name.

Posted in Azure | Tagged: , , , | Leave a Comment »

Windows Azure – WCF in Web Role

Posted by JP on November 29, 2011

In this article I would like to demonstrate the creation and deployment of WCF service in a Web Role.

The attributes of WCF service on Web role are:

  • IIS Hosted
  • IIS features like pooling and caching availability
  • Less Configurations Needed

Following are the steps involved.

Step 1: Create the WCF Service

Create a new Windows Azure project in Visual Studio 2010 and name it as WCFInWebRole as shown below

clip_image002

In the appearing dialog add one Web Role project as shown below.

clip_image004

Add a new WCF Service into the project. Name it as MessengerService.

clip_image006

Now the Solution Explore will look like below with the newly added contracts and service files.

clip_image008

Modify the DoWork() method in the interface IMessengerService as given below.

string SendMessage(string name);

Modify the DoWork() method in the interface IMessengerService as given below.

public string SendMessage(string name)

{

return “Hello ” + name;

}

Step 2: Test the application

Make the MessengerService.svc file as the start page as shown below.

clip_image010

Press F5 to execute the application and you can see the service opened in the browser as shown below.

clip_image012

Now are have tested the application and it is ready to be deployed to the cloud.

Step 3: Deploy to the cloud

Right click on the Web Role project and click package menu item as shown below.

clip_image014

In the appearing dialog select the default option and click the Package button.

clip_image016

Now sign in to the Windows Azure portal and click on the New Hosted Service button from the top ribbon.

clip_image018

In the appearing dialog box enter the details as shown below.

clip_image020

Choose the option “Deploy to production environment”

Locate the package and configuration files from your application bin folder.

(Eg: ..\WCFInWebRole\bin\Debug\app.publish)

Please note that the URL prefix should be a unique name. If the URL prefix entered is already in use you need to change it.

After that click the Ok button of the dialog box. (You have to scroll down to see the button)

If any warning box appears, click Yes button to continue. Wait for a few minutes and your deployment will be ready in a few minutes as shown below.

clip_image022

Select the Deployment 1 row and from the properties window you can get the url of the web role.

clip_image024

Click on the url and your application will get opened in the browser. Add the suffix MessengerService.svc to get the messenger service.

clip_image026

Step 3: Create the Client

Now we are ready to create the client application and test the deployed online cloud WCF service.

Create a new console application into the existing Azure project and name it as TestClient.

Use the add service reference option of the console application and in the appearing dialog enter the service url as shown below.

clip_image028

Click Ok button to continue.

Modify the main method in the Program.cs as following:

static void Main(string[] args)

{

ServiceReference1.MessengerServiceClient client = new ServiceReference1.MessengerServiceClient();

string result = client.SendMessage(“Ian”);

Console.WriteLine(string.Format(“Invoking WCF Service Result: {0}”, result));

Console.ReadKey(false);

}

Now set the console application as the start project and execute the application.

You can see the following results.

clip_image030

You can see the result Hello Ian from the WCF service.

This concludes our article on WCF service deployment as web role and the testing.

Summary

In this article we have seen how to deploy a WCF service to cloud platform. The WCF service inside the Web role will be hosted in IIS. The source code is attached and the application name in the url has to be changed according to your application name.

Posted in C# | Tagged: , , , | Leave a Comment »

Windows Azure – WCF Hosting Methods

Posted by JP on November 29, 2011

In the previous article we have experimented the ways of WCF hosting in Windows Azure. In this article I would like to summarize the important points of WCF service exposing in Windows Azure.

There are multiple ways of hosting WCF service in Windows Azure.

WCF Hosting

Description

Web Role

Hosted inside IIS with pooling and caching facilities

Worker Role

Self Hosted with more control

AppFabric

Self Hosting, Relayed connectivity through Service Bus

Let us examine them closely.

clip_image002

Method 1: Web Role Hosting

In the Web Role hosting, the WCF service is hosted inside IIS. This will give the advantages of IIS to the WCF service.

  • Identity Management
  • Recycling
  • Caching
  • Pooling
  • Logging


The Service creation will be much easier in this method as Visual Studio provides the templates for Service (.svc files). We need to create a new .svc file and place it in the web role project. The host names and ports are configured by the deployment and we can access the service through a browser.

The metadata end points are also automatically added. This saves a lot of amount of work from the developer side.

Method 2: Worker Role Hosting

Here the developer has to perform more work in creating the service contracts by defining the attributes in the contracts and implementation.

This method is advised if more control is needed over the service. We can easily configure the protocols in this way. In this case a corporate port has to be opened to expose the service while using the worker role.

Method 3: Hosting through AppFabric

In this method the WCF service is exposed through the Service Bus service feature of Windows Azure AppFabric. We can choose this option if we need to connect two disconnected applications.

This method is self hosted and more configurations needed. Here we can connect two disconnected applications using the Service Bus namespace. The namespace identifies the subscription and will be used for billing purposes on the cloud.

The Service Bus provides the following features:

  • Connectivity between disconnected applications
  • Higher Availability

Relay Service

There are two modes of connectivity in the Relay Service.

· TcpRelayConnectionMode.Relayed

· TcpRelayConnectionMode.Hybrid

The default mode is Relayed and here the service and client is connected through the relayed service.

Relayed Mode Connectivity

The following picture depicts the process in the Relayed mode.

clip_image004
The steps involved are following:

Step 1: The WCF Service authenticates and registers with the Relayed Service using the namespace and Provider keys.

Step 2: The Client authenticates with the Relay Service

Step 3: Client invokes a method using the Relay Service

Step 4: The Relay Service redirects the call to the registered WCF service.

Hybrid Mode Connectivity

In the Hybrid way of connectivity the client can communicate directly to the service. First the client connectivity starts as Relayed as usual and then if there is possibility of connecting directly to the service it will be provided.

Summary

In this article we have discussed the various WCF exposing methods in Windows Azure like web role, worker role and through AppFabric Service Bus.

Posted in Azure | Tagged: , , , | Leave a Comment »

Low Level Design Document

Posted by JP on November 29, 2011

Often in my consulting experience developers are needed of Low Level Design Document.  This is a simple document created for that purpose.

You can download the file here.

Typically two documents are involved in the design phase:

    • High Level Design
    • Low Level Design (Detailed Design)

image

You are free to download and change it.  Please let me know your feedback to improve the same.

Posted in C# | Tagged: | Leave a Comment »

Chain of Responsibility Pattern

Posted by JP on November 27, 2011

Chain of Responsibility is one among the 23 Design Patterns by Gang of Four. It is an interesting pattern and similar to Observer pattern. In this article we are exploring the Chain of Responsibility pattern.

I am using the same Challenge and Solution style for explaining this pattern.

Challenge

You are working on an application in which the Logic class generates various messages. The messages are of two types.

  • Normal Priority
  • High Priority

The Normal Priority messages are to be processed by Logger class and High Priority messages by Emailer class.

You have to make the design in such a way that the Logic class need not think about right handler of the message. It will just send the message.

How the design will proceed?

Definition

“Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.”

Control Flow

clip_image002

Implementation

Following is the definition for Logic class:

public class Logic

{

public IReceiver Receiver;

public void CreateMessage(Message message)

{

if (Receiver != null)

Receiver.HandleMessage(message);

}

}

We can see from the above code that the Logic class has a property of type IReceiver. On the CreateMessage method this Receiver is used to handle the message. So only one receiver is registered by the Logic class instance.

Following are the definition of Message class and MessagePriority enumeration:

public class Message

{

public string Text;

public MessagePriority Priority;

}

public enum MessagePriority

{

Normal,

High

}

Following are the Receiver Interface and Implementation classes:

public interface IReceiver

{

bool HandleMessage(Message message);

}

public class Logger : IReceiver

{

private IReceiver _nextReceiver;

public Logger(IReceiver nextReceiver)

{

_nextReceiver = nextReceiver;

}

public bool HandleMessage(Message message)

{

if (message.Priority == MessagePriority.Normal)

{

Trace.WriteLine(message.Text + ” : Logger processed it!”);

return true;

}

else

{

if (_nextReceiver != null)

_nextReceiver.HandleMessage(message);

}

return false;

}

}

public class Emailer : IReceiver

{

private IReceiver _nextReceiver;

public Emailer(IReceiver nextReceiver)

{

_nextReceiver = nextReceiver;

}

public bool HandleMessage(Message message)

{

if (message.Priority == MessagePriority.High)

{

Trace.WriteLine(message.Text + ” : Emailer processed it!”);

return true;

}

else

{

if (_nextReceiver != null)

_nextReceiver.HandleMessage(message);

}

return false;

}

}

From the above code we can see that each receiver class checks the message priority and processes it. If the priority is not matching it is send to the next receiver in the chain.

Here each receiver takes care of passing the unprocessed message. The next receiver is stored through the constructor of each receiver.

The chain will be executed until:

  • Message is processed
  • Receiver chain exhausted

Code Execution

The windows forms application attached can be used to test the control flow.

clip_image004

Here the chain is built as following:

  • Logic class holds first receiver which is Logger
  • Logger class holds the next receiver which is Emailer
  • Emailer class have null receiver denoting end of chain

Following code depicts the above chain creation:

Logic logic = new Logic();

logic.Receiver = new Logger(new Emailer(null));

Note: Please note that the advantage of this pattern is decoupling of sender and receiver. The sender does not think about the right receiver. Instead it will pass the request and the appropriate receiver should process it. The above example can be written using a list of receivers in the Logic class with a Boolean property mentioning whether the message is processed or not.

Comparing Observer and Chain of Responsibility

In the case of Observer pattern all the registered receivers will get the request. Each of the receivers is interested in processing it. But in chain of responsibility the request is passed until it is not processed.

clip_image006

Summary

In this article we have explored Chain of Responsibility pattern with a C# example. The associated source code contains the example we discussed.

Posted in Design Patterns | Tagged: , , | Leave a Comment »

Adapter Pattern

Posted by JP on November 25, 2011

Most of you might have heard about Adapter Pattern. It is a pattern commonly used in our applications but without knowing it. Adapter Pattern is one among the 23 Design Patterns. In this article I would like to examine this pattern using a simple example.

Challenge

You are working on a Square class. You need to find the Area of it using Calculator class. But the Calculator class only takes Rectangle class as input. How to solve this scenario?

clip_image002

Definition

“Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.”

Implementation

Following are the class definitions for Rectangle and Calculator.

public class Rectangle

{

public int Width;

public int Height;

}

public class Calculator

{

public int GetArea(Rectangle rectangle)

{

int area = rectangle.Width * rectangle.Height;

return area;

}

}

As we cn see from the above example an instance of Rectangle is needed to calculate the area. If we have a square class of definition below, the calculation cannot be done.

public class Square

{

public int Size;

}

Here we have to create a new CalculatorAdapter to get the work done.

public class CalculatorAdapter

{

public int GetArea(Square square)

{

Calculator calculator = new Calculator();

Rectangle rectangle = new Rectangle();

rectangle.Width = rectangle.Height = square.Size;

int area = calculator.GetArea(rectangle);

return area;

}

}

The CalculatorAdapter performs the following functions:

· Takes the Square parameter

· Convert Square to Rectangle

· Call the original Calculator.GetArea() method

· Return the value received

The invoking code is shown below:

// Create Square class and assign Size from UI

Square square = new Square();

square.Size = SquarePanel.Width;

// Use Adapter to calculate the area

CalculatorAdapter adapter = new CalculatorAdapter();

int area = adapter.GetArea(square);

// Display the result back to UI

ResultLabel.Text = “Area: ” + area.ToString();

On running the sample application we can see the following results.

clip_image004

Note: We can have other examples including Interfaces to show the above pattern. For simplicity I have avoided the interfaces. In real life the AC to DC adapter is an example of the Adapter pattern as it makes the incompatible device and power supply work together.

Summary

In this article we have explored Adapter pattern. This pattern is useful in scenarios where incompatible types are dealt with. The associated source code contains the example application we have discussed.

Posted in Design Patterns | Tagged: | Leave a Comment »

Reflection–Copy Properties

Posted by JP on November 22, 2011

Often in enterprise standard projects, we will be dealing with converting one entity into another.  Most of the cases the properties will be of same name and type.  In this case the following method is useful. 

The method saves the time of assigning each properties line by line.  Reflection is implemented to achieve this.

Reflection is upto 8 times slower than normal code but for a few dozen of entities the slowness does not arise.

 

  public static void CopyProperties(object source, object dest)
        {
System.Type type1 = source.GetType();
            System.Type type2 = dest.GetType();

            foreach (PropertyInfo pInfo1 in type1.GetProperties())
                foreach (PropertyInfo pInfo2 in type2.GetProperties())
                    if (pInfo1.Name == pInfo2.Name)
                    {
                        if (pInfo1.CanRead && pInfo2.CanWrite)
                            pInfo2.SetValue(dest, pInfo1.GetValue(source, null), null);
                        break;
                    }
        }

Usage:

public class Person
{
    public int Id
    {
        get;
        set;   
    }

    public string Name
    {
        get;
        set;   
    }
}

// Code

Person p1 = new Person ();

p1.Name = “Person Name”;

Person p2 = new Person();

CopyProperties(p1, p2);

Posted in C#, Reflection | Tagged: | Leave a Comment »

LINQ2XML Example

Posted by JP on November 21, 2011

This is one of the code sample which I worked over a forum.

From the xml file given below, we need to select the nodes with category attribute of value pending.

 

<root>
  <fault category=”pending”>
    <text>Pending Fault found on</text>
  </fault>
  <fault category=”repaired”>
    <text>Repaired Fault on</text>
  </fault>
  <genere>
    <text1>Aircraft</text1>
    <text2>Component</text2>
    <text3>Subsystem</text3>
  </genere>
</root>

 

Following the LINQ2XML Code to attain the same:

 

XElement xElement = XElement.Load(@”c:\\temp\\xml.txt”);
            var list = (from e in xElement.Elements(“fault”) where e.Attribute(“category”).Value == “pending”
                 select e).ToList();

            foreach (XElement xe in list)
                Console.WriteLine(xe.Value);

            Console.ReadKey(false);

Posted in C#, Design Patterns | Tagged: | Leave a Comment »

Visiting the Visitor Pattern

Posted by JP on November 19, 2011

Visitor Pattern is one among the 23 design patterns. It is less known but holds a good idea for OOPs enthusiasts.

Challenge

You are having a list of objects with the following class structure:

public class Member

{

public string Name;

public DateTime DateOfBirth;

}

You need to do an operation of selecting all Member having age greater than 18.

One way of the solution is add a new property called IsAboveEighteen and set the value by iterating over the items and comparing with current date. But this requires more processing.

We can achieve the same using Visitor pattern by adding a property which operations on the existing properties and returns the value.

Definition

“Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.”

Implementation

Introducing a new property named IsAboveEighteen and in the getter implement the code to read DateOfBirth property to calculate the value.

public class Member

{

public string Name;

public DateTime DateOfBirth;

public bool IsAboveEighteen

{

get

{

bool result = (DateTime.Now – this.DateOfBirth).TotalDays > 365 * 18;

return result;

}

}

}

In the above example, the new property explores the existing property values to calculate its own value. The advantage is that there is no change of structure and no extra operations to achieve the desired result.

clip_image002

The following unit tests operate on the new property and display the result having IsAboveEighteen as true.

[TestMethod()]

public void IsAboveEighteenTest()

{

IList<Member> list = new List<Member>()

{

new Member() { Name = “N1”, DateOfBirth= new DateTime(2000, 1, 1)},

new Member() { Name = “N2”, DateOfBirth= new DateTime(2000, 1, 1)},

new Member() { Name = “N3”, DateOfBirth= new DateTime(1990, 1, 1)},

new Member() { Name = “N4”, DateOfBirth= new DateTime(1980, 1, 1)}

};

var selectedList = list.Where(m => m.IsAboveEighteen);

foreach (Member member in selectedList)

Console.WriteLine(member.Name);

Assert.AreEqual(2, selectedList.Count());

}

On running the test we can see the following output.

clip_image004

Extending Visitor in Sql Server

In Sql Server the same functionality can be achieve using Computed Columns. Even though Vistor Pattern is an Object Oriented Extension we can use the concept in database too.

Let us explore this with a simple example. We are having a table to store Transaction having Quantity and Price. The table is populated with data. We need to get the TotalPrice which is Quantity multiplied by Price. Without doing any data updating we can use Computed Column as shown below to achieve the results.

clip_image006

clip_image008

The result is shown below:

clip_image010

The above result is achieved without doing any data updating.

Summary

In this article we have explored the Visitor pattern. It allows us to be add more functionality without doing much change in the structure. Keeping this pattern in mind often helps in a better way of architecting.

Posted in C#, Design Patterns | Tagged: | 6 Comments »