Introduction:

Windows Communication Foundation (WCF) is a communication frame work for building service-oriented applications. With WCF, data can be sent from one service endpoint to other. The data sent can be a single character or word sent as XML or a stream of binary data.

Creating and Consuming a Sample WCF Service:
There are three main steps involved in creating and using the WCF services.

  • To create a wcf Service.(Creating)
  • Bind an address to the service and host the Service. (Hosting)
  • Use the Service.(Consuming)

Step 1: Create a wcf service

In WCF, all the services are exposed as contracts. A contract is a neutral and standard way of describing what the service does. Mainly there are four types of contracts:

  • Service Contract
    This contract describes all the available operations that a client can perform on the service.
  • Data Contract
    This contract defines which data types that are passed to and from the service.
  • Fault Contract
    This contract describes about the error raised by the services and how the service propagates errors to its clients.
  • Message Contracts
    This contract provides the direct control over the SOAP message structure. This is useful in inter-operability cases and also when there is an existing message format you have to comply with.

Step 2: Binding and Hosting
Each service has its own end points. Clients communicate with this end point only. End points describe three things:

  • Address
  • Binding type
  • Contract Name (defined in STEP 1)

Every service should be associated with a unique address. Address mainly contain the following two key factors:

  • Transport protocol that is used to communicate between the client proxy and service.
  • Location of the service.
    Location of the service describe the targeted machine path (where service is hosted) and an optional port name.

Hosting:
Every service must be hosted in a host process. Hosting can be done by using:

  • IIS
  • Windows Activation Service (WAS)
  • Self hosting

IIS Hosting
IIS hosting is the same as hosting the traditional web service hosting. It can be done by creating a virtual directory and supplying a .svc file.

Hosting with Windows Activation Service (WAS)
WAS is part of IIS 7.0. It comes with VISTA OS. The hosting with Windows Activation Service is same as hosting with IIS. The only difference between these two is that IIS supports for HTTP bindings only. Whereas WAS supports for all transport schemas.

Self Hosting
In this technique the developer is responsible for providing and managing the life cycle of host process. In this the host service must be running before the client call the service. To host this service we use the .NET class ServiceHost. We have to create an instance of ServiceHost. Constructors of this class take two parameters: service type, base address. (Base address can be empty set.)

Add the Service End points to the host:
We will use the AddServiceEndpoint() method to add an end point to the host. The end point contains three things: type of service, type of binding and service Name. So, AddServiceEndpoint() method accepts these three required parameters.

Consuming by creating the channel factory:
We can consume this service by creating the channel factory manually. While creating the channel, we will have to provide the same binding type and end point address where the service is hosted.

Best Practices to create a wcf service:

General Guidelines

  • The services should be very much secure.
  • Services should be accessed by concurrent clients.
  • The services should be robust and reliable.
  • The services should be responsive and disciplined.

Essentials:

  • The service code should not be places in any hosting EXE. Instead it should be placed in a class library.
  • The provided constructors should not be parameterized.
  • The namespaces provided to the contracts should be meaningful.
  • Self hosting should be preferred over IIS hosting for intranet applications.
  • WAS hosting should be preferred over Self hosting on Windows Vista and Windows Server 2008.
  • All the end-points should be named in the config file.
  • The proxy should be cleaned up while using a tool such as Visual Studio 2008.
  • The proxy should be factored to a separate class library, if two or more clients are using the same contract.
  • The proxy should always be closed or disposed.

Service Contracts:

  • ServiceContractAttribute should always be applied on an interface, not on a class.
  • The service contract name should always be prefixed by I.
  • Property-like operations should always be avoided.
  • Contracts having only one member should also be avoided.
  • Three to five members should be tried to have in a service contract.
  • Do not have more than twenty members per service contract.

