Friday, July 10, 2009

Strategy Pattern

Definition:

The Gang of Four defines the Strategy in the following way,
"Define a family of algorithms, encapsulate each one,
and make them interchangeable.
Strategy lets the algorithm vary independently from clients that use it. "

Many developers who are new to design patterns will definitely get confused with this definition. Well, I will provide a simple explanation for this definition with an example.

Scenario

Let us assume a simple scenario that we have different classes for different kind of employees, Say, SoftwareEmployee, SalesEmployee and AccountingEmployee.  Now, all these classes needs have to implement SalaryRange which is a common method for all.  However, different employee type may have different salary schemes.  So implementing the SalaryRange is especially independent to the particular Employee type.

Solution

Overview of Strategy

In order to define the SalaryRange method in all the classes(SoftwareEmployee, SalesEmployee and AccountingEmployee), we define a interface with a method called SalaryRange which returns only string as follows(I made a simple implementation for demonstration purpose),

public interface IEmployee 

    string SalaryRange(); 
}

Now, let us implement this interface for all the employee types as follow,

public class SalesEmployee : IEmployee
    {
        string IEmployee.SalaryRange()
        {
            return "Depends on the target achieved";
        }

        //Some other members related to Sales person such as Area of Marketing,

//Product information, Sales Target

     }

    public class AccountingEmployee : IEmployee
    {
        string IEmployee.SalaryRange()
        {
            return "2000 - 8000";
        }

        //Some other members related to Accountants such as Method of Accounting

        //(manual or automated) etc. 
  }

Now each method(SalaryRange) is independent of it's own class.  So it has encapsulated its behavior with in the particular class that it belongs to.

The next goal is to create a concrete class that can communicate with all the Employee Types. Let us assume we have the class named as, SalaryRange with a method in the called SalaryRange as follows,

All we need to have in the SalaryRange class is to define a variable of type IEmployee.

IEmployee empType;
public SalaryRange()
        {
            //No implementation or provide default EmpType as
            this.EmpType = new SoftwareEmployee();
        }

        public SalaryRange(IEmployee empType)
        {
            this.EmpType = empType;
        }

        public IEmployee EmpType
        {
            set
            {
                empType = value;
            }
            get
            {
                return empType;
            }
        }


1. In this simple code we have a default constructor which will be called when the client wont send any type.
2. An Overloaded constructor which takes a single parameter of the type IEmployee.
3. Finally we define a Property to pass the value for IEmployee type.

The way we call the original method will be from the method getSalaryRange() defined in the SalaryRange class.

public string getSalaryRange()
        {
            if (empType != null)
                return empType.SalaryRange();
            else
                return "Employee type not specified..";
        }
This is a simple method which delegates it's call to the particular employee type dynamically.

We have now defined a Strategy which is an Interface called as IEmployee,
the ConcreteStrategy which are the classes SoftwareEmployee, SalesEmployee and AccountingEmployee.

Now we are going to write a asp.net page which acts as a client. In order to call get the
employee salary range of a particular employee we just need to define an object for the SalaryRange type.

This is the code in the Page Load event of our aspx page,

protected void Page_Load(object sender, EventArgs e)
   {
       SalaryRange softwareSalary = new SalaryRange();
       Response.Write("Software Engineer's Salary Varies " + softwareSalary.getSalaryRange());

       SalaryRange accountantSalary = new SalaryRange();
       accountantSalary.EmpType = new AccountingEmployee();
       Response.Write("<hr/>Accountant's Salary Varies " + accountantSalary.getSalaryRange());

       SalaryRange salesSalary = new SalaryRange(new SalesEmployee());
       Response.Write("<hr/>Sales Person's Salary Varies " + salesSalary.getSalaryRange());

       Response.Write("<hr/>");
   }

For the softwareSalary we are calling the default constructor where our default constructor will takes SoftwareEmployee type as its default.

AccountantSalary is implemented by using the Property.
SalesSalary is implemented by using the parameterized constructor.

In the Response.Write method we are just calling the getSalaryRange() method.  So here our client can call the SalaryRange class's getSalaryRange method as it likes.


kick it on DotNetKicks.com

Wednesday, July 8, 2009

Communicate Among the Databases

In certain cases we occasionally need to communicate between the tables that are in different databases.  In this post I am going to explain how to communicate between the tables that are in different databases and in different servers, with a simple example. Let us consider the below database schema,

                     DBSchema

We have two databases say OurPerson and TheirPerson each database having the table Person(may be different in real time scenarios).

To be simple, let us try to get the names of all the persons from OurPerson database whose ID’s exist in TheirPersons’s Person table.  Here is the simple query to do that.

Query 1:

SELECT P1.Name AS Name FROM  OurPerson.dbo.Person P1 WHERE P1.ID IN(SELECT ID FROM TheirPerson.dbo.Person);

