Using LINQ with Relational Data

Greetings,

Till this point we have seen LINQ To Objects and LINQ To XML. I found a great webcast on using LINQ with Relational Data by Rob Bagby, So I thought instead of explaining my way, I would recommend you to go through the webcast 🙂

MSDN Webcast: Using LINQ with Relational Data (Level 100)

LINQ To XML

In my earlier post on LINQ, we saw an example of LINQ to Objects. In this post we will see LINQ to XML example. LINQ to XML was the real reason why i attracted towards LINQ. I’m pretty excited to see what LINQ provides as compare to the old techniques. So let’s start coding 🙂

Let’s say we have an XML as below:











Now suppose that I want to get list of all employees in Microsoft. Without LINQ, I would probably load the xml in XmlDocument object and then apply XPATH with respect to the company name attribute. With LINQ, it’s easy and simple way to load xml and write a single SQL like query even for XML. For instance i want to fetch list of all employees in KalSoft,

var companies = XElement.Load("companies.xml").Elements("Company");

var queryResult = from company in companies
where company.Attribute("Name").Value == "KalSoft"
select company.Descendants();

This query selects all the descendants i.e. Employee(s) of company having Name == “KalSoft”. To obtain the output we can get the string as

foreach (var item in queryResult)
{
foreach (var element in item)
{
Console.WriteLine(element);
}
}

which will give us the desired output:

LinqToXmlOutput

Hence, LINQ to XML provides an simpler way, to programmer, to query XML Documents based on different conditions.

Beginning WCF

Windows Communication Foundation (WCF) is an integral part of .NET Framework 3.*. “It provides a unified framework for rapidly building service-oriented applications that makes it easy to build and consume secure, reliable, and transacted Web services. It unifies the capabilities in ASMX, WSE, Remoting, COM+, and MSMQ; therefore developers need to learn only one programming model.” -MSDN

And Today we are going to see a very very basic example of using Windows Communication Foundation(WCF). So let’s begin.

Pre-Requisites:

The first thing you need is .NET framework 3.*, 3.5 SP1 in particular 🙂 which you can download from Microsoft Download Center. Okay, the next thing is IDE. If you don’t have Visual Studio, there are express edition(s) available that are free to download and use. In particular, I’ve just downloaded Visual C# 2008 Express Edition which seems cool 🙂

vcsharpIDE

Get Set Go!
Service

First of all we need to create a Service and for that I’m going to create a new project i.e. Class Library with name RegistrationService as shown below:

projectType

Now we need to add reference of System.ServiceModel which is main dll required for WCF.

reference

Next we need to create a contract of Service i.e. the interface of the service having required attributes as shown below:

[ServiceContract(Namespace="http://adil.com/RegistrationService/2009")]
public interface IRegistrationService
{
[OperationContract]
string RegisterName(string name);
}

Notice that the interface is having ServiceContractAttribute which is mandatory and indicates that an interface defines a service contract in a WCF application. The namespace parameter is optional and is used to define unique namespace to the service and by default its set to http://tempuri.org/. Also notice that OperationContractAttribute is marked on the method(s) need to be exposed to the client.

Next we are going to add a class with name RegistrationService.cs which will implement this interface.

public class  RegistrationService: IRegistrationService
{
public string RegisterName(string name)
{
return string.Format("Registered Name : " + name);
}
}

All right, till this point our service is ready. We have contract to be exposed and we have class implementing that contract. Now we need to have a Host Application (Executable). Every service need to be hosted either on IIS or WinApp or Window Service etc. So, for this example, we will create a Console Application to Host our Registration Service.

serviceHost

Also you need to add System.ServiceModel reference to this host (executable) application as well. The Host application need to define the ABC of WCF which is

  • A-> Address (Address where service will be hosted)
  • B-> Binding (For now, take it as underlying protocol like HTTP, TCP etc)
  • C-> Contract (The interface of the service)

We will create a class Host for hosting this RegistrationService.

public class Host
{
ServiceHost host;
public void StartService()
{
try
{
host = new ServiceHost(typeof(RegistrationService));
host.AddServiceEndpoint(typeof(IRegistrationService),
new BasicHttpBinding(),
"http://localhost:8000/RegistrationService");
host.Open();
Console.WriteLine("Service Started Successfully");
Console.ReadLine();
}
catch (System.Exception exception)
{
Console.WriteLine("Unable to start service n " + exception.Message);
}
}
public void StopService()
{
if (host != null)
host.Close();
}
}

Notice that the line

host.AddServiceEndpoint(typeof(IRegistrationService),
new BasicHttpBinding(),
"http://localhost:8000/RegistrationService");

basically adds an Endpoint where service will be hosted defining the type of contract i.e. IRegistrationService, the underlying protocal i.e. BasicHttpBinding and the Address. Let’s hit F5 and run it.

serviceStarted

That is all for the service.

Client