Data Contracts:

  • DataContract attribute should always be applied on Data Contracts.
  • DataMemberAttribute should be used on properties or read-only public members only.
  • Explicit XML serialization should be avoided.
  • All the members coming from the same level in the class hierarchy should be assigned the same value when using the Order property.
  • Delegates and events should not be marked as data members.
  • ADO.net DataSet and DataTables should not be accepted or returned from operations.
  • A neutral representation such as an array should be returned instead.
  • Data Contract should be shared across projects wherever possible.

Operations And Calls:

  • One way calls should not be treated as asynchronous or concurrent calls.
  • Exceptions should always be expected out of a one way operation.
  • Reliability should be enabled even on one way calls. Use of ordered delivery is optional.
  • One way operations should be avoided on a sessionful contract or it should be used as a terminating operation.
  • Callback Contract on the service side should be named after the service contract suffixed by Callback.
  • Regular callbacks and events should not be mixed on the same callback contract.
  • Event operations should be designed with return type as void and no out parameters.

Transactions:

  • One way calls should not be treated as asynchronous or concurrent calls.
  • Exceptions should always be expected out of a one way operation.
  • Reliability should be enabled even on one way calls. Use of ordered delivery is optional.
  • One way operations should be avoided on a sessionful contract or it should be used as a terminating operation.
  • Callback Contract on the service side should be named after the service contract suffixed by Callback.
  • Regular callbacks and events should not be mixed on the same callback contract.
  • Event operations should be designed with return type as void and no out parameters.

Security:

  • IDesign’s security framework should be used and manual configuration should be avoided for security purposes.
  • PrincipalPermissionAttribute should never be applied directly on service class.
  • Work requiring authorization at service constructor should be avoided.
  • Role based security should not be relied upon in the client’s callback operations.
  • Transport security should be used for Intranet clients and Message security should be used for Internet clients.
  • Clients should be allowed to negotiate the service certification.

Some of the guidelines listed above can safely be ignored when applying special circumstances. But make sure you fully understand about serialization, deserialization, and schema mechanisms involved before you deviate from the guidelines.

Further Reading:

http://msdn.microsoft.com/en-us/netframework/aa663324

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

http://wcftutorial.net/

http://en.wikipedia.org/wiki/Service-oriented_architecture

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

http://www.service-architecture.com/

http://www.webopedia.com/TERM/S/Service_Oriented_Architecture.html

http://www.javaworld.com/javaworld/jw-06-2005/jw-0613-soa.html

http://www.youtube.com/watch?v=sbd_1G8Kqjs

http://www.soapatterns.org/

http://www.cio.com/topic/3016/Service_Oriented_Architecture_SOA

http://looselycoupled.com/glossary/SOA

Are you not able to enhance a product easily because the design is not allowing you to do?

Are you not able to integrate new interfaces/services?

Are you not able to connect to multiple databases?

Above are some typical problems that come during maintenance of existing applications to incorporate new business requirement. These are also some common requirements while defining scalable framework for new application and products so that future changes can be incorporated with minimal design changes. To address above concerns there are industry proven pattern available which is named as “Inversion of Control (IoC)” or “Dependency Injection Pattern (DI)” by Martin Fowler or  “Unity Application Block” in Enterprise Library 4.1 by Microsoft.

The purpose of this pattern is to reduce coupling between software components and build loosely coupled applications. It provides a way to handle dependencies between objects. Traditional approach was to hard-code objects and their dependencies. For instances application can hard-code single/multiple database driver which would enable it to connect to a particular database but what if business requirement changes to connect to different family of database. This would require changes to existing code to connect to new database which can introduce more defects into code and above all there will be two pieces of code which need to be modified for any changes in the way application interacts with database.

