Homam's Mind

Friday, May 29, 2009

Service Provider Pattern Part II

Read the first part

At first I found it is generally a good advice to store the configuration in a static, read-only property somewhere. And there's no better place other than the configuraiton class itself:
static MyServicesConfigurationSection _Value;
public static MyServicesConfigurationSection GetValue()
{
if (_Value == null)
{
_Value = (MyServicesConfigurationSection)
System.Configuration.ConfigurationManager.GetSection("myServices");
}
return _Value;
}

Here we assume that we always define the matching element to be "myServices" in the configuration file. It makes sense because it makes it easier for us to find the element in different configuration files. We can always access the value using:
var config = Configuration.MyServicesConfigurationSection.GetValue();

Modularizing is the obvious upgrade we are goging to make to the Service Provider Pattern Part I. I can find three distinct components:

Service-Provider-Pattern-Ar 

  • Service Provider Pattern contains all the logic required by the pattern to work. You alway reference it everywhere you want to use the pattern.

  • Service Definitions is where we define our services.

  • Implementation of the Services contains  concrete classes and implementations of (some of) the services that have been defined in Service Definitions module. In a real application you may end up with many Implementation components each containing the implementation of a one or few number of services.


As before the configuration file of the Host Application maps the definitions (abstract services) to implementations (concrete services).

It's clear that using this architecture we can have host applications that are hosting different implementations of the services.

Configuring the Services


Till now the only purpose of the configuration file was to store the mapping between the definitions and the implementations. But we can use it in order to actually configure the services. For an example it's very likely that the FTPFileStorageService that we defined in the previous part, needs a FTP account credential to work. In this case the <add> element (that maps FileStorageService to FTPFileStorageService) may look like:
<add def="MyServiceDefinitions.FileStorageService"
impl="MyServiceImplementations.FTPFileStorageService,
MyServiceImplementations
"
host="ftp://ftp.wingooli.com" username="wingooloi"
password="password" />

Both the abstract service definition and the concrete implementation can implement IServiceBase interface:
public interface IServiceBase
{
void Initialize(Configuration.ServiceProviderSettings settings);
}

This interface just has one method, Initialize, that takes a ServiceProviderSettings (the <add> element). We can read the additional attributes of the <add> element using a code like this:
settings.Properties["host"]

The logics in the Service Provider Pattern component automatically call the Initialize method if this interface has been implemented in the definition the  implementation of the service.

Here is the design:

Service-Provider-Pattern

Now our Service Provider Pattern has nothing less than ASP.NET Provider Pattern but it is easier to implement.

Using all these modules we can reduce the code needed to instantiate a service (this code snippet should be placed in the abstract service definition class):
static FileStorageService _Instance;
static object _InstanceLocker = new object();
public static FileStorageService Instance
{
get {
if (_Instance == null) {
lock (_InstanceLocker) {
_Instance = ServiceModel.ServicesHelper
.GetServiceInterface<FileStorageService>();
}
}
return _Instance;
}
}

Because it is a repeatable pattern and to make it all more developer friendly, I created a C# code snippet that generates a similar code automatically.

You can download the whole things here.
Monday, May 25, 2009

JQuery Auto Ellipsis Plugin

It is one of my most favorite JQuery plugins I coded for Dig and Win. As Dig and Win is a AJAX game, we have developed many JavaScript snippets including JQuery plugins and controls and behaviors for Microsoft AJAX Framework. And I had much fun working on JavaScript, honestly I didn't know how powerful and how interesting this language is before working on the Dig and Win game. Check out Auto Ellipsis in my homepage or its JQuery page.
Wednesday, May 20, 2009

Service Provider Pattern, Part I

Read the Second and final part

Hyzonia is made of dozens of services running in many machines and app domains all over the internet. One problem we faced early in designing Hyzonia was the need to have different implementations for the a service and the ability to switch between the implementation as the need arises in the run time.

ASP.NET has already had a well-established Provider Pattern. But soon it turns out that it is not the best solution in our case. It seems ASP.NET Provider Pattern is not that developer friendly especially when you have dozens and increasing number of service definitions; because you have to code a new configuration class, create an abstract class, its implementation and a static helper class and it means you have to write the same methods in at least three places.

I wanted to let our developers to be able to add new services very fast. Here is a description of the provider pattern I came with.

Here I assume that services are stateless singleton objects, that is a true assumption in the context of Hyzonia and most of service oriented applications. That's also true about ASP.NET providers. The main reason lies in the SOA paradigm, as in service oriented architecture we think of an operation as something that when it is given its required input arguments it does all the job and returns a success or a failure message. When a client calls an operation it passed all the job to the service and basically it disconnects and waits until the operation returns. The operations that perform an a business object should perform a meaningful business process. It means that those operations must transfer a business object to consistent state.

It is guaranteed that by obeying such those rules you will have a clear separation between your service/business logic and the clients (that are the users of the services).

How to