The client need to have proxy of the service, in general, ABC of the service. For proxy we will copy the contract of the service at the client side and create proxy using ChannelFactory class of WCF. Further the type of contract, Binding and Endpoint Address is passed to ChannelFactory constructor. Consider the code snippet below:

[ServiceContract(Namespace = "http://adil.com/RegistrationService/2009")]
public interface IRegistrationService
{
[OperationContract]
string RegisterName(string name);
}
class Program
{
static void Main(string[] args)
{
IRegistrationService proxy = ChannelFactory.CreateChannel
(new BasicHttpBinding(), new EndpointAddress("http://localhost:8000/RegistrationService"));
Console.WriteLine("nCalling Service...n");
Console.WriteLine(proxy.RegisterName("Adil"));

Console.ReadLine();

}
}

That’s it. Let hit F5,

callingRegService

So we have created a simple client/server application using WCF. Please note that this is very simple example in which both client and server know the address, contract and binding. In real scenario, the service information is exposed to client using WSDL (Web Services description Language).

Hello LINQ

In Microsoft Pakistan Developers Conference (PDC) 2007, I attended a sessions on Language Integrated Query (LINQ) but until recent I didn’t utilize it seriously. But recently I go through some videos on LINQ at MSDN. I was impressed at all 🙂

LINQ is used to query data from objects. There are three basic categories of LINQ:

  • LINQ to Objects
  • LINQ to XML
  • LINQ to SQL

If you are new to LINQ, I would recommend to skim through article on LINQ on MSDN. Let’s see a simple example of LINQ to Objects. LINQ to Objects is used to query in-memory data stores. Suppose we have a collection of countries’ name and we want to get list of countries starting with ‘C’.

string[] countriesCollection = 
{ "Pakistan", "India" , "UAE", "US", "Australia", "UK", "Canada",
"China"};

Without LINQ, we need to traverse the list and manually add a check on each string. LINQ do that for me in a simpler way:

var queryResult = from country in countriesCollection
                  where country.StartsWith("C")
                  orderby country
                  select country;

Now simply print the list return, ordered, in queryResult

foreach (var item in queryResult)
    Console.WriteLine(item.ToString());

The ouput will comprise of two items:

Canada
China

Similarly, we can query to not only primitive data types but also custom data types as well. For instance, let’s say we have a class Student as shown below:

public class Student
{
    public string Name { get; set; }
    public int Id { get; set; }
    public string Grade { get; set; }
    public Student(string stName, int stId, string stGrade)
    {
        Name = stName;
        Id = stId;
        Grade = stGrade;
    }
}

Let’s create a List of student type and manually feed some data to it. After that we will query to get all the student having grade B:

List studentsList = new List();
studentsList.Add(new Student("Adil", 1, "A"));
studentsList.Add(new Student("Sami", 10, "B"));
studentsList.Add(new Student("Faisal", 100, "B"));
var query = from student in studentsList
            where student.Grade == "B"
            select student;

Printing result in query will be

Sami
Faisal

In short, LINQ to Objects allows us to query in memory objects not just on primitive data types but also on our custom data types and provide an ease to developer for querying data from in memory objects.

MSDN Social Platform Overview

Get an overview of all the new community-driven applications on MSDN, including social bookmarking, forums, and community content.

MSDN Social Platform Overview

N-Tier Vs. Multi-Layered Architecture

Last week I was invited to assist Final Year Project Coordinator at University of Karachi to take viva for final year projects. So I observed one thing that students do not have clear picture between N-tier architecture and multi-layered architecture. So here I write few lines for them, hope that this will improve their understanding.

Layered architecture refers to logical distribution/separation of components like, a rough example will be, separate DLLs for Business Logic Layer(BLL) or Data Access Layer(DAL).

N-Tier refers to physical separation of components either on same machine or across different machines. For example, We have 3-tier architecture with UI on ASP.NET, BLL as WCF service on different server and DAL as WCF service on different layer. UI communicates with BLL and BLL with DAL. Even when there are multiple processes on single machine interaction through some means, let’s say services, it is said to be N-tier architecture.

Hope this will give you better idea. Don’t forget to live it 🙂

Have a good day!

Object Initializers in C# 3.0

C# 3.0 facilitates programmer by providing the feature of Object Initializers for both Named and Anonymous types. Object Initializer let you assign values to any accessible fields or properties without the need to create a explicit constructor. Consider the code below:

private class Student

    public string Name { get; set; }
    public int Age { get; set; }
}

static void SomeMethod()
{
    // Object initializer
    Student stObj= new Student {Name = “Adil”,  Age = 24 };

}

If we notice in the code above, the properties of student are assigned values directly with the use of braces { } around it and comma in between each member. Without object initializer this will be done in the way as shown below:

Student stObj=new Student();
stObj.Name=”Adil”;
stObj.Age= 24;

Again features such as Automatic properties, Implicitly typed local variables and Object Initializer are provided in C# 3.0 specially to support LINQ.