This pattern offers a solution to this problem, Instead of hard-coding the dependencies, a component/object just lists the necessary services in configuration files (In our case database drivers and Unity Framework or DI framework will provide (create, initialize and setup) these services (database drivers) to objects or software components at runtime. These services can be changed or modified later based on business requirements which makes code scalable and maintainable in future.

Benefits of above pattern is to reduce common code to create, initialize and setup dependencies or objects, this is handled automatically by pattern framework using configuration files. Configuration files also provides flexibility to incorporate alternate implementations or a given service/component or object. This is also useful during unit testing as it is easy to inject fake implementations of a service (If actual services are paid or inaccessible from development environment) into objects being tested by changing configuration files.

References:-

http://martinfowler.com/articles/injection.html

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

How to configure OpenLDAP
Posted on December 29, 2010

Softwares Used:

openLDAP (Windows edition)

LDAP Browsers(Jxplorer, LDAPsoft admin tools, Softerra LDAP admin etc)

Download Softwares:

1. You can download openLDAP windows edition from the following location:

http://www.userbooster.de/en/download/openldap-for-windows.aspx

2. you can download browsers from the locations given below:

Softerra LDAP admin: http://www.ldapadministrator.com/download.htm

LDAPsoft admin tool: http://ldapadmin.sourceforge.net/download/ldapadmin.html

JXPLORER: http://jxplorer.org/

Installing openLDAP:

1. Follow the instructions and choose your host as “localhost” or an “IP address”

2. Choose the port and SSL-port as you may want to use or can let it by default to 389 and 636 respectively.

3. Select a database for directory you want to use: BDB or LDAP (we have used BDB i.e berkely’s DB)

4. NEXT -> choose a password for your root directory, by default it would be “secret”

5. NEXT-> install-> Finish.

Using an LDAP Browser:

Note: Any of the Browsers except JXPLORER because it causes problem on updating everytime. We are not able to fix it at our end, may be you are lucky :) For this blog, we have used “LDAPsoft LDAP admin”

1. Start the server using command: “slapd –d 1″ from the directory where OpenLDAP is installed

2. Install LDAPsoft LDAP admin

3. Open “LDAPsoft LDAP admin” and create new connection to LDAP.

4. Specify the connection name - it could be any friendly name you may want to use

5. Specify the Hostname as “localhost” or “IP Address” as set at the time of installing OpenLDAP

6. Specify the port you are using for LDAP

7. Choose the version of LDAP (in Protocol drop-down) you are using as “LDAP v3″

8. Specify the Base DN as “dc=maxcrc,dc=com” or you may choose to click on “Fetch Base DNs” button to automatically fetch the Base DNs

9. You may want to test the connection by clicking on “Test Connection” button

10. Got to NEXT and select “Simple Authentication” method. For this, you will be needed to provide Bind DN and Password which would be “cn=Manager, dc=maxcrc, dc=com” and “secret” respectively. The Bind DN can also be populated by clicking on the button, which is on the right hand side of the Bind DN text field.

12. NEXT->Finish.

Now you have a complete connection with  openLDAP and you can create your own OUs and CNs .

Open Source CMS Systems
Posted on September 22, 2009

Open source CMS systems are the CMS systems that are available with complete source code and can be customized to fit the needs of your business.

Parameters to identify you need a CMS:-

• You need to change the content regularly
• You need to manually update the content
• There are multiple users managing the content
• A lot of time is spent in content update
• You have multiple versions of the same content
• You have multi-lingual content
• Same content is available at multiple locations and is inconsistent

Benefits of Open Source CMS

No upfront cost and cheaper to implement – You do not need to pay any licensing cost which can be heavy sometimes. You might need to get a few customizations done based on requirement and would need to pay a development team for that.

Complete flexibility of development and customization – You can customize the CMS based on your requirements and tweak the code/design as your need.

Easy to find development teams and users worldwide– There are a lot of software service vendors available who specialize in open source CMS development.

Features/extensions available- You can find a lot of features developed over the CMS and available for free or for some nominal fee.

Ease of use: - You can get the CMS customized to be used in the way you would like to use it.

Drawbacks of Open Source CMS

No direct support – There is no support available, you would need to depend on your technical team.

