Thursday, May 22, 2008

Unique Index Schema Information in SQL Server

Unique indexes along foreign key constraints are used to model One-To-One relationships in Database model design. In fact, when it comes to the DB design, the only difference between a One-To-One relationship and a One-To-Many relationship is that Unique index. For Data Access code generation purposes the existence of the unique index will effectively tell you, for example if you are generating navigation properties, whether to create a simple entity type navigation (One-To-One) or an entity array type navigation (One-To-Many) between the two entities that take part in the data base relationship.

In ADO.NET the GetSchema methods can be used to get Schema information from different Data base provider types; unfortunately for SQL Server Databases unique index information is not provided with that API. Don't panic though, one way or another SQL Server hast to store the unique index information in its catalog tables so after digging into the master database views list for a while, we bump into the table sys_indexes and its is_unique column. An index can be applied upon many columns therefore we'll need to join with sys.index_columns and sys.columns in order to get the column name as well.

SELECT c.[name] as column_name, a.[name] as index_name, is_unique
FROM sys.indexes a INNER JOIN sys.index_columns b
ON a.object_id = b.object_id AND a.index_id = b.index_id
INNER JOIN sys.columns c
ON b.object_id = c.object_id and b.column_id = c.column_id
WHERE a.object_id = OBJECT_ID(N'dbo.yourTable')

kick it on DotNetKicks.com

Saturday, May 17, 2008

Dependency Injection in WCF Services Part 3

In the first post of these series, I explained the problems you may run into when applying Dependency Injection in your distributed service layer, and in the second one I put the theory in practice using Castle Windsor WCF Facility.

Now that our DI container instantiates our services, we can take advantage of other features not necessarily related to Dependency Injection available in the container. Particularly in this post I'll drift away a bit from dependency injection and I'll focus on the interception capabilities that Castle Windsor framework offers.

Let's take the sample that I've been using for these series and say for example that we want to use Enterprise Library Application Loggin Block so as to log every method execution in our service object.
A simple implementation would be to include the logging call in the service implementation.
namespace DISample.Service
{
public class CustomerService:ICustomerService
{
#region properties
private ICustomerDataAccess customerDataAccess;
public ICustomerDataAccess CustomerDataAccess
{
get { return customerDataAccess; }
set { customerDataAccess = value; }
}
#endregion
#region ICustomerService Members
public Customer GetCustomer(long id)
{
Logger.Write("GetCustomer Start");
Customer customer = CustomerDataAccess.GetCustomer(id);
Logger.Write("GetCustomer End");
return customer;
}

#endregion
}
}
So we are leaving the logging responsability to the service class itself... That doesn't sound quite right, does it? The service responsability is to interact with the Data Access layer and/or carry out business process but logging is a cross cutting concern that has nothing to do with the actual service implemenation. Besides, for the sake of code cleanignless and reusability, in my Service code I don't want stuff that is not related to the Service main purpose.