So, in order to get access the tables of the other databases we can just use the complete table information as this,

DatabaseName.User.TableName

and similarly for the columns we use like this

DatabaseName.User.TableName.Column

Accessing the Database From Different Server

The above procedure is fine as long as you have all the databases existing on the same server.  Then what about if the databases are in different servers.  Let us suppose that OurPerson is in Server1 and TheirPerson is in Server2.

Now does the same query as we wrote above will work fine?  Suppose we logged in to Server1 and try to execute with this query,

Query 2:

SELECT P1.Name AS Name FROM  Server1.OurPerson.dbo.Person P1 WHERE P1.ID IN(SELECT ID FROM Server2.TheirPerson.dbo.Person);

The query above is exactly valid query.  But there is no way for the Server1 to pass it’s credentials to Server2, which causes the query to fail.  This is the situation where Linked Server concept come into the picture.  Let us see how to create a Linked Server from Server1 to link Server2.

Creating a Linked Server

You can create the Linked Server from Sql Server with the help of server explorer through the Server Objects as shown in the below figure. 

                             image

Right click on the Server Objects and select the New->Linked Server from the context menu which will open a configuration window. In the general tab you can configure your server details, such as the database name, database provider etc. details.  You should provide the security details in the Security tab, which allows you to enter either trusted or untrusted authentication to connect to your linked server.  After everything is configured just click on OK.  That’s it.  Your linked server is now configured with your server.  Now, you can access the Server2’s databases and its tables from the Server1 as in the Query 2 as,

ServerName.DatabaseName.TableName.ColumnName………

Now, you can do all the insertions, updates and queries etc for Server2 from Server1 itself.  One limitation is that you cannot try to update or insert the columns which are of type XML. Hope Microsoft may support this feature in it’s future releases of Sql Server.  For more information on linked servers please visit http://msdn.microsoft.com/en-us/library/aa213778(SQL.80).aspx. This documentation will provide information about how to configure and drop the linked servers using the system defined stored procedures.


kick it on DotNetKicks.com

Friday, July 3, 2009

Let us Inspire.



Watch the patience of Zebra.  The zebra never lost her confidence.  Watch your self instead of telling..

Quote of the Day:
WARNING: Repeated brain usage may be harmful to others.
--rdude

Wednesday, July 1, 2009

Add a check constraint for your date in Sql Server

 

Generally most of the people will have the requirement to add the dates to the database.  Most of the cases they will have two related dates, as FromDate and ToDate or Begin and End.  However most of the people wont add any constraints to their database even they knows that the First Date is always less than the Second Date. 

CREATE TABLE CheckDates
(
    StartDate DATETIME,
    EndDate DATETIME,

    CONSTRAINT
        cmp_Dates CHECK (StartDate<EndDate)
)

Here I am adding a table level check constraint.  Now the database will verify when ever the user tries to add the Start Date > End Date with out writing any triggers or additionally writing logic in stored procedures or front end application every time we insert.

However, you will face problem if you try to insert the column level constraint by referring to another column in the same table.

CREATE TABLE CheckDates
(
    StartDate DATETIME,
    EndDate DATETIME CONSTRAINT cmp_Dates CHECK (StartDate<EndDate)
)

Writing the script as above will give you the error message “Column CHECK constraint for column 'EndDate' references another column, table 'CheckDates'.”.  Notice the comma in the first script which separates the column after EndDate DATETIME.


kick it on DotNetKicks.com

Friday, June 26, 2009

Difference between Web Services and WCF

Last time when I talked about WCF and told to upgrade from Web Services to WCF, many of my friends asked me about the difference between the Web Services and WCF and why to upgrade. So now this blog entry explain why we need to upgrade from Web Services to WCF.

Reach ability

SOA initiatives using ASMX services and trying to reach out to all the stakeholders on internet using SOAP/http clients was the natural option, where as to connect with employees, internal users or partner’s it would have used TCP IP based .Net Remoting. Thus to serve different user base, one has to use different transport option and each transport needed independent implementation.

Unlike ASMX services which were primarily Http based, WCF Services can be reached using multiple protocols like Http, TCP IP, Named Pipe and MSMQ. Other clients like internet/intranet or partners can use any of the above mentioned preferred channels to hook on to these services without IT having to maintain separate code base to serve different client class.

Interoperability

Large Enterprises having mix of technologies, Interoperability requirements with Non Microsoft clients is one of the common scenarios in any SOA initiatives. With ASMX WS-*, XML Serialization is not standardized and hence it is difficult to achieve true interoperability. With WCF, it generates standard SOAP based XML to be consumed by clients. Additionally by using data contracts and message contracts, information exchange with non Microsoft clients’ become easy and improves interoperability.

Performance

