Wednesday, October 7, 2009
Back to Work...
Hi Guys,
I have been away from my blog for some while since my schedule kept me occupied. But now I am back and will carry on writing. As a priority, I intend to complete my LINQ Explained series. So stay tuned for more...
Thursday, September 3, 2009
Some Useful Developer Tools
Scott Hanselman has posted some useful developer and power user tools for windows. I thought of sharing this with you. The post can be found here
Saturday, August 15, 2009
Using Custom Entities in ASP.NET Applications – Part 3
This is the third and final part of my short series on using custom entities in asp.net applications. In this part, we will look at some coding technique commonly used to program around custom entities and data transfer objects. For the sake of brevity, I will not go into the coding details rather focus on the architectural issues. So let’s get started.
Using Custom Entities and DTOs
Many of the sample applications show how to use Custom Entities (and DTOs). In addition to the standard UI, BLL and DAL Layer, the usual design is to have a fourth layer (usually known as Model Layer) consisting of Data Transfer Objects. The DTOs in the model layer is used for transfer of data betweent the three layers. Usually when a user makes a request, it flows from the UI to the BLL and finally to the DAL. In response, the DAL populates one or more DTOs and sends it back to the BLL. The BLL then sends the data back to the UI. Pay close attention to this last statement which is highlighted. To me, this is where we can employ different coding techniques and this decision is left to the developer. Let me explain these techniques in the following sections with examples.
Using DTOs - Only
In this technique, only DTOs are used between all the layers for transfer of data. The BLL returns the same DTOs received from the DAL to the UI. The UI binds to one or more instances of DTOs. Listing 1 shows this technique:
Listing 1
// Model Layer
using System;
public class EmployeeDTO
{
// properties
public int EmployeeID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Designation { get; set; }
public int Age { get; set; }
// constructor
public EmployeeDTO () {}
// constructor
public EmployeeDTO (int employeeId, string name, string address, string designation, int age)
{
this.EmployeeID = employeeId;
this.Name = name;
this.Address = address;
this.Designation = designation;
this.Age = age;
}
}
// Business Logic Layer
using System;
public class Employee
{
public Employee () {}
public IListGetAllEmployees ()
{
return EmployeeDAL.GetAllEmployees ();
}
public EmployeeDTO GetEmployeeById (int employeeId)
{
return EmployeeDAL.GetEmployeeById (employeeId);
}
public int Save (EmployeeDTO employee)
{
return EmployeeDAL.Save (employee);
}
// Validation…
// Business Rules…
}
The Emloyee entity in the BLL has a corresponding data transfer object (EmployeeDTO) in the Model Layer. The Employee entity has different CRUD methods. These methods accept and return one or more instances of type EmployeeDTO. This technique is shown in figure 1.
DTO DTO
UI <----------> BLL <-----------> DAL
Fig 1
There is nothing wrong in using DTOs throughout the application. But to me, this has a few shortcomings. First of all, this technique breaks the basic principle of OO programming, Encapsulation. Encapsulation states that both the state and behavior are held within the object. The object itself is responsible for managing its state and behavior. The state or behavior cannot be separated from the object. In the above code, the Employee class (residing in the BLL) does not define any state. It instead relies on the EmployeeDTO (Model Layer) to handle its state. This shows that the object is not in charge of its state and hence clearly breaks the principle of encapsulation.
Second, custom entities (defined in the BLL) have association with each other. These associations are defined by the help of their properties (primary keys). If they lack any property (as in the above code) then how do we define an association? I don’t see a point in defining associations in the Model Layer between data transfer objects (which lack any behavior as well).
Data Transfer Objects lack behavior yet they are not without advantage. Since they only consist of properties, they are light weight objects used to send data across subsystems and hence help improve the throughput of the system.
Using DTOs in parallel to Custom Entities
In this case, DTOs are limited between the BLL and DAL for transfer of data. However; the UI binds to custom entities instead of DTOs. This is possible since the custom entities define both the state and behavior. Before the UI binds to a custom entity, the custom entity copies over the properties of the DTO. This way, the data is available when the UI binds to a custom entity. Let us see this approach in listing 2:
Listing 2
// Model Layer
using System;
public class EmployeeDTO
{
// properties
public int EmployeeID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Designation { get; set; }
public int Age { get; set; }
// constructor
public EmployeeDTO () {}
// constructor
public EmployeeDTO (int employeeId, string name, string address, string designation, int age)
{
this.EmployeeID = employeeId;
this.Name = name;
this.Address = address;
this.Designation = designation;
this.Age = age;
}
}
// Business Logic Layer
using System;
public class Employee
{
// properties
public int EmployeeID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Designation { get; set; }
public int Age { get; set; }
// constructor
public Employee() {}
// constructor
public Employee (int employeeId, string name, string address, string designation, int age)
{
this.EmployeeID = employeeId;
this.Name = name;
this.Address = address;
this.Designation = designation;
this.Age = age;
}
// ------------------- CRUD Methods -------------------------------
public IListGetAllEmployees ()
{
return ConvertListOfEmployees (EmployeeDAL.GetAllEmployees ()); // convert to list of BO before sending to UI
}
public EmployeeDTO GetEmployeeById (int employeeId)
{
return MapToBO (EmployeeDAL.GetEmployeeById (employeeId)); // convert to BO before sending to UI
}
public int Save (Employee employee)
{
return EmployeeDAL.Save (MapToDTO (employee)); // convert to DTO before sending to UI
}
// ------------------- Converters ---------------------------------
// Convert list of EmployeeDTO to list of Employee
private void ConvertListOfEmployee (IListemployeeList)
{
IListEmployeeCollection;
foreach (EmployeeDTO employee in employeeList)
{
EmployeeCollection.Add (MapToBO (employee));
}
return EmployeeCollection;
}
// Convert an EmployeeDTO to Employee
private Employee MapToBO (EmployeeDTO employee)
{
return new Employee (employee.EmployeeID, Name, Age, Address, Designation);
}
// Convert an Employee to EmployeeDTO
private Employee MapToDTO (Employee employee)
{
return new EmployeeDTO (employee.EmployeeID, Name, Age, Address, Designation);
}
}
As you can see clearly, the above Employee Entity follows the principle of encapsulation. Both the state and behavior are encapsulated within the entity. However, in addition to the CRUD methods, the entity has a set of converters which are used to convert a DTO to a CE and vice versa. In my view, this is the only shortcoming of using this approach which may incur some overhead. But this overhead is minimal and can be ignored easily.
CE DTO
UI <----------> BLL <-----------> DAL
Fig 2
Why not use Custom Entities directly
Curios readers must be thinking “Why not just use custom entities throughout the layers” i.e. In addition to the UI, custom entities can be referenced by DAL as well. This way we don’t need to have an extra layer of data transfer objects. The answer to this is that referencing custom throughout will create a circular reference between the BLL and DAL. A reference to the DAL from the BLL is unidirectional. But if DAL also references the BLL, it results in a bidirectional reference which leads to a circular reference.
Summary
In this part, we saw how to use custom entities in conjunction with data transfer objects. We looked at two different techniques. The first technique uses DTOs for transfer of data through all the layers. This technique works well but does not follow the principle of encapsulation. Also, this leads to the confusion as what is the best place to define the association. Should we define it at the BLL layer or the Model layer?
The second technique uses DTOs only between the BLL and DAL. The UI communicates with the BLL through the custom entities. This approach removes both the problems the first approach, however; it incurs a slight overhead of converting custom entities to DTOs and vice versa.
With this, we come to the end of this series. But this is just not it. I plan to write more on custom entities as this has become the standard coding practice. Please do provide your feedback through your comments. Stay tuned for more...
Monday, August 10, 2009
Using Custom Entities in ASP.NET Applications – Part 2
This is the second part of my short series on using Custom Entities in asp.net applications. In this part we will see how association between custom entities is defined. We will also explore the different types of association between which can exist between custom entities.
Association between Entities
In the database world, relationship is a mandatory feature. Different tables are linked to each other through relationships. Relationships are defined by the help of primary keys. These primary keys are placed as reference (foreign keys) in other tables. In OO programming, this relationship between entities (or classes) is known as association. Each custom entity is uniquely identified by an entity identity or identifier. This entity identity maps to the primary key in the database.
In custom entities, an association is defined by placing the identity of one entity in the other. For example lets assume two entities Book and Author. Since a book always has an author (not to mention how many) we can define this association by placing the author identity in the book entity as show in listing 1:
Listing 1
public class Book
{
private int bookID;
private string title;
// other properties
private int AuthorID; // association
// other constructs
}
Association between Entities
In the following sections, we will look at the different types of association, also known as cardinality between entities. For this purpose, I will use the following entities:
• Customer
• Orders
• Products
• Suppliers
One-to-Many Association
In this type of association, one instance of an entity type is associated with multiple instances of the second type. For example, one Customer can have many Orders. In this case, the Customer is the owner of this association. So the Customer entity specifies the mapping by having a child list object of type Order as shown in listing 3:
Listing 3
public class Customer
{
private int CustomerID;
// other properties
private IListOrderCollection; // 1:M association
}
Many-to-One Association
In this type of association, multiple instances of one entity type are associated with a single instance of another type. For example, many Orders (owner) belong to one Customer. So each Order specifies the mapping by including the identity of the related Customer as shown in listing 4:
Listing 4
public class Order
{
private int OrderID;
// other properties
private int CustomerID; // M:1 association
}
Many-to-Many Association
In a many to many association, multiple instances of one entity type are associated with multiple instances of the other type. For example, many Products have many Suppliers and vice versa. In this case, both entities are the owner and have a child list collection of the related entity as shown in listing 5:
Listing 5
public class Product
{
private int ProductID;
// other properties
private IListSupplierCollection; // M:M association
}
public class Supplier
{
private int SupplierID;
// other properties
private IListProductCollection; // M:M association
}
One-to-One Association
One to One association is not very common and exists in special cases. For example, if a database table is very large and most of the fields are rarely used then the database designer tends to separate out these fields in a different table to improve performance. But both the tables are still linked through the same identity. In custom entities, such association is presented by a single entity which has all the fields.
Using an Identifier or a Full-Blown Object
One question commonly asked on different forums is that when defining an association, should we use the entity identity (a primitive data type) or a full blown object of the entity being referenced. In other words, listing 1 can be rewritten as following:
Listing 6
public class Book
{
private int bookID;
private string title;
// other properties
private Author author; // association – Full Blown Object
// other constructs
}
Watch closely, in the above listing, we are not using the simple AuthorID of type integer to define the mapping. Rather we have used a child object of type ‘Author’. This is one approach taken by developers. To me, the answer to the above question depends on different factors including the technology being used plus the user requirements. Let me explain both these scenarios in details.
First, ASP.NET comes with many built in controls which make data binding a breeze. These controls including the ObjectDataSource, GridView, ListView etc are capable of binding to custom entities as well. However, these controls can only bind to properties of primitive types (int, string, bit etc). These controls cannot bind to complex child object or collection. To me, this is a short coming in the framework and hopefully will be removed in a future version. Although there are workaround, but they do not offer a concrete solution. So if the custom entity contains a reference of simple type, it can easily bind to a data control.
Second, the user requirement also plays an important role. Suppose we are creating an application for a retail outlet. A Customer makes an Order for different purchases. This customer may already exist in the system. Now if we have modeled our Order class to have a full blown Custom child object, we can easily create both the Order and the Customer object. Why because we have full access to the Customer object through the Order object. This way when the Order is passed down to the DAL, the entire Customer object is passed along and saved to the database. On the other hand, if the Order only had a reference to Customer identity, we first had to create a new Customer and then assign his identity to the Order object. This would be more like a two step process.
In the end, to me it remains a user preference whether to use a reference of simple or custom type. Different factors play in and have to be considered before preference is locked down.
Light-Weight Model and Association
When it comes to architecture, different people have different opinions (and they are justified as well). When defining association between entities, it tends to get very complex and difficult to handle. Custom Entities may have a deep hierarchy of association. For example, a Product is composed of Components. Each Component has many Parts and each Part may be made up of Sub-Parts. With such hierarchy, many issues have to be considered. For example, if we make changes at any level or the hierarchy, the entire hierarchy has to be persisted. Similarly, if we are making changes at any level and the parent hierarchy leaves the transaction, all the properties have to be restored back to the original state. There are numerous scenarios with such deep hierarchy.
An alternative to deal with such associations is by defining a light-weight model. This means that there is no need to have a child object with the parent object. We can instead use method (or more specifically services) to fetch the child data. This is more like a Service-Oriented Architecture where we tend to rely on services. The concept is to simply fetch the data when required.
For example, using the above approach, we can rewrite listing 1 as following:
Listing 7
public class Book
{
private int bookID;
private string title;
// other properties
public Author GetBookAuthor ()
{
//return GetBookAuthor (this.bookID)
}
// other constructs
}
In the above listing, an Author object is returned using the method GetBookAuthor. This eliminates the need to reference the Author object within the Book class. I am sure you can see the advantages of using this approach. However, my opinion is not final.
Summary
In this post, we saw the how association is defined between entities. We also looked at the different types of associations also known as ‘cardinality’. We also looked at the different scenarios which lead to deciding whether to use a reference of primitive type or a full blown object. In the next post, we will see how to code around custom entities. Stay tuned for more…
Friday, August 7, 2009
Using Custom Entities in ASP.NET Applications – Part 1
Recently there has been a surge of architecture-related discussion in the .NET community. This stems from the fact that business applications are getting complex and intricate to build. Building N-Tier business applications is both a requirement and a challenging task. This cannot be achieved by just using a specific framework such as the .NET Framework. The .NET Framework does provide a rich library for building enterprise business applications but this is half the story. Sound Object-Oriented principles supported by architectural patterns apply across all development platforms without targeting a specific technolgy. This combination of technology, OO principle and architecture results in applications which are scalable, fault tolerant and user interactive.
In this short series, I will talk about using Business Entities in ASP.NET applications. The reason behind this series to present my two cents on most of the question asked on the forums regarding developing N-Tier applications using Custom Entities. This discussion is not intended to explain OO programming. The focus is to discuss architecture issues when using Custom Entities. I will start with simple concepts and then extend it from there.
What’s wrong with DataSet
Honestly speaking, DataSets are not evil at all and I prefer to use them whenever I can. It’s easy to program around a DataSet and IMHO, works great for small to mid sized applications. If you really fine tune the data layer accessing the database, a DataSet gives optimal performance. In addition to this, many of the data controls available in asp.net including ObjectDataSource, GridView, Datalist etc work really well with DataSets. However, a DataSet has its limitations and is not suited for every situation especially when used for Enterprise Applications. The most commonly faced problems include:
• They are not strongly-typed
• They lack validation and business rules.
• They do not support OO principles such as Encapsulation, Inheritance etc
• DataSet have a performance issue when used for large amount of data (see this)
• DataSets are not interoperable with applications written in other languages such as Java, PHP etc
• The use of DataSet dictates the Data-First design whereas OO principles focuses on Domain-First design
• Maintenance becomes difficult when an application starts growing with time (which every application does)
The alternative is to use custom entities discussed in the following section.
Using Custom Entities
Seasoned programmers tend to use classes for developing business applications. Classes allow the developers to take advantage of a rich OO programming model. This model comes with a set of well defined OO principles including Data Abstraction, Information Hiding, Encapsulation, Inheritance etc.
In its essence, a custom entity is just a regular class. But what makes it different is that it is a domain object. In business applications, domain objects identify the key entities within the system. Each domain object can be represented by a Custom Entity.
In addition to supporting OO principles, a custom entity defines business rules and custom validation. This subtle addition is the real difference between a regular class and a custom entity. For example, let’s look at the following Book custom entity:
public class Book
{
// properties
public int BookId { get; set; }
public string ISBN { get; set; }
public string Title { get; set; }
public string Author { get; set; }
// constructors
public Book () {}
public Book (string isbn, string title, string author)
{
// set values
}
// simple method
public int BuyBook (string ISBN)
{
// process
}
// validation rule
public book Validate (Book book)
{
if (book.ISBN == null)
return false;
// other rules
}
// business rule
public int isPremiumMember (int customerId)
{
// if customer is a premium member
// eligible for gift voucher
// return voucherNumber
}
}
The above entity defines the normal properties, constructors and a method (BuyBook). In addition to these constructs, the class also defines a validation method (Validate) and a business rule (isPremiumMember). The Validate method validates the state of the object while isPremiumMember method determines if the customer is eligible for a gift voucher given he is a premium member. This is just a trivial example. True custom entities can have a complex set of business rules.
Different terms including Business Object, Business Entity and Custom Business Entity are used interchangeably to represent a Custom entity. Though the purists may differentiate between them but IMHO, they all are the same. It’s just a preference of term used by different users.
Data Transfer Objects
Data Transfer Object (DTO) is a design pattern used to transfer data between software application subsystems. It is basically a data container. The main difference between a DTO and a Custom Entity is that a DTO does not have any behavior or responsibility and only consists of properties. A DTO is also known as a dumb object due to the lack of any behavior. Using a DTO has several advantages including:
• All data is summed up in one DTO and passed down to a layer
• Since an entire object is passed down the wire, adding or removing properties to the object does not effect the calls
• DTOs are light weight objects which give better as compared to DataSets
Keeping above in mind, the book BO in the above section can have the following corresponding Book DTO:
public class BookDTO
{
public int BookId { get; set; }
public string ISBN { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public Book () {}
public Book (string isbn, string title, string author)
{
// set values
}
}
Using Custom Entities and DTOs
A typical 3-tier (logical) application has three layers namely User Interface Layer (UI), Business Logic Layer (BLL) and the Data Access Layer (DAL). The UI layer provides an interface to the user to interact with the system. The BLL (application layer, middle layer) is where all the business logic resides and the DAL deals with operations of the data source. The UI never interacts with the DAL directly. When a user makes a request from the UI, the request is directed to the BLL. The BLL then forwards the request to the DAL. The typical flow of a user request is as following:
UI <-> BLL <-> DAL
The question is how the data transfers between the layers? This is where the DTOs come into play. When the user request reaches the DAL, the DAL fetches the data from the data source and bundles it into a DTO. The DTO is then returned to the BLL followed by the UI. Similarly when a user creates or updates a record, the entire DTO is transferred back to the BLL and then to the DAL.
The update and delete process can be handled by just using the primary key value.
Is a DTO a Custom Entity
This is an interesting question. I have seen many applications where both the terms are used interchangeably. There is no harm in doing so but I tend to disagree. A DTO is really a design pattern used to transfer data between subsystems. Although it a class but keep in mind that a DTO does not define any behavior, business rules, validation or relationship. In the following posts, I will show you how a DTO is used both as a custom entity and individually.
Summary
In this post, I just gave you an overview of what Custom entities are and tried to understand the basics of using Custom Entities when developing business applications. In the following post, we will dive deeper and explore more about custom entities.
Thursday, July 9, 2009
Getting Started with WCF Service
In this post, I will walk you through creating your first Windows Communication Foundation Service. Those new to WCF should read my previous post to understand the basics concepts of WCF Service.
Introduction
Before a WCF Service can be consumed by a client application, the following three steps are required:
Service: The actual WCF Service which provides business functionality
Host: A hosting environment which hosts the service
Client: A client application/service which invokes the WCF Service
In the following sections, we will create a solution which consists of three separate projects representing the service, host and the client respectively. I will be using Visual Studio 2008 to create the application.
Getting Started
1. Start a new instance of Visual Studio 2008.
2. Click on File -> New Project. From Project types pane, select Visual Studio Solutions
3. From the Template pane, select Blank Solution
4. Enter WCFIntroduction for Project Name. Also specify the location according to you working preference
This will create a blank solution as shown in figure 1. Let us now create the actual WCF Service.

Fig 1
Creating the Service
1. In the solution explorer, right click on ‘WCFIntroduction’ and select Add -> New Project.
2. Select Class Library template and name it as WCFCalculator. Make sure that the location is set to ..\WCFIntroduction as shown in figure 2. Click OK to create the project.

Fig 2
3. The newly created project contains a single file ‘Class1.cs’. Rename it to ‘WCFCalculatorService.cs’. We will return to this file shortly.
4. From the solution explorer, right click on ‘WCFCalculator’ project and select ‘Add Reference’. The ‘Add Reference’ dialog appears. From the .NET tab, select ‘System.ServiceModel’ and click OK. A reference to the respective namespace is added which is required to work with WCF Services
5. Again right click on ‘WCFCalculator’ project and select Add -> New Item. Select ‘Class’ template, name it as ‘IWCFCalculatorService.cs’ as shown in figure 3 and click Add
6. This will create a new class file ready to be coded

Fig 3
7. Change the class definition to ‘public interface IWCFCalculatorService’. Type in the code as shown in listing 1 and save the file
Listing 1
8. Let us now return to the ‘WCFCalculatorService.cs’ file. Open it and type in the following code:
Listing 2
Compile this project to make sure there are no errors. We have just created a very basic WCF Service used to add two numbers. The next step is to host this service in a hosting environment. In the following section, we will create a windows console application which will host this service.
Hosting the Service
1. Right click on the solution ‘WCFIntroduction’ and select Add -> New Project.
2. Select ‘Console Application’ template, name it as ‘Host’ as shown in figure 4 and click OK

Fig 4
3. Right click on ‘Host’ project and select Add Reference. From the .NET tab, select System.ServiceModel. From the Projects tab, select ‘WCFCalculator’ and press OK
4. The Host project consists of one file ‘Program.cs’. Open this file and type in the code as shown in listing 3
Listing 3
5. Compile this project. Make sure that the Host project is set as Startup Project (You can do so by right clicking on Host project and select ‘Set as Startup Project’). Press Ctrl+F5 to run this project. You should see a command window with message ‘Press to terminate service...’ as shown in figure 5. This means the service is up and runninig. Keep this window open (service is active). Next we will create a client application which will interact with this service. Let us return to our solution.

Fig 5
Consuming the Service – Client Application
1. Right click on solution ‘WCFIntroduction’ and select Add -> New Project
2. Select ‘Console Application’ template, name it as Client and click OK as shown in figure 6

Fig 6
3. Add a reference to System.ServiceModel namespace (as done in the above steps)
4. This project consists of a single file ‘Program.cs’. Open this file and type in the code as shown in listing 4
Listing 4
5. Here is the tricky part. In the above code, a proxy is created using the Service Contract (IWCFCalculatorService). To use this interface, copy it over from the ‘WCFCalculator’ project to the ‘Client’ project. Don’t forget to change the namespace to ‘Client’ in this file (In short the same interface now exists in both the ‘WCFCalculator’ and ‘Client’ project).
6. Compile the ‘Client’ project and make it the Startup Project (Right click on ‘Client’ project and select ‘Set as Startup Project’). Press Ctrl+F5 and you should see the output as shown in figure 7

Fig 7
Wow, you just create a WCF service from scratch and got it working. Though it may not be simple, I am sure it’s worth a try.
How it Works
Let me explain some of the concepts discussed in the above sections. If you have read my previous post, many of the details should be self explanatory. In listing 1, the IWCFCalculatorService interface is the Service Contract since it is decorated with the [ServiceContract] attribute. The single method within this interface - AddNumbers – is a WCF method as its decorated with the [OperationContract] attribute. Since IWCFCalculatorService is a service contract, any class implementing this interface becomes a WCF Service. This is also true for the WCFCalculatorService class as shown in listing 2.
In listing 3, an instance of ServiceHost class is created. This class provides a host for a WCF Service. It accepts two parameters, Type and params respectively. The Type parameter specifies the type (WCFCalculator.WCFCalculatorService) of the service while params specifies a collection of addresses (http://localhost:8000/WCFCalculator) where the service can be hosted. Next the ServiceHost defines a new Endpoint by calling the AddServiceEndPoint (). This method accepts two parameters including a contract (WCFCalculator.IWCFCalculatorService) and the type of binding (basicHttp) used by the Endpoint. Once an endpoint is defined, the service is open and available to accept requests from the client.
For a client to communicate with the service, a proxy is required. In listing 4, the generic ChannelFactory service model type generates the proxy and the related channel stack. This factory uses an instance of the EndpointAddress class which provides a unique network address (which points to the service endpoint) used by the client to communicate with the service. The factory creates a service of type IWCFCalculatorService. Later the generated proxy is used to invoke the required funcationlity.
Summary
In this post, I walked you through creating your first WCF Service. You may find it a bit difficult in the beginning but as you gain experience, WCF is a great tool to work with. In future post, I will talk more about WCF. So stay tuned for more…
Introduction
Before a WCF Service can be consumed by a client application, the following three steps are required:
Service: The actual WCF Service which provides business functionality
Host: A hosting environment which hosts the service
Client: A client application/service which invokes the WCF Service
In the following sections, we will create a solution which consists of three separate projects representing the service, host and the client respectively. I will be using Visual Studio 2008 to create the application.
Getting Started
1. Start a new instance of Visual Studio 2008.
2. Click on File -> New Project. From Project types pane, select Visual Studio Solutions
3. From the Template pane, select Blank Solution
4. Enter WCFIntroduction for Project Name. Also specify the location according to you working preference
This will create a blank solution as shown in figure 1. Let us now create the actual WCF Service.
Fig 1
Creating the Service
1. In the solution explorer, right click on ‘WCFIntroduction’ and select Add -> New Project.
2. Select Class Library template and name it as WCFCalculator. Make sure that the location is set to ..\WCFIntroduction as shown in figure 2. Click OK to create the project.
Fig 2
3. The newly created project contains a single file ‘Class1.cs’. Rename it to ‘WCFCalculatorService.cs’. We will return to this file shortly.
4. From the solution explorer, right click on ‘WCFCalculator’ project and select ‘Add Reference’. The ‘Add Reference’ dialog appears. From the .NET tab, select ‘System.ServiceModel’ and click OK. A reference to the respective namespace is added which is required to work with WCF Services
5. Again right click on ‘WCFCalculator’ project and select Add -> New Item. Select ‘Class’ template, name it as ‘IWCFCalculatorService.cs’ as shown in figure 3 and click Add
6. This will create a new class file ready to be coded
Fig 3
7. Change the class definition to ‘public interface IWCFCalculatorService’. Type in the code as shown in listing 1 and save the file
Listing 1
using System;
using System.ServiceModel;
namespace WCFCalculator
{
[ServiceContract(Namespace = "http://youruniquedomain")]
public interface IWCFCalculatorService
{
[OperationContract]
int AddNumbers (int x, int y);
}
}
8. Let us now return to the ‘WCFCalculatorService.cs’ file. Open it and type in the following code:
Listing 2
using System;
using System.ServiceModel;
namespace WCFCalculator
{
public class WCFCalculatorService : IWCFCalculatorService
{
public int AddNumbers (int x, int y)
{
return x + y;
}
}
}
Compile this project to make sure there are no errors. We have just created a very basic WCF Service used to add two numbers. The next step is to host this service in a hosting environment. In the following section, we will create a windows console application which will host this service.
Hosting the Service
1. Right click on the solution ‘WCFIntroduction’ and select Add -> New Project.
2. Select ‘Console Application’ template, name it as ‘Host’ as shown in figure 4 and click OK
Fig 4
3. Right click on ‘Host’ project and select Add Reference. From the .NET tab, select System.ServiceModel. From the Projects tab, select ‘WCFCalculator’ and press OK
4. The Host project consists of one file ‘Program.cs’. Open this file and type in the code as shown in listing 3
Listing 3
using System;
using System.ServiceModel;
namespace Host
{
class Program
{
static void Main (string[] args)
{
using (ServiceHost host = new ServiceHost (typeof (WCFCalculator.WCFCalculatorService), new Uri ("http://localhost:8000/WCFCalculator")))
{
host.AddServiceEndpoint (typeof (WCFCalculator.IWCFCalculatorService), new BasicHttpBinding (), "WCFCalculatorService");
host.Open ();
Console.WriteLine ("Pressto terminate service...");
Console.ReadLine ();
}
}
}
}
5. Compile this project. Make sure that the Host project is set as Startup Project (You can do so by right clicking on Host project and select ‘Set as Startup Project’). Press Ctrl+F5 to run this project. You should see a command window with message ‘Press
Fig 5
Consuming the Service – Client Application
1. Right click on solution ‘WCFIntroduction’ and select Add -> New Project
2. Select ‘Console Application’ template, name it as Client and click OK as shown in figure 6
Fig 6
3. Add a reference to System.ServiceModel namespace (as done in the above steps)
4. This project consists of a single file ‘Program.cs’. Open this file and type in the code as shown in listing 4
Listing 4
using System;
using System.ServiceModel;
namespace Client
{
class Program
{
static void Main (string[] args)
{
EndpointAddress endPoint;
IWCFCalculatorService proxy;
int result;
endPoint = new EndpointAddress ("http://localhost:8000/WCFCalculator/WCFCalculatorService");
proxy = ChannelFactory.CreateChannel (new BasicHttpBinding (), endPoint);
result = proxy.AddNumbers (2, 3);
Console.WriteLine ("2 + 3 = " + result.ToString ());
Console.WriteLine ("Pressto terminate client...");
Console.ReadLine ();
}
}
}
5. Here is the tricky part. In the above code, a proxy is created using the Service Contract (IWCFCalculatorService). To use this interface, copy it over from the ‘WCFCalculator’ project to the ‘Client’ project. Don’t forget to change the namespace to ‘Client’ in this file (In short the same interface now exists in both the ‘WCFCalculator’ and ‘Client’ project).
6. Compile the ‘Client’ project and make it the Startup Project (Right click on ‘Client’ project and select ‘Set as Startup Project’). Press Ctrl+F5 and you should see the output as shown in figure 7
Fig 7
Wow, you just create a WCF service from scratch and got it working. Though it may not be simple, I am sure it’s worth a try.
How it Works
Let me explain some of the concepts discussed in the above sections. If you have read my previous post, many of the details should be self explanatory. In listing 1, the IWCFCalculatorService interface is the Service Contract since it is decorated with the [ServiceContract] attribute. The single method within this interface - AddNumbers – is a WCF method as its decorated with the [OperationContract] attribute. Since IWCFCalculatorService is a service contract, any class implementing this interface becomes a WCF Service. This is also true for the WCFCalculatorService class as shown in listing 2.
In listing 3, an instance of ServiceHost class is created. This class provides a host for a WCF Service. It accepts two parameters, Type and params respectively. The Type parameter specifies the type (WCFCalculator.WCFCalculatorService) of the service while params specifies a collection of addresses (http://localhost:8000/WCFCalculator) where the service can be hosted. Next the ServiceHost defines a new Endpoint by calling the AddServiceEndPoint (). This method accepts two parameters including a contract (WCFCalculator.IWCFCalculatorService) and the type of binding (basicHttp) used by the Endpoint. Once an endpoint is defined, the service is open and available to accept requests from the client.
For a client to communicate with the service, a proxy is required. In listing 4, the generic ChannelFactory
Summary
In this post, I walked you through creating your first WCF Service. You may find it a bit difficult in the beginning but as you gain experience, WCF is a great tool to work with. In future post, I will talk more about WCF. So stay tuned for more…
Tuesday, June 30, 2009
Fundamentals of Windows Communication Foundation
In this post, we will look at the fundamental concepts behind Windows Communication Foundation or WCF (formally known as Indigo). This is not a walkthrough post rather it emphasis on the concepts which make up WCF. Creating and working with WCF Services will be a topic of future post.
What is Windows Communication Foundation
WCF is Microsoft’s flagship technology for developing Distributed application. It is a development platform which targets Service-Oriented Architecture. WCF provides a loosely coupled and interoperable platform for developing service-oriented applications.
Before the introduction of WCF, technologies such as .NET Remoting, COM, DCOM+ and MSMQ have existed for developing distributed applications. The downfall of these technologies has been coupling to a specific technology. Only a .NET Remoting client can talk to a .NET Remoting server. This means that’s its almost impossible for a Java-based client to talk to a .NET Remoting Server. Although Web Services have addressed the issue of interoperability to a greater extent, the introduction of Enhancement have started yet another race between different vendors.
To overcome the problem of interoperability and tight coupling, Microsoft introduced Windows Communication Foundation with .NET Framework 3.0. The System.ServiceModel assembly provides the core functionality for WCF. WCF provides a single programming model for developing distributed applications. It supports different protocols, behaviors and policies. This means the same WCF Service can be exposed to clients using different protocols. This way the service encompassing the business functionality remains the same but has different interfaces to interact with.
How does a WCF Service Work
Before I proceed to explain the different concepts behind WCF, I want to give you a faint idea of how a WCF application is organized. Basically a WCF application consists of three parts:
Service: The service exposes the business functionality to the rest of the world
Host: Before a service is available, it must be hosted in an environment.
Client: The client is an application or yet another service which accesses the service
Let us now look at the different concepts which make up a WCF application in the following sections.
Service and Contract
A service is a set of business functionality. From a .NET point-of-view, a service represents a CLR type. This type exposes different methods which can be invoked by client. For a type to be WCF Service, it must have a service contract. A service contract is defined by applying the [ServiceContract] attribute on a class or an interface. Any class implementing an interface with associated service contract is also a WCF service. Following listing shows a simple service contract:
[ServiceContract (Namespace="http://myuniquenamespace/")]
public interface IMaths
{
[OperationContract]
int AddTwoNumbers (int x, int y);
}
It is quite obvious that a class/interface define methods to be invoked. All methods exposed by a WCF Service must be decorated with the [OperationContract] attribute. A method without this attribute is not a part of the WCF Service. You must keep in mind that the OperationContract can only be applied to methods and not to a property or event. Why, because WCF is about exposing business functionality and business functionality resides in methods. For this reason, the OperationContract is only specific to methods.
Hosting
As I mentioned above, before a service can be accessed, it must be hosted in a host process. A host process can be any Windows Process. We can host multiple services under one host process or vice versa. There are three kinds of hosting available including:
Self Hosting: In self-hosting, the programmer is responsible for providing a hosting environment for the service which can include a Console application, Windows Form, WPF application or Windows NT Service.
IIS Hosting: A service can be hosted like a regular asp.net application. This requires a .svc file to be hosted in IIS
WAS Hosting: The Windows Activation Service (WAS) is only available for Windows Vista. Like IIS Hosting, WAS also requires a .svc file and is available for different protocols.
Under the hood of every host, the WCF Service Model is responsible for handling the communication. The ServiceHost class (a part of the service model) initiates the communication channel. A ServiceHost has an associated service type, address, service contract and communication protocol.
Addresses
Each WCF service has a unique address which a URI (Universal Resource Identifier). The URI has the following syntax:
[scheme]://[domain|machine-name][:port]/[optional [path]
A scheme defines the transport protocol used for communication. These protocols can include HTTP, TCP, name-pipes, MSMQ etc. Each of these protocols has an associated scheme such as http, net.tcp etc. The domain is the name of the machine or domain hosting the service. The port identifies the communication port associated with a specific protocol. A path can be used to avoid ambiguity. For example, we may have two services hosted on the same address. In this case, the optional path will give a separate address for each hosted service. The following shows a few examples of addresses:
http://www.mydomain.com
net.tcp://localhost/servicename
net.pipe://localhost:5500/myservice
Binding
Binding represents the options of choosing from different transport protocols, message encoding formats, security and reliability options for communication. When it comes to using a combination of these features, the options are countless - almost. For example, one may decide to use Http, Https, TCP, MSMQ, Named Pipes etc. as a transport protocol. Message encoding can be based on Binary Serialization or XML formatting. Security is yet another broad area to select from. If we plot a matrix of available options, we will end up with a very long list.
WCF Binding simplifies the above process by grouping together different options. For example HttpBasicBinding supports Http/Https protocols, Text/MTOM encoding format and is interoperable between existing and new web services format. Similarly, NetTcpBinding supports TCP protocol, Binary formatting and is not interoperable with other protocols. Details of different binding options can be found here.
Endpoint
To initiate communication with a service, the service model (ServiceHost) must provide an Endpoint. An endpoint is basically the trilogy of Address, Binding and Contract (commonly known as the ABC of a service). A service must have at least one endpoint, although it can have multiple endpoints. The ServiceHost must be initialized with one or more endpoints before communication commences.
Since a service can expose more than one endpoint, the same service is available with different communication options. For example, Service-A may be available over Http for web services but is also is available over TCP behind a firewall. It all comes down to the user requirements but the options are numerous. Endpoints can be configured using config files or programmatically.
Metadata
A service is attached to an endpoint where each endpoint has associated address, binding and contract. The client communicates with this endpoint to invoke business functionality. But the client needs to know about the endpoint before interacting with the service. Metadata provides information about an endpoint to the clients. Metadata can be generated by the help of a ServiceHost. The ServiceHost can either expose a metadata endpoint (this is different from the service endpoint) or can generate a WSDL file representing the metadata.
Proxy
A client can only communicate with a service using a proxy. A proxy acts on behalf of the service and exposes methods to the client. It also handles the underlying plumbing associated with the communication i.e. it handles message serialization, encoding format etc. A proxy communicates with one endpoint so it’s a one-to-one relationship. Proxies are generated by the help of metadata of a service.
With this we come to the end of this post. Future posts will talk about creating WCF Services. So stay tuned for more…
Wednesday, June 24, 2009
Dynamic ASP.NET Ajax Accordion Control
In this post we will take a look at the accordion control. The Accordion control is a part of the AJAX Control Toolkit which comes as a separate bundle to be used with ASP.NET AJAX.
Accordion Control
An accordion control represents a group of panels where only one panel is selectable at a time. Each panel consists of a header and content template. According to ASP.NET AJAX Website “An Accordion is a web control that allows you to provide multiple panes and display them one at a time. It is like having several CollapsiblePanels where only one can be expanded at a time”.
There are different properties of an accordion which control its look and feel. These properties include:
SelectIndex: Specifies the pane to be selected
FadeTransitions: A boolean value which adds or removes a transition effect to a pane
TransitionDuration: Specifies the time of transition. This is in milliseconds
RequiredOpenPane: A boolean value which always keeps one pane open
DataSourceID: Specifies the data source for building data-bound control
Data-Binding with Accordion Control
An accordion control can display both static and dynamic data. When displaying static data, an accordion uses the <Pane> template. Each pane consists of an <AccordionPane> which in turn consists of a <Header> and <Content> template.
Listing 1 defines a simple accordion which displays static data using the <Panes> template:
Listing 1
<cc1:Accordion
ID="Accordion2"
runat="server">
<Panes>
<cc1:AccordionPane runat="server" ID="AccordionPane1">
<Header>First</Header>
<Content>This is the Firt Content Pane </Content>
</cc1:AccordionPane>
<cc1:AccordionPane runat="server" ID="AccordionPane2">
<Header>Second</Header>
<Content>This is the Second Content Pane </Content>
</cc1:AccordionPane>
<cc1:AccordionPane runat="server" ID="AccordionPane3">
<Header>Third</Header>
<Content>This is the Third Content Pane </Content>
</cc1:AccordionPane>
</Panes>
</cc1:Accordion>
To build a dynamic accordion control, two points are important. One is to use the DataSourceID property (which is a standard property of most of the ASP.NET Controls) and second is to use the <HeaderTemplate> and <ContentTemplate>. The function of each of these templates is pretty obvious from their names.
Listing 2 shows a dynamically created accordion control which displays data from the Northwind Database:
Listing 2
<cc1:Accordion
ID="Accordion1"
runat="server"
FadeTransitions="true"
AutoSize="Fill"
SelectedIndex="0"
RequireOpenedPane="false"
TransitionDuration="250"
DataSourceID="SqlDataSource1"
Width="500">
<HeaderTemplate>
<b><%#DataBinder.Eval(Container.DataItem, "CustomerID")%></b>
</HeaderTemplate>
<ContentTemplate>
<table border="1" cellpadding="4" cellspacing="0" width="100%">
<tr>
<td width="10%" align="right" class="style1">
<b>Company:</b>
</td>
<td width="90%" class="style1">
<%#DataBinder.Eval (Container.DataItem, "CompanyName")%><br />
</td>
</tr>
<tr>
<td width="10%" align="right" class="style1">
<b>Contact: </b>
</td>
<td width="90%" class="style1">
<%#DataBinder.Eval (Container.DataItem, "ContactName")%><br />
</td>
</tr>
<tr>
<td width="10%" align="right" class="style1">
<b>Address: </b>
</td>
<td width="90%" class="style1">
</b><%#DataBinder.Eval (Container.DataItem, "Address")%><br />
</td>
</tr>
<tr>
<td width="10%" align="right" class="style1">
<b>City: </b>
</td>
<td width="90%" class="style1">
<%#DataBinder.Eval (Container.DataItem, "City")%><br />
</td>
</tr>
<tr>
<td width="100%" colspan="2" align="right" class="style1">
<b><a href="edit.aspx?CustomerID=<%#DataBinder.Eval(Container.DataItem, "CustomerID")%>">Edit</a></b>
</td>
</tr>
</table>
</ContentTemplate>
</cc1:Accordion>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT TOP (10) [CustomerID], [CompanyName], [ContactName], [Address], [City] FROM [Customers]">
</asp:SqlDataSource>
Summary
The Accordion control comes with ASP.NET AJAX Control Toolkit. An accordion can consists of multiple panes where each pane consists of a header and content template.
An accordion control has different properties. Many of the properties are used to control the way a pane is rendered or hidden. These properties add animation effects to a pane transition. A data source property also exits to bind an accordion control to a data source.
An accordion can bind to static or dynamic data. For static data, the <Panes> template is used. To dynamically bind the data, the </HeaderTemplate> and <ContentTemplate> are used.
Sunday, May 17, 2009
Exclude Pages from ASP.NET Authentication
Recently i discovered an interesting feature of asp.net where we can exclude page(s) from asp.net authentication. Usually once we have asp.net authentication setup, our requests to different pages must be authenticated. But at times we may require to exclude some of the page(s) from this restriction. This can be easily done by adding a <location> section in the web.config file. The <location> tag goes under the <configuration> section and can be defined as following:
<location path="excludepage.aspx">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
This tag can also be applied to page in a specific folder as following:
<location path="myfolder/excludepage.aspx">
We can have several <location> tags defined for seperate pages in a web.config file. However, if you have many pages to be excluded, a better approach is to move all the pages under one folder and specify this folder in the <location> tag as following:
<location path="myfolder">
Do keep in mind that if excluded pages reference a css, image etc file, those too must be excluded in order work properly.
Hope this post has been helpful. Stay tuned for more...
Wednesday, May 13, 2009
Crystal Report with Alternate Row Color
In my previous post, I walked you through creating a simple crystal report in visual studio. I also mentioned that in the following posts, I will touch upon different topics relating to crystal report. Creating a crystal report is easy; however the users always expect better looking reports for their use.
One of the questions which pops up on many forums is ‘how to have alternate row color’ in a crystal report just like a gridview in asp.net. To have alternate row color in a crystal report, you have to format a section. A section is separated by a gray bar on the report. There are different sections in a report including ReportHeader, PageHeader, GroupHeader, Details and ReportFooter sections. Usually records appear under the Details Section. To have alternate row color, follow these steps:
1. Right click on Details Section and select Section Expert…

2. In the Section Exert panel, select the Color Tab and click on the formula icon (with x+2 written on it).
3. In the Formula Section panel, we have to write code to change the color for alternate rows.
4. Enter the following code as in listing 1 and click on Save and close icon at the top.
Listing 1
IF RecordNumber mod 2 = 0 Then
crRed
Else
NoColor
Now when you view the report, you will see alternate rows with a red background. That is all required to have the required alternate coloring effect. Hope this post was useful for you. Stay tuned for more…
Subscribe to:
Posts (Atom)