For adding a new service you need to create the service definition that is an abstract class. Here as a rule we store the service definitions in a seperate assembly that could be shared among many app domains. For our pattern to work we need to add a static getter member to the abstract definitions, just like what you may do for creating a singleton object. Let's name it Instance, that is a getter-only property of the type of the abstract class itself. It's obvious that we are going to load, instantiate and return the concrete implementation here. Let's talk about it a bit later.

For an example, suppose that we are building a File Storage Service. There's no doubt that the main functionalists of such this service are Storing and Deleting the files. So here is the service definition:
public abstract class FileStorageService {
public static FileStorageService Instance {
get { // I told you, we talk about it later }
}
public abstract string Store(Byte[] bytes, string extension);
public abstract bool Delete(string url);
}

Suppose we have a FTP implementation the service: FTPFileStorageService:
public class FTPFileStorageService : FileStorageService {
//...
}

Now if we want to instantiate the FTPFileStorageSerivce in a host application, we need to modify the configuration file of the host app in a way to relate the service definition to our desired implementation. Here is the way we do it:
<service def="FileStorageService" impl="FTPFileStorageService"/>

Now let's back to where we left our discussion about the static Instance property in the service definition class. We need to somehow read the configuration file, find the active implementation, instantiate and return it here. Here is the code:
static FileStorageService _Instance;
public static FileStorageService Instance {
get {
if (_Instance == null)
{
var name = (typeof(FileStorageService)).FullName;

var myAppConfiguration =
(MyApp.Configuration.MyAppServiceConfigurationSection)
System.Configuration.ConfigurationManager
.GetSection("myAppConfig");

var services = myAppConfiguration.Services;

ServiceProviderSettings config = null;

foreach (var s in services)
{
var serviceConfig = (ServiceProviderSettings)s;
if (serviceConfig.Definition == name)
{
config = serviceConfig;
break;
}
}

if (config == null)
throw new Exception(@"A service mapping is
missed in the configuration file");

var type = Type.GetType(config.Implementation);
_Instance = (FileStorageService)Activator.CreateInstance(type);
}
return _Instance;
}
}

You may want to download a demo project here.

If you're new to .NET configuration you'll find the download a good demonstration for starting working with custom configuration classes.

In the second and the final part of this discussion you'll see how we convert a good idea to a working one. The most obvious issue with the code above is here
System.Configuration.ConfigurationManager.GetSection("myAppConfig")

where we are coupling the abstract class (the service definition) and the configuration of the host application. I'm advocating the idea that service definitions must be and are in nature independent of their host.

I will talk about such these issues and making the whole thing more developer friendly in the next part. We will also add more features and try to make it really like a pattern.

Read the Second and final part
Sunday, May 10, 2009

JQuery Wingooli Photo Gallery

I just want to introduce a JQuery photo gallery plugin I developed fro my profile. My main motivation for building this plugin was that I wanted it to be search engine friendly therefore I needed a clear separation between the photo gallery functionalists and the data describing the photos and the gallery. It is something that is easy to achieve using JQuery.

BTW these days I spend a part of my time discussing and teaching OOP JavaScript to our fellow programmers in RENA. It's interesting for me to discuss the somewhat weird features of JavaScript for these guys who are already well experiencedand talented .NET developers. I try my best to convince them JavaScript is so fun when you get used to it, so fun and so powerful that you end up you want to kiss all the ASP.NET AJAX and UI functionalists a goodbye and develop the effects yourself and see how much you can improve the performance and the branding of your application.

We in RENA are looking for a Web UI Developer to handle such those tasks, it came out to be a very hard job finding a person for this position, mainly because it requires you to be a JavaScript God! to pass the first step in the recruitment process. Drop us a message if you fit the position.
Monday, May 4, 2009

They kill people like us

I just wanted to share and save this article: They kill people like us, says gay Iraqi. This is exactly what life is for gays living in the middle east.

One evidence that make me think this situation would not be eased by years, is where Moyad says something like "my future is in the hand of God". As long as middle eastern gays think there's a God who has control over their life, the shall see no optimism for the future. All these troubles have been caused by the name of God and will be easily resolved if people simply loose their faith in God. I believe the first groups who should start thinking twice when they hear the word God are the ones who have suffered because of the belief in God in general and particularly sexual minorities.
Friday, May 1, 2009

Award for Best Website Developed on Microsoft Technology

DSC_0185

Hmm, Thanks for these awards I have cool subjects to post.

It’s a few days I’m receiving e-mails from a girl, saying we both were going to the same kindergarten :-) My mom was working there. I enjoyed the conversation so far, it’s interesting to find a person who seems to know you after years, whilst you remember nothing at all.

I had time to watch some shows of American Idol today, comparing to the last year I totally missed it, and not surprisingly I found myself a fan of Adam.

I am getting worried about the path the business people are taking in our company, in many ways I am completely in disagreement with them. This week I have to concentrate to bring some changes to the company business. Actually I started by changing the layout (physical!) of my department; we changed the position of tables, we bought a whiteboard and for the first time I have a well-defined schedule covering all the days till the end of the week. But still I have to force the business to take a look at the state and the way they are taking from an outsider perspective. For me it’s very wrong, I have to fix it.