Then, how we can possibly achieve logging in our service object leaving the logging calls out of our service implementation? Well, we might use the Decorator pattern for that. This pattern gives the ability to extend the functionality of a class without changing its orginal implementation.
Let's create the CustomerServiceLogginDecorator logging decorator in order to include logging capabilities to our service.
namespace DISample.Service
{
public class CustomerServiceLoggingDecorator:ICustomerService
{
#region properties
private ICustomerService customerService;
public ICustomerService CustomerService
{
get { return customerService; }
set { customerService = value; }
}
#endregion
#region ICustomerService Members
public Customer GetCustomer(long customerId)
{
Logger.Write("GetCustomer Start");
Customer customer = CustomerService.GetCustomer(customerId);
Logger.Write("GetCustomer End");
return customer;
}
#endregion
}
}
Notice that the decorator implements the same interface that our service implementation; that's the whole point of the Decorator pattern. The service consumers use the service through its interface (ICustomerService) and it's through the DI container that we specify a particular service implementation for that interface. Therefore, we can create our decorator as a service frontend and inject the actual service implementation into the decorator.
<configuration>
<components>
<component id="CustomerService"
service="DISample.Service.ICustomerService, DISample.Service"
type="DISample.Service.CustomerServiceLoggingDecorator, DISample.Service">
</component>
<component id="CustomerServiceImpl"
service="DISample.Service.ICustomerService, DISample.Service"
type="DISample.Service.CustomerService, DISample.Service">
</component>
<component id="CustomerDataAccess"
service="DISample.DataAccess.ICustomerDataAccess, DISample.DataAccess"
type="DISample.DataAccess.CustomerDataAccess, DISample.DataAccess">
</component>
</components>
</configuration>
Notice as well that, since the decorator uses ICustomerService interface as dependency, the underlying implementation of the service remains hidden and therefore we can use the DI container to inject as many ICustomerService decorators as we wish upon the real service implementation. Let's imagine that we want to add an exception decorator...
<configuration>
<components>
<component id="CustomerService"
service="DISample.Service.ICustomerService, DISample.Service"
type="DISample.Service.CustomerServiceExceptionDecorator, DISample.Service">
</component>
<component id="CustomerServiceLogging"
service="DISample.Service.ICustomerService, DISample.Service"
type="DISample.Service.CustomerServiceLoggingDecorator, DISample.Service">
</component>
<component id="CustomerServiceImpl"
service="DISample.Service.ICustomerService, DISample.Service"
type="DISample.Service.CustomerService, DISample.Service">
</component>
<component id="CustomerDataAccess"
service="DISample.DataAccess.ICustomerDataAccess, DISample.DataAccess"
type="DISample.DataAccess.CustomerDataAccess, DISample.DataAccess">
</component>
</components>
</configuration>
Ok, so we got it, there are no longer cross cutting concerns in my service implementation but probably you´ll have already realized that this solution is not the best either. If we carried on with this approach we'd need to create a decorator for each cross cutting concern in each service, it means that we could end up with a number of decorator classes up to (number of Services)*(number of cross cutting concerns) = let´s call this idea off now!

Well, it looks like the Decorator Pattern can be the way but we need something to remove from us the burden of creating for a single aspect a bunch of service specific decorators. Fortunately, castle framework comes to our rescue and offers us the Interceptor functionality which allows to create independent and reusable cross cutting concern implementations.
Let´s create our reusable logging interceptor.
using Castle.Core.Interceptor;
using Microsoft.Practices.EnterpriseLibrary.Logging;

namespace DISample.Interceptor
{
public class LogginInterceptor:IInterceptor
{
#region IInterceptor Members
public void Intercept(IInvocation invocation)
{
Logger.Write(invocation.Method.Name + " Start");
invocation.Proceed();
Logger.Write(invocation.Method.Name + " End");
}
#endregion
}
}
And to start using it, we just have to define it in the castle configuration file.
<configuration>
<components>
<component id="CustomerService"
service="DISample.Service.ICustomerService, DISample.Service"
type="DISample.Service.CustomerService, DISample.Service">
<interceptors>
<interceptor>${LoginInterceptor}</interceptor>
</interceptors>
</component>

<component id="LoginInterceptor"
type="DISample.Interceptor.LoginInterceptor, DISample.Interceptor"/>

<component id="CustomerDataAccess"
service="DISample.DataAccess.ICustomerDataAccess, DISample.DataAccess"
type="DISample.DataAccess.CustomerDataAccess, DISample.DataAccess">
</component>
</components>
</configuration>
That's great, isn't it? We define independent interceptors that can be applied upon any class regardless of its type; Castle will take care of the call flow an interception for us.