Most often sharpness of underlying technology contributes in meeting performance based business SLAs (e.g. In banking gateway for Money transfer, Number of clients served per second). ASMX services were part of .net framework 2.0, since then with .net 3.5 and 4.0 around, there has been continuous improvements in core .net framework to improve performance.

One of the key reasons WCF performance is better than ASMX services is due to the improved serialization techniques in the .net framework. WCF services provide 25 to 40% improvement in performance over ASMX services and hence become natural preference for high performance application.

Extensibility

If ASMX services were to be delivered to clients, only possible way to host them was on to IIS (Internet Information Server). With WCF services, one can host the services into Windows services, Windows Activation Service (WAS) or IIS. WCF also supports claims based authorization which is more granular than existing mechanisms. With WCF starting from application runtime, security, binding, serialization, channel system to service host everything is extensible.

ASMX with WSE 3.0 supports security and http buffering/caching/sessions but still lacks support for Session management, Concurrency, Security, Reliable messaging, Transaction, Throttling, Exception handling and faults. In applications explicitly using WSE to support some of these features is difficult and cumbersome, where as with WCF WSE is inbuilt.

With .Net 4.0, the argument to migrate becomes even stronger because of the benefit from platform features like CLR enhancements, Improved Garbage collection, Parallel programming, Distributed caching, and improved support for REST, and Workflow Services.

With above benefits making way to WCF migration, one of the ways to solve service migration problem is by overlaying WCF attribute over ASMX attributes. e.g. With ServiceContract() attribute on ASMX Service class, and OperationContract() on service methods/operations and then making appropriate changes in .config file. This wrapper based approach may make asmx services work with asmx and wcf clients. But with this approach, since the underlying code is still asmx, it will not benefit from the underlying framework advantages that WCF provides as discussed above.



kick it on DotNetKicks.com

Thursday, June 18, 2009

WCF - Understanding the Service.

This post is an introduction to Windows Communication Foundation (WCF) and will illustrate the ease at which a WCF service can be built. This article is written with the assumption that the reader has no prior knowledge of WCF.

In this article I will just give you a small demo and allow you to get confidence on WCF especially if you are a novice.

In this post we will just see how to create a simple WCF service application without going into more theory on WCF.

In general WCF as the name Windows Communications Foundation implies that the WCF is the concept released in .NET Framework 3.0 in order to provide effective communication between different applications.

There is myth that WCF is only for windows applications. However, it is wrong to think that WCF is only for windows. This can be thought as the replacement(strictly speaking enhancement) of the Web Services in .NET 1.X and .NET 2.0 frameworks.

I am using the Microsoft Visual Studio 2008 for this demo. Here are the simple steps to follow,

1. Open visual studio and create a new project.

2. In the project types under Visual C# or Visual Basic, select the Web and select the WCF Service Application from the right pane as shown in the figure.

New Project Template

3. Once we click on the OK button we will get file opened Service1.svc.cs or Service1.svc.vb based on the language.

Now let us examine a few details on this newly created project.

Firstly, in the Solution explorer files, we can see three new files have created.

IService.cs

Service1.svc

Service1.svc.cs

Once we open the IService.cs file we can see the a interface and a class. The interface looks something like this(in C#),

[ServiceContract]
public interface IService1
{

[OperationContract]
string GetData(int value);

[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);

// TODO: Add your service operations here
}

If we examine the Interface code carefully, we find an attribute called ServiceContract. Well ServiceContract is something similar to a normal Service Contract in the real world. We some one agree to provide any service to their customers they need to tell the customers what the services they can offer. This is one service of such kind. This interface with ServiceContract attribute will have methods that will be exposed as the Service to the public. If you are not sure what does the expose to the public means, don’t panic, you can understand in the meanwhile.

So now, for whatever class we need to expose to the public will implement the interface that has the ServiceContract attribute. Well, then what about the attribute called OperationContract. This is nothing but the method that we need to expose to the public. For e.g., if we have 10 methods in our interface and out 10 we need to provide 5 methods to the public and the remaining 5 need not be. So now for the 5 methods which we planned to publish should have the attribute [OperationContract]. And the methods that do not have this attribute will never be exposed to the public.

Also note that this service contract(interface) has defined a using namespace called as System.ServiceModel

That’s all now for the Service Interface. Then what about the class that we see at the bottom which looks here,

[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";

[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}

[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}

We can see two kind of attributes here, namely [DataContract] and [DataMember]. For e.g., we need to expose the CompositeType to the public as a data type, then we can go for this attribute for our CompositeType. Since, WCF will support the standard data types as well as the data types which are surrounded with the attribute [DataContract]. And the [DataMember] is the property that we are allowed to provide for the service. And now we can add this class as the parameters as well as the return type as this,

CompositeType GetDataUsingDataContract(CompositeType composite)

{

}

Now, coming to the file named Service1.svc.cs, where we can find the actual service class that is to be exposed to the public.

public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}

public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}