Dependence on IT team – You would need to be more dependent on an IT team.

Security Risks – As the code is available to everyone there are security holes that hackers can misuse.

Documentation - Open source systems are not very well documented.

Algoworks believes in Open source CMS development and specializes in implementation, customization, support and migration from existing systems to Alfresco, Joomla, Drupal, Typo3, DNN CMS systems.

Extension less URL Rewriting

Extensionless URL’s are more user and search engine friendly. Overall, you can make your website URL’s more meaningful and less difficult to remember.

Development steps:-

1.       We need to add a third party URL rewriter assembly. Many such assemblies are available. I used URL Rewriter assembly “Intelligencia.UrlRewriter”. This assembly would change all your URL’s, you just need to let the system know what URL’s to use through web.config.

 

2.      For IIS 7 you might need to make changes in applicationhost config file to permit IIS applications to use handlers and modules. Please check to make sure following sections have “allow” permissions. Application host file is located at c:/windows/system32/inetsrv/config/ applicationHost.config

<section name=”globalModules” allowDefinition=”AppHostOnly” overrideModeDefault=”Allow” />

<section name=”modules” allowDefinition=”MachineToApplication” overrideModeDefault=”Allow” />

<section name=”handlers” overrideModeDefault=”Allow” />

 

3.      Add configurations as mentioned below in your web.config.

<configuration>

  <configSections>

    <section name=”rewriter” requirePermission=”false”

       type=”Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter” />

  </configSections>

 

  <system.web>  

    <httpModules>

      <add name=”UrlRewriter” type=”Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter” /> // Assembly name of the URL rewriter assembly

    </httpModules>   

  </system.web>

 

  <system.webServer>

    <modules runAllManagedModulesForAllRequests=”true”>

      <add name=”UrlRewriter” type=”Intelligencia.UrlRewriter.RewriterHttpModule” />

    </modules>

 

    <validation validateIntegratedModeConfiguration=”false” />

  </system.webServer>

 

 

 4) Use following URL rewrites. In below mentioned URL your URL will be http://www.xyz.com/myprofile and your application url would be “http://www.xyz.com/Profile.aspx”

<rewriter>

   // This is the place where we write our rewriting rule like

 <rewrite url=”~/MyProfile$” to=”~/Profile.aspx” ignoreCase=”true” />

  </rewriter>

I only recently became aware of another breaking change in ASP.NET 2.0: In order to optimize session state management, some changes have been implemented. One of the most puzzling ones when you’re not aware of it can be reproduced as follows:
  • In ASP.NET 1.1, create a new web application.
  • Add a label to the page, name it lblSessionID.


  • In the code behind, add the following code in the “Page_Load” method:
protected void Page_Load(object, sender, EventArgs e)
{
lblSessionID.Text = this.Session.SessionID;
}


  • Load the page in the web browser. Press F5 as many times as you like, and the SessionID remains the same.
This behaviour is expected, and my guess is that quite a few applications rely on the SessionID being consistent on every page refresh.
However, in ASP.NET 2.0, the behaviour is different, which may cause applications to break: If you create a new website (or a new web application) and reproduce all the steps above, the SessionID will be different on every refresh of the page. The reason is found in MSDN:
“When using cookie-based session state, ASP.NET does not allocate storage for session data until the Session object is used. As a result, a new session ID is generated for each page request until the session object is accessed. If your application requires a static session ID for the entire session, you can either implement the Session_Start method in the application’s Global.asax file and store data in the Session object to fix the session ID, or you can use code in another part of your application to explicitly store data in the Session object.”
Since cookie-based session state is the default, this change of behaviour will affect existing web applications relying on the SessionID to identify the current user without having previously stored data in the Session object.
Here is a possible fix:
protected void Page_Load(object, sender, EventArgs e){
if( this.Session["dummy"] == null)
{
this.Session["dummy"] = 1;
}
lblSessionID.Text = this.Session.SessionID;
}
Not very elegant, and I can’t say that I totally understand the reason why the ASP.NET team doesn’t offer a better way to keep the SessionID consistent all the time, even when nothing is stored in the Session object. Anyway, this has caused me a few headaches, so hopefully this article will help other developers.

