Sunday, February 21, 2010

Rhino Mocks

http://www.ayende.com/projects/rhino-mocks/api/files/MocksRepositoryGenerics-cs.html
http://www.ayende.com/projects/rhino-mocks/api/files/MockRepository-cs.html
http://www.codeproject.com/KB/dotnet/Rhino_Mocks_Version_20.aspx
http://www.ayende.com/projects/rhino-mocks/api/index/Functions.html
http://www.ayende.com/wiki/AllPages.aspx

http://www.ayende.com/wiki/Rhino+Mocks+Documentation.ashx
http://www.ayende.com/wiki/GetFile.aspx?File=Rhino+Mocks+3.3+Quick+Reference.pdf
http://www.ayende.com/wiki/GetFile.aspx?File=rhino_mocks.pdf
http://house9-code-samples.blogspot.com/2008/02/rhinomocks-basics.html
http://ayende.com/Blog/category/515.aspx

Tuesday, February 16, 2010

Code Generation

http://www.pnpguidance.net/Post/SampleFluentNHibernateT4TemplatesCodeGenerationLINQToSQL.aspx
http://davidhayden.com/blog/dave/category/15.aspx?Show=All

http://www.codeproject.com/KB/architecture/linqrepository.aspx

http://www.codeplex.com/RepositoryFactory

Guidance Automation Extensions - February 2008 Release
______________________________________________________
http://www.microsoft.com/downloads/details.aspx?FamilyId=DF79C099-4753-4A59-91E3-5020D9714E4E&displaylang=en

http://servicefactory.codeplex.com/releases/view/11147

http://www.microsoft.com/downloads/details.aspx?FamilyId=6C200BAC-9F33-46E3-A5A2-839FD7DC022F&displaylang=en
http://blogs.microsoft.co.il/blogs/gilf/archive/2010/01/20/using-repository-pattern-with-entity-framework.aspx

Generic WCF Converter function

public TDestination Convert(TSource objSource, TDestination objDestination)
{
if (objSource == null)
{
return default(TDestination);
}

if (objDestination == null)
{
return default(TDestination);
}

// Read Destination Properties
foreach (PropertyInfo propInfo in objDestination.GetType().GetProperties())
{
if (!propInfo.PropertyType.IsGenericType)
{
// Read Source Properties
object val = null;
foreach (PropertyInfo info in objSource.GetType().GetProperties())
{
// Match Source & Destination Properties
if (propInfo.Name == info.Name)
{
if (info.CanRead)
{
val = info.GetValue(objSource, null);
}

if (propInfo.CanWrite)
{
// If Source is Enum Type and Destination is byte type
if (info.PropertyType.IsEnum == true && propInfo.PropertyType.IsEnum == false)
{
byte tmpVal = System.Convert.ToByte(info.PropertyType.GetField(info.GetValue(objSource, null).ToString()).GetRawConstantValue());
propInfo.SetValue(objDestination, tmpVal, null);
}
else
{
propInfo.SetValue(objDestination, val, null);
}
}

break;
}
}
}
}

return objDestination;
}

Friday, February 12, 2010

CSLA

http://en.wikipedia.org/wiki/Component-based_Scalable_Logical_Architecture
http://www.lhotka.net/cslanet/Info.aspx

CAB,EntLib files

CAB can be downloaded from:
http://msdn.microsoft.com/library/en-us/dnpag2/html/cab.asp

EntLib can be downloaded from:
http://msdn.microsoft.com/library/en-us/dnpag2/html/EntLib2.asp

Books

http://www.amazon.com/Expert-C-2008-Business-Objects/dp/1430210192/ref=sr_1_2?ie=UTF8&s=books&qid=1265963916&sr=8-2
www.amazon.com(applying UML and patterns)

Thursday, February 11, 2010

Presentation Model

http://www.codeproject.com/KB/smart/PMinAction.aspx

Smart Client Software Factory (SCSF)

http://www.codeproject.com/KB/smart/SCSF_CSLA_ProjectTracker.aspx
http://msdn.microsoft.com/en-us/magazine/cc188688.aspx
patterns & practices Smart Client
http://smartclient.codeplex.com/
http://martinfowler.com/eaaDev/PresentationModel.html
http://www.codeplex.com/smartclient

Wednesday, February 10, 2010

svcutil