Well, this class is nothing but the implementation of the IService1 interface as we saw earlier. This may have some user defined logic or some database operations etc.

While we try to open the file named Service1.svc we can see that the file will never open. In order to open this file make a right click on the file and choose Open With.. In the Open With dialog box you can select the Web Service Editor(Default) and click on the open button.

Open With..

In that file you can find something similar to this,

<%@ ServiceHost Language="C#" Debug="true" Service="WcfService1.Service1" CodeBehind="Service1.svc.cs" %>

This has the different attributes such as CodeBehind, Debug, Service and Language where we can customize or go for default.

Once we open the web.config file we can find an element called as system.serviceModel which will look as follow,

<system.serviceModel>
<services>
<service name="WcfService1.Service1" behaviorConfiguration="WcfService1.Service1Behavior">
<!-- Service Endpoints -->
<endpoint address="" binding="wsHttpBinding" contract="WcfService1.IService1">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WcfService1.Service1Behavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

However, this is the main part of the WCF goes on where we need to define where we host the service and how what are the bindings and what are the data contracts which is generally called as the ABC’s of the WCF.

Where

A= Address we host our service

B= Binding method we use for the service

C= Service Contract that we use.

This is a simple way of creating the Service. In the upcoming posts we can see how to consume the service, the security issues, transactions etc.

Thursday, March 19, 2009

Internet Explorer 8 Back Ground color issue

Today I saw a really interesting issue. The issue come up with Internet Explorer 8. However my site is running with out any issues since lot of days. In my page, I has a some shifts to be selected to do some task. Each shift may have some color. I need to display all the shifts in their own colors. To do this I have a RadioButtonList in my asp.net page. I am adding the style attribute to the page from the code behind as follows,

radioButtonListItem.Attributes.Add("style", "color:white;background-color:" + alteredColor);

This will display the my radio button list similar to this,



However, this looked very ugly when viewed in Internet Explorer 8,



After doing a small research, I understood that the background color is missing. Unfortunately, I was unable to browse the google in a effective way, since the problem is some what new. However with some observation Microsoft provided a good alternative for this issue. There is a button named "Compatibility View" which is placed just beside address bar of IE 8,



In the above image, you can see that there is a button just beside the Address bar. While clicking this button the page will reload. This has fixed the problem in my case.

Friday, March 6, 2009

Pull the html from a different page

I will demo a small interesting feature of ASP.NET which is unknown to many people. One of the hardest things in asp.net is to build a html strings in order to send a mail. Hardest - in the sense I mean to construct a good html. However a lot of developers will try to construct all the html by making use of StringBuilder objects. Sadly many people I saw were using the strings which leave the Garbage Collector to have work more.

Well. What if you have want to format your email text is a really good manner. Or what if you want to mail the page that is already existing. However you need to get all the html from a different page. A browser can get the html generated by your ASP.NET application and IIS. While a browser can get the html why cannot your application get the html of a page. Yes, you can get the html page of your aspx page.



This feature is provided in ASP.NET by the System.Net namespace. You can create an instance of the WebClient class.



using System.Net;

.....

.....

//The parameter url is to be the full url of your web page. It cannot be physical path. For eg., Http://www.google.com/test.aspx instead of ~/test.aspx

public string getTheHtmlOutput(string url)

{

string myHtmlOutput=string.Empty;

WebClient HtmlClient=new WebClient();



//Executes the page(url) that is passed and retrieves the html in the byte array.

byte[] outputBytes=HtmlClient.DownloadData(url);

myHtmlOutput=Encoding.Default.GetString(outputBytes);

return myHtmlOutput;

}



This method will return the html of some other page in your application. However, there are even some issue behind this such as execution time. And what if there is an error in the different page. Should the error will be mailed if you are using the page for mailing purposes. However, the raising errors in this way is very rare case.

Wednesday, March 4, 2009

GridView Series

I am very happy to create my first blog. I have chosen to cover the topics on gridview. I will cover the gridview control of asp.net in a series of blogs. First of all, to say GridView is a simple table in the html point of view. This is a new control released in .NET 2.0. It offers a lot of inbuilt options such as sorting, editing, paging with out a single line of code. Of course, the sentence "Single line of code" has many restrictions. I will discuss those in my future article.

However, coming to the point the GridView is frequently used to display the data in a tabular context. This consists of lot of formatting options, which can be easily handled by the developer without any knowledge on css.

The GridView will offer us a lot of ways to bind the data to it. We can connect to the gridview via,

-The ADO.NET objects such as DataTable, DataSet, DataView
-The User Objects such as the collections, ArrayLists etc.
-The Data Source controls such as SqlDataSource, ObjectDataSource.

In the next article I will conver how to fill the data to the grid.