To that's it, we have used Castle framework to apply cross cutting concerns in our WCF Service... But that's not what WCF Custom Behaviours are for? Yes, Custom Behaviours get injected in the WCF call stack and in there you can implement some aspects not related to your service implementation like logging, catching, transaction handling, etc. Besides the Enterprise Library 3.1 comes along with a set of Custom Behaviors for WCF that are nothing more that thin wrappers upon the Application Blocks like the Validation Block Custom Behavior. Then, why would we want to build Castle Interceptors if we can use the Enterprise Library WCF custom Behaviors?.

Thinking in terms of the overall application and not only about the service layer, you might decide to apply cross cutting concerns to your web layer, your controller layer, your data access layer, etc. and for that WCF Custom Behaviours have no use. The bottom line is that if you want to use a unique homogeneous mechanish to handle cross cutting concers across all your application layers, WCF Custom Behaviours are not the solution!

Having said that, in the next post of these series I'll show how to implement a more sophisticated Interceptor than the Logging one I explained in this post; Particularly I'll show what it takes to implement an equivalent of the Enterprise Library WCF Validation Custom Behaviour in a Castle Interceptor.

kick it on DotNetKicks.com

Saturday, May 10, 2008

JSON services in ASP.NET Ajax

Lately the use of client centric development model in .NET is getting increasingly popular. In contrast to the traditional server model where html tags are rendered in server side and then sent to the browser, the client centric approach consist of the use of asynchronous HTTP requests to retrieve data from server side and then do the html rendering in client side code.

The main advantage of this client centric approach is that the communication between the browser and the server gets much lighter; the browser doesn't need to post the page to get information from the server, it rather issues asynchronous calls to Web Services, which implement the JSON protocol, for retrieving the data. You might be wondering why XML-SOAP or other XML based RPC protocols are not used instead of that JSON...

JSON is a non-markup based language which has some limitations comparing to XML languages (i.e: lack of namespaces) but that simplicity makes it lighter, easier to handle by browsers, and overall more performant and more suitable for this web client scenario.