svcutil /d:d:\LearningWCF /noconfig /o:serviceproxy.cs /r:ContentTypes.dll /ct:System.Collections.Generic.List`1 http://localhost:8000

Sunday, February 7, 2010

Calling WCF Services: A better way than generating a proxy

Introduction

This article deals with replacing the auto generated proxy class in WCF with a generic class such that if the interface of the service contract is known, there is no need of ever generating a proxy class, which ends up improving developer productivity.

Audience
It is assumed that the audience is aware of WCF, operation contracts, data contracts, WCF Channel, Lambda Expressions, and Generics to understand the code. If however you just want to use the code, basic knowledge of C# is required.

Background
It is only in a dream that we can have all our interfaces closed before development phase. In practice, interfaces change because the method signature must change, or a new requirement comes in, or some other unanticipated task pops up.

The proxy is usually generated after defining the interface, and it is required that all associated code such as implementers of the interface compile. There are multiple instances where some interface changes need to be commented to get the proxy and then regenerate the proxy at least three times. This problem is compounded as the number of implementers of the interface increases.

Using the proxy also generates equivalent classes of the data contract for which adapters need to be written in some extreme programming requirements.

Solution
These problems can be eliminated by generation of a proxy. To achieve this, two technologies are used:

Generics - This helps us to specify a type at runtime
Lambda Expressions - This helps us to specify a code block (name of the operation contract method) to be passed to a function (to execute the code)
Code
This section jumps straight into the code. The first section describes the code of the service and how it will be used. This is followed by code of the proxy helper and how to use it. In this article, the code has been written in Visual studio 2010 using the .NET 3.5 framework. In case the client can only be created in .NET 2.0, the client code may be written using anonymous delegates.

Code Organization
WCFInterface - This class contains the interface of the service contract along with the data contracts. In a regular WCF project, these are part of the service implementation, but in this scenario, they have been separated. This project will be referenced by the client.

WCFService1 - This is the implementation of the service contract by a class.
WCFProxy - This is the proxy helper class whose job is to replace the proxy.
WCFClient - This is the WCF client which uses the proxy.
It should be noted that channel definition on both the server and the client remains unchanged and will be picked from the .config file.

The Service
The service in this code as visible is the default WCF service generated by the template. The only change done to the code is separation of the service implementation from the service contract in a separate project. The WCFInterface project is referred to by both the client and WCFService1.

Calling Sync
This section describes the code to call the WCF service in a synchronous call.

The proxy helper
This is a delegate which will be used by the client to specify the method name on the interface. This delegate says tell us the name of the code of type T.

Collapse Copy Code///
/// This delegate describes the method on the interface to be called.
///

/// This is the type of the interface
/// This is the method.

public delegate void UseServiceDelegate(T proxy);This is a simple method. It creates a channel using the channel factory for the specified WCF end point and opens the channel. It then calls the code block - which is the method on type T as told by UseServiceDelegate.

Collapse Copy Code///
/// Invokes the method on the WCF interface with the given end point to
/// create a channel
/// Usage
/// new ProxyHelper().Use(serviceProxy =>
/// {
/// value = serviceProxy.MethodName(params....);
/// }, "WCFEndPoint");
///

/// The WCF interface method of interface of type T
///
/// The end point.
public void Use(UseServiceDelegate codeBlock, string WCFEndPoint)
{
try
{
//Create an instance of proxy
this.proxy = GetChannelFactory(WCFEndPoint).CreateChannel() as IClientChannel;
if (this.proxy != null)
{
//open the proxy
this.proxy.Open();
//Call the method
codeBlock((T)this.proxy);
this.proxy.Close();
}
}

catch (CommunicationException communicationException)
....The client
This is the client to the above code. We tell the LamdaProxyHelper that we want a proxy for type IService1 and then call the Use method. In the Lambda Expression, we call the method GetData and return the value in the variable value (Lambda Expressions allow us to access the local variables).

Collapse Copy Code//using a proxy for the interface IService1 call the method GetData
//call a sync method
new LamdaProxyHelper().Use(serviceProxy =>
{
//save the return value in value
value = serviceProxy.GetData(7);
}, "WCFEndPoint");//use the end point name WCFEndPoint for this proxyI would suggest that at this point of time, you should try this code and understand this completely before moving to the next piece which is calling async.

Calling Async
Proxy helper
This code follows a similar pattern; here, the delegate tells that it will be sending an additional parameter while executing. This is the object obj. This is sent because it helps during the async execution to pass additional parameters such as the ID of the request so as to tie up the async response or the object on which the async method has to be executed or anything else.

Collapse Copy Code///
/// This delegate describes the method on the interface to be called.
///

/// This is the type of the interface
/// This is the method.
/// This is any object which may be used to identify
/// execution instance.
public delegate void UseServiceDelegateWithAsyncReturn(T proxy, object obj);The proxy in this case is quite similar, except that now the execution is done on a new thread to provide the async pattern.

Collapse Copy Code///
/// This method calls the WCF Service in a new thread. The calling of other method
/// for result is the
/// responcibility of the client code
///

/// The method on the WCF service to be called
/// This is the WCF end point
/// This is any object which may help in exeution of the async
/// parameters
public void UseAsyncWithReturnValue(UseServiceDelegateWithAsyncReturn codeBlock,
string WCFEndPoint, object obj)
{
try
{
this.proxy = GetChannelFactory(WCFEndPoint).CreateChannel() as IClientChannel;
if (this.proxy != null)
{
this.codeBlockWithAsyncReturn = codeBlock;
new Thread(() =>
{
//Create a new thread and on the new thread call the methos
codeBlock((T)this.proxy,obj);
this.proxy.Close();
}).Start();
}
}
catch (CommunicationException communicationException)
{...The client
The client is called on a separate thread, but this time, the client code just doesn't tell the method to be called, it also calls up an async method to pass results: CallBackForReturnValueOfGetData.

We should note that the same object (Guid in this case) is passed back. In certain scenarios, we may choose to send the method as the object or any other code. It should be noted that type safety is maintained.

Collapse Copy Codenew LamdaProxyHelper().UseAsyncWithReturnValue((proxy, obj) =>
{
//save the return value in value
value = proxy.GetData(9);
CallBackForReturnValueOfGetData(value, (Guid)obj);
}, "WCFEndPoint",Guid.NewGuid());
//use the end point name WCFEndPoint for this proxy

///
/// This is a type safe return method for getting the return value on a
/// seperate thread. This is called when the method is actully invoked.
///

/// This is the return value
static void CallBackForReturnValueOfGetData(string returnValue,Guid id)
{
Console.WriteLine("The return value is =" +
returnValue+" which was called on the Guid = " +id);
}Calling async with no return value
This is a similar proxy helper code in which we exploit the BeginInvoke method on a delegate. It allows completion of the code on a separate thread and then calls the method implementing the AsyncCallback delegate.

The proxy helper
In this code, a delegate of type AsyncCallback via AsyncResults called by the method closes the proxy and then calls the callBack method.

Collapse Copy Code///
/// Invokes the method on the WCF interface with the given end point to
/// create a channel
/// Usage
/// new ProxyHelper().Use(serviceProxy =>
/// {
/// value = serviceProxy.MethodName(params....);
/// }, "WCFEndPoint",callBackMethodName,id);
///

/// The WCF interface method of interface of type T
///
/// The end point.
/// The object instance used to identify in callback
public void UseAsync(UseServiceDelegate codeBlock, string WCFEndPoint,
AsyncCallback callBack,object obj)
{
try
{
this.proxy = GetChannelFactory(WCFEndPoint).CreateChannel() as IClientChannel;
if (this.proxy != null)
{
this.proxy.Open();
this.callBack = callBack;
this.codeBlock = codeBlock;
IAsyncResult result = codeBlock.BeginInvoke((T)this.proxy, AsyncResult, obj);
}The client
The client in this case is rather self explanatory, and is doing similar tasks as before.

Collapse Copy Codenew LamdaProxyHelper().UseAsync(serviceProxy =>
{
serviceProxy.GetDataUsingDataContract(compositeType);
}, "WCFEndPoint", AsyncResultCallBack, Guid.NewGuid());GetChannelFactory
This class is a simple method whose job is to provide a channel based on the channel name. It creates a singleton for each channel and keeps them. This gives performance benefits as creation of a channel is expensive.

Collapse Copy Code///
/// This is the end point
/// Return List of all the invoked proxies
private ChannelFactory GetChannelFactory(string WCFEndPoint)
{
ChannelFactory channelFactory = null;
//Check if the channel factory exists
//Create and return an instance of the channel
if (! channelPool.TryGetValue(WCFEndPoint,out channelFactory))
{
channelFactory = new ChannelFactory(WCFEndPoint);
channelPool.Add(WCFEndPoint, channelFactory);
}
return channelFactory;
WCF Client Proxy IDisposable - Generic WCF Service Proxy
I have run into this issue on several clients now. The basic issue is when using WCF on the client, using ClientBase<>, and you do not close the channel, you can tie up the server until the channel times out. So, once the max instances, sessions, or concurrent calls is reached and the clients are not closing their channels, the server will block and queue up subsequent calls. The un-closed client channels will eventually timeout, which causes a fault on the client, and the next set of calls will then make it through.

When I first hit this issue, my thought was to wrap my client base code in a using () statement so Dispose() would then be called. But, ClientBase<> does not implement IDisposable. Here is some info on the issue...


So, after lots of testing to understand all the WCF knobs to tweak, I came up with a generic class I called ServiceProxy for clients to use when creating/using client channels. This has been through several revisions and here is what I have ended up with. The idea to add support for the delegate came from this blog entry


Here is the code for my generic service proxy wrapper...

public class ServiceProxy : ClientBase, IDisposable where TInterface : class
{
public delegate void ServiceProxyDelegate(TInterface proxy);
public ServiceProxy(): base(typeof(TInterface).ToString())
{
}

public ServiceProxy(string endpointConfigurationName): base(endpointConfigurationName)
{
}
protected override TInterface CreateChannel()
{
return base.CreateChannel();
}

public TInterface Proxy
{
get{return this.Channel;}

}
public static void Call(ServiceProxyDelegate proxyDelegate)
{
Call(proxyDelegate, typeof(TInterface).ToString());

}

public static void Call(ServiceProxyDelegate proxyDelegate, string endpointConfigurationName)
{
ChannelFactory channel = new ChannelFactory(endpointConfigurationName);
try
{
proxyDelegate(channel.CreateChannel());

}
finally
{
if (channel.State == CommunicationState.Faulted)
{
channel.Abort();
}else{
try
{
channel.Close();
}
catch
{
channel.Abort();
}
}
}
}

public void Dispose()
{
if (this.State == CommunicationState.Faulted)
{
base.Abort();
}
else{
try
{
base.Close();
}
catch
{
base.Abort();
}
}
}
}

And, here are some usages samples...

//delegate example1

string response = null;

ServiceModel.ServiceProxy.Call(p =>
{
response = p.DoStuff("ServiceProxyUsingTest");
}
);

//delegate example2

string response = null;
ServiceProxy.Call(p => response = p.DoStuff("ServiceProxyUsingTest"));


//using example

string response = null;
using (ServiceProxy service = new ServiceProxy())
{
response = service.Proxy.DoStuff("ServiceProxyUsingTest");
}

Friday, February 5, 2010

WCF Design Pattern: Generic Service

WCF provides great opportunities to architects for building robust applications. One thing many architects may not realize is that it is also a great technology for building reusable patterns as well; and to do so without incurring limits on the types of entities and fields operated on by the service.

A common task is to create an SOA that provides business rules in a WCF Facade that also calls into an abstracted data storage mechanism. This data storage can vary from service to service depending on the originating source for the data that the Facade is exposing as a service. Although it is very easy to create this pattern, it's not usually intuitive to do so in a generic manner; but since you're reading this you know I have a pattern in hand that fits the bill!

The WCF Generic Service Pattern has three parts: the service facade, business entity (or entities) and business entity persistence. To create a reusable pattern, we start with our entity as an abstract base class:

public abstract class EntityBase
{
Key m_keyID;

[DataMember]
public Key ID
{
get { return m_keyID; }
set { m_keyID = value; }
}
}
This looks like Generics 101, right? Just a simple entity with a definable key. What could be easier? Well, when we create our concrete entity all we need to do is supply a type for the key!

[DataContract]
public class Entity : EntityBase
{
// Nothing needed!
}
OK, nothing is needed to support using a GUID for the value of the ID property. But this is a WCF article, so you should note a couple of things. First, DataContract and DataMember are not married to each other. I've defined a DataMember in the abstract EntityBase, but it is not a DataContract; which it couldn't be because you cannot instantiate EntityBase. The Entity class is what's marked as a DataContract and the base class members marked as DataMember will be serialized by WCF.

So, we've created our Entity, so how are we going to save it to the database? Well, not only are we abstracting details about the entity, we are also abstracting details about persistence. What if one entity required saving to XML while another required saving to Oracle? It's as easy as spelling interface!

public interface IEntityPersistence
{
TEntity GetByKey(Key key);
}
Hmm, see the generics on the Interface? This is the meat-and-potatoes of this design pattern which allows any number of implementations to be created to work with the entities of your choice. To handle our previously defined entity, the persistence class looks like this:

public class Persistence : IEntityPersistence
{
#region IEntityPersistence Members

public Entity GetByKey(Guid key)
{
// TODO: Implement your data access code here!
throw new Exception(
"The method or operation is not implemented.");
}

#endregion
}
Note that the class declaration sets the persistence provider to use our Entity class with a Guid for the key. You'll need to handle the actual persistence here.

OK, we have our entity and our persistence, now let's expose them as a service! Best practices for WCF say to use an interface for our service's ServiceContract:

[ServiceContract()]
public interface IService
{
[OperationContract]
TEntity GetByKey(Key key);
}
Here we define both the WCF ServiceContract and the OperationContract for GetByKey. Notice the use of generics; we are once again making our service pattern completely reusable. Next, we create an abstract service base class that has our reusable functionality:

public abstract class ServiceBase : IService
{
protected IEntityPersistence m_objPersistence = null;

#region IService Members

public TEntity GetByKey(Key key)
{
return m_objPersistence.GetByKey(key);
}

#endregion
}
This easy! We've declare an instance variable to hold our persistence instance and actually used it to return our entity from our data store. What's missing? Oh, yeah, the instantiation of the persistence class! Now we need to provide an actual public class that WCF can instantiate:

public class Service : ServiceBase
{
// This constructor sets the appropriate
// persistence instance for the entity
// being exposed by this service.
public Service()
{
m_objPersistence = new Persistence();
}

// All the business rules for the entity
// is handled in the ServiceBase class!
}
And that's it! We now have a complete WCF service build from our WCF Generic Service pattern. We could create any number of sub-classes of EntityBase and matching facade and persistence classes. This is a very powerful tool for creating a consistent API with WCF.
WCF does not support the use of generic methods for service operation. In other words, only concrete types can be used for service operations. Open generic types cannot be used. Now, it is important to clarify this is not a limitation of WCF. Rather, it is a limitation of WSDL, which is used to expose service metadata to consumers. There is no construct within WSDL to define a generic type. Generally speaking, I agree with this behavior since it decreases the coupling between a client and service.
Although generic methods are not supported, it is possible to expose generic objects for the purpose of exchanging data. However, there are some limitations. Let's take a closer look:

Bounded Generics
In his book Programming WCF Services , Juval Lowy points out that it is possible to use "bounded generics." This is sometimes referred to as closed generics. Basically, it refers to defining a generic class for your data contract, but it is restricted to a specific type in the service operation. This may sound somewhat vague. So, here is an example to provide a better illustration:

[DataContract]
public class MyGenericObject
{
private T _id;
private string _description;

public MyGenericObject()
{
}

[DataMember]
public T ID
{
get { return _id; }
set { _id = value; }
}

[DataMember]
public string Description
{
get { return _description; }
set { _description = value; }
}
}

[ServiceContract(Namespace = "http://jeffbarnes.net/2007/05/boundedgenerics/")]
public interface IBoundedGenerics
{
[OperationContract]
MyGenericObject GetGenericObject(int id);
}

As you can see, a generic object (MyGenericObject) is exposed to the client. However, the service operation restricts the usage to being of type integer. This is what Juval Lowy means by "bounded generics." However, it should be noted the client will not see the object as a generic. When the metadata is generated to describe the service operation, the data contract and service operation will appear as a normal non-generic class.

[DataContract]
public class MyGenericObjectOfint
{
private int _id;
private string _description;

public MyGenericObjectOfint()
{
}

[DataMember]
public int ID
{
get { return _id; }
set { _id = value; }
}

[DataMember]
public string Description
{
get { return _description; }
set { _description = value; }
}
}
The resulting name is due to an applied naming pattern that consists of:
Generic Class Name + "Of" + Type Parameter Name + Hash
The hash is added under certain conditions to reduce the risk of a name collision. However, you should be aware the hash can create a really ugly class name. It could be something like: MyGenericObjectOfSomeTypegDh87uV. Obviously, this isn't an ideal name for the client to use. Fortunately, you can override the use of the hash by specifying the Name property of the DataContract. It supports parameters that correspond to the generic type parameters.

For example:
[DataContract(Name = "MyGenericObjectUsing{0}"]
public class MyGenericObject
Using this approach, it is still possible to leverage generics from within the service implementation, but there is nothing special going on from the client's perspective.
You can download the sample code from here.
http://jeffbarnes.net/download/blog/200705/genericserialization.rar