Data Architecture for SaaS applications:-

SaaS applications are frequently required to have a secured data structure per client in addition to the database being robust. Thus, a SaaS application data structure varies from being a single database to a multi database solution. Broadly, there can be four approaches to designing database based on the requirements.

  • One database per client and a master database for the application holding general details e.g. Clients information.
  • Single database for all the clients with separate tables for clients.
  • Single database for all the clients with shared tables.
  • A multi-database solution with a few clients sharing the database based on data load and security factors.

Solutions for creating SaaS data architecture:-

Data can be stored in a single database for all the clients or it can be stored in a different database per client. Other options are a transition state, the transition between multi database and single database is fuzzy. The data can be stored in multiple transition states as described below depending on the volume, security and load factors

Above two pictures depict how the transition happens. So, the data can be stored in “separate DB”, “Separate Schema”, “Shared schema” (One database) or Multiple shared database.

Separate Databases

Storing tenant data in separate databases is simple. Along with this if needed, you can create a master application database holding client details with the database name (assigned dynamically on client creation) for each client.

Shared Database, Separate Schemas

Another approach involves creating separate tables in the same database for each clients.

Shared Database, Shared Schema

Third approach involves using the same database and the same set of tables to host multiple tenants’ data. A given table can include records from multiple tenants stored in any order; a Tenant ID column associates every record with the appropriate tenant.

Conditional DB sharing

Other approach involves using the same database or multiple database to host multiple tenants’ data. A given database can include records from multiple tenants or from single tenant depending on the requirements.

How this works:-
If client needs more security then we can house his data in separate DB.
Clients who do not have very critical data and have less load can be housed in single database.
This approach helps you enjoy the benefits of not increasing the unnecessary load on server with separating clients/data into single/multiple databases.

Ref :- http://msdn.microsoft.com/en-us/library/aa479086.aspx

Events and Delegates
Posted on December 15, 2008

Events and Delegates
Events

An Event is a message sent by an object that tells us that some action has been performed. This action can be any thing. It may be cause by some user interaction, Mouse click, button Click, or it could be triggered by some Programming Funda or logic.

The Object that raises the event or in other words triggers the event is termed as event Sender. While on the other hand any object that captures the event and look after it is termed as event receiver.

During the entire communication, event sender class is not aware of the fact that which event, he is going to handle or receive.

So to put it in a more effective way, we need a mechanism may be a Pointer Like mechanism between the source and the receiver.

Then comes the Concept of Delegates…
To overcome from this Problem .NET Framework Provides a special type called Delegates that works as a function Pointer.

A Delegate is basically a class that holds a reference to a method. Unlike the other class Delegate has a signature. Beauty of this concept is that it will hold reference of only that method that matches its signature. So basically a Delegate is equivalent to type safe function pointer or a call back.
Declaration of Methods and Delegates.
Public delegate void RingEventHandler(object sender,RingEventsArgs e)
Here
RingEventHandler is the delegate for the ring event.
RingEventArgs is a class that holds data for ring event.

Moving further,A Delegate can be of two types.
->Single cast Delegate.
-> Multi cast Delegate.

A single cast Delegate can call only one function. while a Multi cast Delegate is one that can be a part of a Linked list.Multi cast Delegates Points to the head of such a linked list.

The following diagram will show the mechanism that how Events and Delegates work …
<img src=”E:\Documents and Settings\algoworks\My Documents\My Pictures\events.gif”  alt=”Events and Delegates” />

Reflection in C#
Posted on December 15, 2008