Unfortunately there is a catch :( ; since the rendering is done in client side, you'd better forget about using your automatically rendered ASP.NET controls and be prepared to start messing around extensively with javascript code for the rendering... No need to go through that pain though, there are some third party client based controls that implement rendering through javascript libraries, particularly you might want to check what this open source control library can offer you.

Well, now that we have gone through the theory, how can we put that in practice in ASP.NET? How can we implement and consume a JSON service?
ASP.NET Ajax framework provides some built-in mechanisms to handle JSON communication and serialization automatically.
These mechanisms are Page Methods, Ajax Web Services and Ajax WCF Services and I'm going to spend the rest of this post to do a brief walkthrough on them.


Page methods

A page method is a static function marked as a web method and declared within the page code behind. This function can be called from javascript code through a predefined class/keyword called PageMethods. Let's take a look in a sample step by step.

First the Page method execution has to be enabled in the asp.net ScriptManager.
<asp:ScriptManager ID="scriptManager" runat="server" EnablePageMethods="true" />
Now it's time to implement the static web method in the page's code behind.
public partial class _Default : System.Web.UI.Page
{
[WebMethod]
public static String ToUpper(string name)
{
return name.ToUpper();
}
}
Finally, the method is consumed from a script included in the page. As I said before the call execution follows an asynchronous pattern, therefore in the sample below if the operation succeds the resulting string in upper case is passed to the OnSucceded method, otherwise the OnFailed method receives the .NET exception.
function ToUpper(name)
{
PageMethods.ToUpper(name, OnSuccedeed, OnFailed);
}
function OnSuccedeed(res)
{
alert(res);
}
function OnFailed(error)
{
// Alert user to the error.
alert(error.get_message());
}

Web Services


One of the main differences between Page Methods and Ajax Web Services is that Page Methods can only be used by a single Page and Web Services can be used from as many pages as it’s needed. Needlees to say, both Ajax Web Services and Page Methods use JSON as communication protocol. Let's rework the previous example to use Web Services.

First the HTTP Handler that will serve AJAX Web services requests and responses needs to be included in the web.config file.
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
Next step is to create a web service, which I'll call StringHandler.asmx. The Web Service's class needs to be marked with the ScriptService attribute and ToUpper web method to be implemented.
namespace JsonServicesSample
{
[ScriptService]
public class StringHandler : System.Web.Services.WebService
{
[WebMethod]
public string ToUpper(String input)
{
return input.ToUpper();
}
}
}
We are getting there, now it's just to include the server through the ScriptManager...
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference
Path="~/StringHandler.asmx" />
</Services>
</asp:ScriptManager>
and everything is ready to retrieve data from the client script.
function ToUpper(name)
{
JsonServicesSample.StringHandler
.ToUpper(name, OnSuccedeed, OnFailed);
}
function OnSuccedeed(res)
{
alert(res);
}
function OnFailed(error)
{
// Alert user to the error.
alert(error.get_message());
}

WCF Services

The .NET 3.5 framework release came along with some fixes and extensions upon the early WCF .NET 3.0 version; one of those extensions is the webHttpBinding binding which implements JSON serialization and communication protocol.
So for those who use VS2008 and .NET 3.5 let's rework the sample for the last time.

First of all the service implementation has to be changed to include the WCF contract attributes; for the sake of simplicity I won't create a separate interface for the contract, I'd rather apply the contract attributes in the implementation itself.
namespace JsonServicesSample
{
[ServiceContract
(Namespace="JsonServices.Contract.Sample")]
[AspNetCompatibilityRequirements(
RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class StringHandler : System.Web.Services.WebService
{
[OperationContract]
public string ToUpper(String input)
{
return input.ToUpper();
}
}
}
On top of the WCF contract attributes, the AspNetCommpatibilityRequirements attribute is provided. That attribute will allow the WCF service to have access to the HTTP context (i.e.: ASP.NET Session variable) and besides, it will tell the runtime to ensure at Service Host creation time that all the enpoints defined for the JSON contract use the Web http binding.
Now it's time to define the service and its endpoint in Web.config file, notice that the AspNetCompatibilityRequirements attribute needs to be defined at the ServiceHost level as well.
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="StringHandlerBehavior">
<enableWebScript/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<services>
<service name="JsonServicesSample.StringHandler">
<endpoint address=""
behaviorConfiguration="StringHandlerBehavior"
binding="webHttpBinding"
contract="JsonServicesSample.StringHandler"/>
</service>
</services>
</system.serviceModel>
Since the service will be deployed in a IIS environment, the StringHandler.svc is created.
<%@ServiceHost
Service="JsonServicesSample.StringHandler" %>
The server configuration tasks are done, now the service reference needs to be included in the page's Script Manager
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference
Path="~/StringHandler.svc" />
</Services>
</asp:ScriptManager>
And everything is ready to start using the service from client side script code.
function ToUpper(name)
{
JsonServices.Contract.Sample.StringHandler
.ToUpper(name, OnSuccedeed, OnFailed);
}
function OnSuccedeed(res)
{
alert(res);
}
function OnFailed(error)
{
// Alert user to the error.
alert(error.get_message());
}
You may have already noticed that instead of using the service .NET class namespace (JsonServicesSample) as we did in the Web Services sample, this proxy uses JsonService.Contract.Sample, but what the ** is that? Well if you go back to the StringHandler implementation you'll notice that the ServiceContract defines a namespace...
[ServiceContract
(Namespace="JsonServices.Contract.Sample")]
So the bottom line is that WCF client-side proxys use the contract namespace in contrast with Ajax Web services which use the .NET class namespace instead..
And that's it, our WCF service and client are ready. Before finishing though, it's worth mentioning the WebScriptServiceHostFactory Service Host Factory and how it can help us to remove configuration from Json WCF services.
Comparing to the Web service solution, in WCF sample an additional step was taken in order to define the service and endpoint configuration. If you want to keep it simple and skip that step you can do it using the WebScriptServiceHostFactory Service Host factory. This factory creates ServiceHosts with the default services, endpoints and behaviours suitable for this Json web environment so explicit configuration is no longer needeed
In order to achieve it, if we look at the sample then, the service factory is declared in the .svc file...
<%@ServiceHost
Service="JsonServicesSample.StringHandler"
Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"%>
...so the WCF configuration can be now wiped out from the web.config file.

That's all folks! I hope that if you weren't familiar with this subject this rather long post has given you an idea of what it takes to implement basic Json services in ASP.NET.

kick it on DotNetKicks.com

Saturday, May 3, 2008

Dependency Injection in WCF Services Part 2

In the first post of these series, I explained the problems you may run into when applying Dependency Injection in your distributed service layer and some of the available solutions to get them around, mainly focusing WCF services. Let's finish off with the theory and put one of those solutions in practice, shall we? In this post I'll rework the sample that I used in my previous post to show the Service Locator pattern in order to use Dependency Injection instead. As in the project that I'm currently working on we are using Castle, I'll use WCF Castle facility to do the service injection.

Let's take then my Service Locator sample
    public class CustomerService:ICustomerService
{
#region ICustomerService Members
public Customer GetCustomer(long id)
{
ICustomerDataAccess da;
da = Global.Container.Resolve<ICustomerDataAccess>();
return da.GetCustomer(id);
}

#endregion
}
and rework it to use Dependency Injection
    public class CustomerService:ICustomerService
{
#region properties
private ICustomerDataAccess customerDataAccess;
public ICustomerDataAccess CustomerDataAccess
{
get { return customerDataAccess; }
set { customerDataAccess = value; }
}
#endregion
#region ICustomerService Members
public Customer GetCustomer(long id)
{

return CustomerDataAccess.GetCustomer(id);
}

#endregion
}
You can notice that with those changes our service class is no longer dependant on the DI container for resolving the CustomerDataAccess implementation like it is in the Service Locator example. Instead, the Data access dependency is a property that can be injected by an external agent, which can be whatever DI container we want to use or even a simple factory... Let's focus on this sample though!

The next step is to create a Castle configuration file called "Objects.xml" where both service and data access objects are defined.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<components>
<component id="CustomerService"
service="DISample.Service.ICustomerService, DISample.Service"
type="DISample.Service.CustomerService, DISample.Service">
</component>
<component id="CustomerDataAccess"
service="DISample.DataAccess.ICustomerDataAccess, DISample.DataAccess"
type="DISample.DataAccess.CustomerDataAccess, DISample.DataAccess">
</component>
</components>
</configuration>
As you can see there is no need to connect the DataAccess dependency to the Service object in the configuration file; Castle automatically wires it up.

Now that the Service code is ready for injection and the objects are defined in a configuration file, it's time to use the WCF facility to do the actual service injection.
In order to install the dependency injection behavior, Castle facility uses a a custom WCF ServiceHost. Then, for a non-IIS 6.0 environment and asuming that the service and the endpoint configuration are located in an external configuration file, our WCF host creation would look something like this.
WindsorContainer container = new WindsorContainer("Objects.xml");
Uri uri = new Uri("net.tcp://localhost/DISample");
WindsorServiceHost host = new WindsorServiceHost(container.Kernel, typeof(CustomerService), uri);
host.Open();
We instantiate the Windsor container with our object configuration file so as to be used by the custom service host... and that's all for non-IIS6.0 hosts!

As you may already know, ServiceHost instatiatation model for WCF services host under II6.0 is different: We don't explictly create the ServiceHost; instead ServiceHosts are created by a ServiceHostFactory on each HTTP request.
WCF castle facility provides a custom ServiceHostFactory that can be specified for its use in IIS6 .svc service files. Let's change the default CustomerService.svc accordingly.
<%@ ServiceHost Service="CustomerService"
Factory="Castle.Facilities.WcfIntegration.WindsorServiceHostFactory, Castle.Facilities.WcfIntegration" %>
Where the value of attribute Service must match either the id of our service in Castle configuration file or the service type itself.
Are we missing anything? We haven't created the Windsor Container yet, have we?. Like I said before in II6.0 environments ServiceHosts are created by http request, but would it be wise to apply the same approach for creating the WindsorContainer? I don't think so! Don't panic though, WCF facility has already covered that. Since we are in a web environment, we can use the Global.asax Application_Start event to create our Windsor Container and then register it through an available method in the custom ServiceHostFactory.
    public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
WindsorContainer container = new WindsorContainer("Objects.xml");
WindsorServiceHostFactory.RegisterContainer(container.Kernel);
}
}
We are done! What's next then? One of the things that I pointed out in the first post of this series is that no AOP features can be applied upon objects that are not handled by the DI container... That's no longer a problem for us!
In the next post of these series I'll show how we can use castle interceptors to apply cross cutting concerns upon service objects.

kick it on DotNetKicks.com

Thursday, May 1, 2008

Dependency Injection in WCF Services

To use Dependency Injection in a distributed service layer is not a trivial task. Either if you use Web Services or WCF, your services are created by the .NET engine, so somehow you need to find a way to inject your Dependency Injection Container in there.

You might as well let the engine create your service and then use the Service Locator pattern to hook up the underlying layer.
In the following code snippet we use Castle container as a Service Locator to retrieve the Data Access Layer instance that is used from our WCF service.
    public class CustomerService:ICustomerService
{
#region ICustomerService Members
public Customer GetCustomer(long id)
{
ICustomerDataAccess da;
da = Global.Container.Resolve<ICustomerDataAccess>();
return da.GetCustomer(id);
}

#endregion
}
In the above example, you'll notice that apart from using a slightly different pattern for creating the Data Access object, the service instantiation is not handled by our DI container and this has some bad implications. Some DI containers, such as Castle or Spring.NET, offer AOP features but those features can only be applied upon objects instantiated by the container. So the bottom line is that in this scenario we can't use those AOP frameworks upon our service objects.

So for some scenarios Service Locator pattern could be just alright, but what if we still want to go for a pure Dependency Injection pattern in our service layer? How can we get around the service creation problem?

If you are using Web Services I'm afraid you don't have many options. Comparing to WCF, Web services is not a very configurable technology and the only way to intercept requests is to replace the ASP.NET default HttpHandler with a custom one, which handles the requests/responses and the service object creation. Good news are that if you are using Spring.NET, you don't need to create the handler yourself; there is a custom HttpHandler implementation in the framework that you can use for that purpose.

If you are using WCF in your service layer, congratulations :) WCF is a highly configurable technology and in fact it provides AOP features through the injection of custom behaviors. Using this extensibility Oran gives us the solution to our problem here. As you can read in that post, for creating new service instances WCF uses a factory, which implements IInstanceProvider ... Great news are that we can create a custom behavior that replaces the default IInstanceProvider factory implementation with our own implementation, and in there we can hook up our DI Container.
To cut a long story short, Oran creates an IInstanceProvider implementation that uses Spring.NET container for service objects creation.

If you are not using Spring.NET, don't panic :) there are also implementations available for Castle (created by Ayende) and for ObjectBuilder (created by Pablo M. Cibraro) that follow similar approaches than Oran's. Even if you are using Spring.NET, you might as well use Stan's ammendments to Oran's solution.

To sum up, in this post we have explored some different options to implement Dependency Injection in our Service Layer depending on the distributed technology (WebServices and WCF) and on the DI container (Spring.NET, Castle..) used.

In the next post of these series, I'll put these concepts in practice using the WCF Dependency Injection Castle facility.

kick it on DotNetKicks.com