Reflection always plays a greater role during the development of large applications. It is one of the most important features of .Net Framework. It’s a powerful and efficient way of collecting and manipulating information present in application’s assemblies and its metadata.

Metadata is basically defined as data about data.
When Reflection is used along with System.type namespace, it allows developers to gather information about Assemblies and all other types that has been used.

Definition of Reflection:

Reflection is the ability to find out information about objects, the application details(assemblies) and its metadata at run time .
Reflection allows application to collect information about itself and also manipulation of information on itself. This includes information regarding methods, types, properties and events of object. With Reflection We can create instance of type, bind the type to an existing object and invoke its methods or access its fields.

Using Reflection:

System. Reflection namespace contains all the Reflection related classes. These classes are used to get information from any other classes lying under .Net Framework. These are the root of all Reflection classes. Type is an abstract base class that acts as means to access metadata through the reflection classes.
Reflection Provides Objects that encapsulates assemblies, modules and types. If we are using any attributes in our Program then Reflection enables you to access all of them.
Example of Reflection
Int i=10;
System. type type=i.GetType();
System.Console.Writeline(type);

Output is system.Int32.
So why Reflection ???
1) If you need to access attributes in Your Programs Metadata.
2) For Building new types at run time.
3) For performing late binding, Accessing methods on type created at run time.

Session Vs Cookie in ASP.NET
Posted on December 15, 2008

Session Vs Cookies in Asp.Net

Web forms pages are HTTP (Hyper Text Transfer Protocol) based, They are stateless which means they are not aware of the fact that whether request are coming from the same client, and pages are created and destroyed recreated with each round trip to the server, therefore information will be lost, therefore state management is really an issue in developing web applications.
Problems Related to this one can be solved using client side management and Server side management.

Client Side Management
In this case there is no information maintained on server during round trip. Information will be stored in the page or on client’s computer. Client management is done using Cookies, Hidden Fields, and View state and query strings.

Server Side Management

In this case information will be stored on server side, It has higher security but it may use more web server resources. Server management is done using Application Object and Session Objects.

Cookies

Cookie is small amount of Data stored either in a Text File on the client file system or in memory in the client browser Session. Cookies are mainly used for tracking Data Settings.

Sessions
Session Object can be used for storing Session specific information that needs to be maintained between server round trips and between requests for pages. Session is per client basis that is different client object have different session Object. The ideal Data that we should store in a Session is that it should be Short lived, sensitive data and specific to and individual session.

Each Active ASP.NET session is identified and tracked using a 120 bit session string containing URL-Legal ASCII Characters. Session Id are generated using an algorithm that guarantees that each Session ID is unique and it will not Collide. and beauty is such that its hard to predict the session Id of Existing Session. Session ID are basically communicated through client server request either by HTTP Cookies or a modified URL.

Each web Application must have a Configuration file named web.config.Its an XML File.
For Example…
<sessionState mode=”InProc” stateConnectionString=”tcpip=127.0.0.1:42424″ sqlConnectionString =”data source=127.0.0.1; user id=sa; password=” cookieless=”false” timeout=”20″ />
Cookie less Option can be True or can be False..
If it is False (Default Value) ->ASP.Net will use HTTP Cookies to identify user.
If it is true->ASP.Net will randomly generate a unique number and will put it ahead of the address bar.

For Example
http://localhost/Management/(1234Xysdr)/Default.aspx

For storing/Retrieving Information using Session Object.

Session [“myName”]=”nitish”->for storing
myName=Session[“myName”]->for Retrieving.

Session Vs Cookies

The advantages of using Session variables over cookie…

1) We can store Objects such as an array, or Dictionary objects. Since session variable are stored on web server’s memory, storing large objects in a user session on a site with many users can lead to reduced memory on the server.
2) Can be accessed on Any Web browser.

To sum up…
1) Use Cookies for small Non Critical Data.
2) Use Sessions on a user to user basis.
3) Use Application variable for site wide information that does not require Constant revision.