Thursday, June 21, 2012

Web services vs WCF (Windows Communication Foundation) services

When we are talking about WCF and Web Services, are we talking about the same thing? The answer is NO. Today I will be explain the differences between these two and the advantages that WCF has over Web services.

ASP.NET provides .NET Framework class libraries and tools for building Web services, as well as facilities for hosting these services within Internet Information Services (IIS) while WCF provides .NET Framework class libraries, tools and hosting facilities for enabling software entities to communicate using any protocols, including those used by Web services.

WCF supports more protocols for transporting messages than Web services. Web services only support sending messages using the HTTP. WCF supports sending messages using HTTP, as well as the TCP, Named Pipes, and Microsoft Message Queuing (MSMQ). Most importantly, WCF can be extended to support additional transport protocols.

Since Web Services use standard XML, they are platform-independent and language-independent. They don't care about the consuming application as long as they are calling the Web services over HTTP. WCF can be hosted only under the Windows environment, but it can be consumed by clients of different languages and different platforms.

Another significant thing is a WCF service can have one or more WCF endpoints, so one address for each end point. But a Web service can have only one address at one point at a time.

For more information,
   Migrating ASP.NET Web Services to WCF
   Multiple endpoints -WCF

Happy Coding.

Regards,
Jaliya

Monday, June 4, 2012

Asynchronous Programming and Callback Methods with Delegates in C#

My previous post was about Delegates in C# and today I thought of writing about one nice technique which is available with Delegates, and that is "Asynchronous Programming". In one of my previous posts, I wrote about Asynchronous Programming with C# 5.0 and that is with "async" modifier and "await" operator. 

Using Delegates we can call a synchronous method in an asynchronous manner and Callback methods are used to notify the caller, when an asynchronous work is completed. First let's get an idea on how these synchronous and asynchronous methods works.

When we call a synchronous method it will get executed on the same thread as the caller. But what happens here is, caller thread gets blocked while the called method is active. When we call a method in an asynchronous way, the .NET framework obtains a thread from the thread pool for the method invocation and delivers the in parameters passed by the calling code. The asynchronous thread can then run the method in parallel to the calling thread. Here what happens is caller thread is not blocked. The call returns immediately to the caller. If the asynchronous method returns some value, the calling thread must be able to handle it. The .NET asynchronous feature supports two mechanisms: that calling thread can either ask for the results, or the asynchronous method can deliver the results to the calling thread when the results are ready.

Delegate's do this asynchronous call invocation using delegate's BeginInvoke method.
First we have to define a delegate with the same signature as the method we want to call. The common language runtime automatically defines BeginInvoke and EndInvoke methods for this delegate, with the appropriate signatures. If a callback method has been specified in the call to the BeginInvoke method, the callback method is called when the target method ends. In the callback method, the EndInvoke method obtains the return value and any input/output or output-only parameters. If no callback method is specified when calling BeginInvoke, EndInvoke can be called from the thread that called BeginInvoke.

I think it's better if we go by examples.

Let's take the following method under the class i have created named "MyClass".
public class MyClass
{
    public string MyMethod(string s)
    {
        Thread.Sleep(5000);
        return "Hello" + s;
    }
}
I have a public method, which will return a string and accepts a string. Then I am creating a delegate for this method.
public delegate string MyDelegate(string s);
Then I am creating my delegate object.
MyClass oMyClass = new MyClass();
MyDelegate oMyDelegate = new MyDelegate(oMyClass.MyMethod);
Now I am all done for calling the method asynchronously. As I have told you, the CLR automatically defines a BeginInvoke method for this delegate object which would have a signature like this.
IAsyncResult oMyDelegate.BeginInvoke(string s, AsyncCallback callback, Object @object);
In here, the first parameter is the methods parameter. The second parameter is an AsyncCallback delegate that references a method to be called when the asynchronous call completes. The third parameter is a user-defined object that passes information into the callback method.

Let's take a complete example.
using System;
using System.Threading;

namespace MyDelegateExample
{
    public delegate string MyDelegate(string s);

    class Program
    {
        static void Main(string[] args)
        {
            MyClass oMyClass = new MyClass();
            MyDelegate oMyDelegate = new MyDelegate(oMyClass.MyMethod);
            Console.WriteLine("Going to call the method Asynchronously.");
            oMyDelegate.BeginInvoke("Jaliya", new AsyncCallback(oMyClass.MyCallbackMethod), oMyDelegate);
            Console.WriteLine("Back on Main.");
            Thread.Sleep(15000);
        }
    }

    public class MyClass
    {
        public string MyMethod(string s)
        {
            Thread.Sleep(5000);
            return "Hello " + s;
        }

        // call back method to capture results
        public void MyCallbackMethod(IAsyncResult iar)
        {
            // cast the state object back to the delegate type
            MyDelegate del = (MyDelegate)iar.AsyncState;

            // call EndInvoke on the delegate to get the results
            string result = del.EndInvoke(iar);

            // display the results
            Console.WriteLine("Delegate returned result: {0}", result);
            Console.WriteLine("Asynchronous Call Completed.");
        }
    }
}

Output :

Output
In here what happens is in my BeginInvoke call, I have mentioned my Callback method. My main program will continue running in parallel and when the asynchronous call is completed, it will execute the "MyCallbackMethod". In that method, I have called the EndInvoke method to retrieve the results of the asynchronous call. I have put a thread sleep in my Main to keep the program running. So I can see the output from my asynchronous call.

Let's take this example.
using System;
using System.Threading;

namespace MyDelegateExample
{
    public delegate string MyDelegate(string s);

    class Program
    {
        static void Main(string[] args)
        {
            MyClass oMyClass = new MyClass();
            MyDelegate oMyDelegate = new MyDelegate(oMyClass.MyMethod);
            Console.WriteLine("Going to call the method Asynchronously.");
            IAsyncResult IAsyncResult = oMyDelegate.BeginInvoke("Jaliya", null, null);
            Console.WriteLine("Back on Main.");
            IAsyncResult.AsyncWaitHandle.WaitOne();
            string result = oMyDelegate.EndInvoke(IAsyncResult);
            Console.WriteLine(result);
            Console.ReadLine();        
        }
    }

    public class MyClass
    {
        public string MyMethod(string s)
        {
            Thread.Sleep(5000);
            return "Hello " + s;
        }
    }
}

Output :

Output

The difference here is there is no callback method.
AsyncResult.AsyncWaitHandle.WaitOne();
will hold the Main from executing further until asynchronous call completes. After that completes only it will move executing forward.

I hope you all got a good understanding in how Asynchronous Programming and Callback Methods works with Delegates.

Appreciate your feedback.

Happy Coding.

Regards,
Jaliya

Saturday, May 26, 2012

An Introduction to Delegates in C#

If you are familiar with Function Pointers in C or C++ and if you are wondering is there something similar to Function Pointers in C#, Of course there is. It's Delegates. Delegates in one of the nicest techniques in C#, but some find hard to understand the real beauty behind it. So thought to write an Introduction about delegates in C#.

Basically a delegate is a type that references a method or methods. A delegate defines a method signature, and it has the capability of referencing to a methods/methods which has the same method signature as in the delegate. When you instantiate a delegate, you can associate its instance with any method with a compatible signature. Then you can invoke the method through the delegate instance. What really happens here is delegate encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

Because of this behavior, delegates gives us many advantages. One thing is you can pass methods as arguments to other methods. Second is since we are using delegate to invoke the method, it will hide the method from the caller. Another nice advantage would be, using delegates we can call methods asynchronously.

Now let's see delegates in action. First, this is how we define delegates.
public delegate void MyDelegate(string s);
What this delegate means is, it has the capability to encapsulate any method that takes one string value and returns no value. Always remember delegates only has the capability to refer methods in which return type matches delegates return type and parameters matches delegates parameters.

Now let's take this simple but full example.
namespace MyDelegateApplication
{
    public delegate void MyDelegate(string s);

    class Program
    {
        static void Main(string[] args)
        {
            MyClass oMyClass = new MyClass();
            MyDelegate oMyDelegate = new MyDelegate(oMyClass.MyMethod);
            oMyDelegate("I am called through a Delegate.");
        }
    }

    public class MyClass
    {
        public void MyMethod(string s)
        {
            Console.WriteLine(s);
            Console.ReadLine();
        }
    }
}
Output :

calling a method through adelegate

In here I have defined a namespace level delegate, so it as accessible from all the classes in namespace. I have created two classes here to make it easy to understand. In "MyClass", I have wrote a method in which method signature is same as the delegate. Then from my Main method, I have created an instance of "MyClass", so I can access it's methods. Then I am creating an instance of "MyDelegate", and I am passing the method which I need to invoke through "MyDelegate". Then I am invoking my method through the delegate. It's simple as that.

Multicasting


Multicasting is, as I mentioned before delegates has the capability to refer more than one method at a time. A multicast delegate maintains a list of functions that will be called when the delegate is invoked. We can add or remove the pointing methods of delegate using "+" and "-" operators. To demonstrate the delegates multicasting, I will just modify the above example as follows.
namespace MyDelegateApplication
{
    public delegate void MyDelegate(string s);

    class Program
    {
        static void Main(string[] args)
        {
            MyClass oMyClass = new MyClass();
            MyDelegate oMyDelegate = null;
            oMyDelegate += new MyDelegate(oMyClass.MyFirstMethod);
            oMyDelegate += new MyDelegate(oMyClass.MySecondMethod);
            oMyDelegate("I am called through a Delegate.");
        }
    }

    public class MyClass
    {
        public void MyFirstMethod(string s)
        {
            Console.WriteLine(string.Format("{0}-First Method", s));
            Console.ReadLine();
        }

        public void MySecondMethod(string s)
        {
            Console.WriteLine(string.Format("{0}-Second Method", s));
            Console.ReadLine();
        }
    }
}
Output :

Multicasting
So that's the basics of delegates in C#. Hope you all got found this post helpful.

Happy Coding.

Regards,
Jaliya

Wednesday, May 16, 2012

Accessing Report Server using Report Server Web Service - Microsoft SQL Server 2008R2

Today I am going to write about how to access SQL Server Report Server through Report Server Web service. You can access all the full functionality of the report server through this Report Server Web service. The Report Server Web service is an XML Web service with a SOAP API. It uses SOAP over HTTP and acts as a communications interface between client programs and the report server.

The Microsoft SQL Server 2008R2 Report Server Web service provides two endpoints, one is for report management and the other one is for report execution.
  1. ReportService2010
    • The ReportService2010 endpoint contains methods for managing objects in a Report Server in either native or SharePoint integrated mode. The WSDL for this endpoint is accessed through  http://server/reportserver/ReportService2010.asmx?wsdl.
  2. ReportExecution2005
    • The ReportExecution2005 endpoint allows developers to programmatically process and render reports in a Report Server. The WSDL for this endpoint is accessed through  http://server/reportserver/ReportExecution2005.asmx?wsdl.
Previous versions of Microsoft SQL Servers' has several versions of Report Server Web service endpoints. For example ReportService2005 and ReportService2006. But ReportService2005 and ReportService2006 endpoints are deprecated in SQL Server 2008 R2. The ReportService2010 endpoint includes the functionalities of both endpoints and contains additional management features.

Now, I will move into how to access Report Server using Report Server Web Service. I have created sample web site and in the Default.aspx page I have put a single button. First what I would do is, I will add a Service Reference to Report Server Web Service and the endpoint I am going to use is ReportService2010.

I will right click on my Web Site Project and will click on Add Service Reference.

Add Service Reference
In here, I have put http://server/reportserver/ReportService2010.asmx as address, I did not add ?wsdl to the end of the address, because both are valid formats.

Now if you observe the Web.config file, you will see that following part is added.
<system.serviceModel>
  <bindings>
    <basicHttpBinding>
      <binding name="ReportingService2010Soap" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
        <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
        <security mode="None">
          <transport clientCredentialType="None" proxyCredentialType="None" realm=""/>
          <message clientCredentialType="UserName" algorithmSuite="Default"/>
        </security>
      </binding>
    </basicHttpBinding>
  </bindings>
  <client>
    <endpoint address="http://server/ReportServer/ReportService2010.asmx" binding="basicHttpBinding" bindingConfiguration="ReportingService2010Soap" contract="ReportService2010.ReportingService2010Soap" name="ReportingService2010Soap"/>
  </client>
</system.serviceModel>
Now in my button click event I am writing following code.
using System.Net;
using ReportService2010;

protected void btnListChildren_Click(object sender, EventArgs e)
{
    NetworkCredential clientCredentials = new NetworkCredential("username", "password", "domain");
    ReportService2010.ReportingService2010SoapClient client = new ReportService2010.ReportingService2010SoapClient();
    client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
    client.ClientCredentials.Windows.ClientCredential = clientCredentials;
    client.Open();
    TrustedUserHeader t = new TrustedUserHeader();
    CatalogItem[] items;
    // I need to list of children of a specified folder.
    ServerInfoHeader oServerInfoHeader = client.ListChildren(t, "/", true, out items);
    foreach (var item in items)
    {
        // I can access any properties of item
    }
}
Now again in my Web.config file I need to do some modifications. If not I might get this type of error when I am executing my button click event.
Request is unauthorized.
I am modifying the Web.config file as follows.
<security mode="TransportCredentialOnly">
  <transport clientCredentialType="Ntlm" proxyCredentialType="None" realm=""/>
  <message clientCredentialType="UserName" algorithmSuite="Default"/>
</security>
That's all. Now when I run the Web Site I can get the list of children in the parent folder through the Report Server Web Service. Through this Web Service we can access all the full functionality of the report server. Isn't it great.

Happy Coding.

Regards,
Jaliya

Tuesday, May 15, 2012

ASP.NET GridView Row Edit mode

It's great to have CRUD operations in a single place and ASP.NET GridView provides this feature in a nice way. Without much pre writing I will just start off with the topic.

I have a GridView in my page and I have named it "GridViewUsers". First I will load values to a DataSet and Bind my GridView's Data Source to that DataSet in Page Load event. Please note that in here I will be writing only the necessary codes.
using System;
using System.Web.UI.WebControls;
using System.Data;

dbConnection odbConnection = new dbConnection(); // calling my dbConnection class

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DataSet ds = GetAllUsers();
        gridViewUsers.DataSource = ds;
        gridViewUsers.DataBind();
    }
}

private DataSet GetAllUsers()
{
    DataSet ds = new DataSet();
    try
    {
        string selectQuery = "SELECT USER_ID,FIRST_NAME,LAST_NAME,GENDER From USERS";
        ds = odbConnection.ExecuteSelectQuery(selectQuery);
    }

    catch (Exception ex)
    {
        throw ex;
    }
    return ds;
}
Now I will  modify some properties in the GridView from the aspx file.
<asp:GridView ID="GridViewUsers" runat="server"
     AutoGenerateColumns="False"
     GridLines="None"
     AllowPaging="True">
</asp:GridView>
I have put,
AutoGenerateColumns="False"
here, because I need to write column names I want to show in the GridView. If I put,
AutoGenerateColumns="True"
I don't need to write any custom code and all the columns I have selected in my query will be appeared as it is in my GridView. Ok, Now what my target is, I will have some rows in my GridView and initially it will be read only. And in each each row, there will be a single column which will be used to modify the selected row. It will have a single button in read only mode which is "Edit", And when I click on Edit, the row will change into Edit mode. The editable fields of the row will change into edit mode and the "Edit" button will disappear. Instead of  "Edit" button, three more buttons will come to the picture which will be "Update","Delete" and "Cancel".

I hope you all got the target well, let's start achieving it.

So basically we will have two modes and some custom controls. In GridView, to define custom controls with other columns we are using "TemplateField" which is like a place holder. Under "TemplateField", I will have two properties which are "ItemTemplate" and "EditItemTemplate". "ItemTemplate" property is used to control the appearance of a data item and "EditItemTemplate" property is used to control the appearance of a data item in Edit mode. So here is my complete code for the GridView.
<asp:GridView ID="gridViewUsers" runat="server"
     AutoGenerateColumns="False"
     AllowPaging="True" Height="134px" Width="536px" 
     onrowediting="gridViewUsers_RowEditing"
     onrowcancelingedit="gridViewUsers_RowCancelingEdit"
     onrowdeleting="gridViewUsers_RowDeleting"
     onrowupdating="gridViewUsers_RowUpdating">

     <Columns>
          <asp:TemplateField HeaderText="User ID">
               <ItemTemplate>
                    <asp:Label runat="server" ID="lblUserID" Text='<%# Eval("USER_ID") %>' />
               </ItemTemplate>
          </asp:TemplateField>

          <asp:TemplateField HeaderText="First Name" >
               <ItemTemplate>
                    <asp:Label ID="lblFirstName" runat="server" Text='<%# Eval("FIRST_NAME") %>' />
               </ItemTemplate>
               <EditItemTemplate>
                    <asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FIRST_NAME") %>' />
               </EditItemTemplate>
          </asp:TemplateField>

          <asp:TemplateField HeaderText="Last Name" >
               <ItemTemplate>
                    <asp:Label ID="lblLastName" runat="server" Text='<%# Eval("LAST_NAME") %>' />
               </ItemTemplate>
               <EditItemTemplate>
                    <asp:TextBox ID="txtLastName" runat="server" Text='<%# Eval("LAST_NAME") %>' />
               </EditItemTemplate>
          </asp:TemplateField>

          <asp:TemplateField HeaderText="Action">
               <ItemTemplate>
                    <asp:ImageButton ID="btnEdit" runat="server" Text="Edit" CommandName="Edit" ImageUrl="~/images/iconEdit.png" ToolTip="Edit" AutoPostBack="true" />
               </ItemTemplate>
               <EditItemTemplate>
                    <asp:ImageButton ID="btnUpdate" runat="server" Text="Update" CommandName="Update" ImageUrl="~/images/iconUpdate.png" ToolTip="Update" AutoPostBack="true" />
                    <asp:ImageButton ID="btnDelete" runat="server" Text="Delete" CommandName="Delete" ImageUrl="~/images/iconDelete.png" ToolTip="Delete" AutoPostBack="true" />
                    <asp:ImageButton ID="btnCancel" runat="server" Text="Cancel" CommandName="Cancel" ImageUrl="~/images/iconCancel.png" ToolTip="Cancel" AutoPostBack="true" />
               </EditItemTemplate>
          </asp:TemplateField>
     </Columns>
</asp:GridView>
So here what I have done is, UserID is the primary key. So in it there is no Edit mode. For all other columns there is a "EdiItemTemplate". And in "ItemTemplate", I have used a Label to display the value. Because it is read only. And in "EdiItemTemplate", I have used a TextBox to display value, because it should be editable. In here last "TemplateField" is the column which will contain controls for modifying the row. In "ItemTemplate", it will contain a single button which will trigger GridView EDIT command and in "EdiItemTemplate", it will contain three buttons which will trigger GridView UPDATE, DELETE and CANCEL commands. I have used image buttons here to make the UI bit nicer.

Now here is my code behind code file. First it is gridViewUsers_RowEditing event.
protected void gridViewUsers_RowEditing(object sender, GridViewEditEventArgs e)
{
    gridViewUsers.EditIndex = e.NewEditIndex;
    BindGrid();
}
In here GridViewEditEventArgs will give the row number I am editing by it's NewEditIndex property. Then I am assigning that row number to GridView's EditIndex property which will put the appropriate row into the Edit Mode. Then I am calling my custom method which I am going to write in few minutes and it will bind the GridView again.
Then it's gridViewUsers_RowUpdating event and gridViewUsers_RowDeleting event.
protected void gridViewUsers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    Label userID = (Label)gridViewUsers.Rows[e.RowIndex].FindControl("lblUserID");
    TextBox txtFirstName = (TextBox)gridViewUsers.Rows[e.RowIndex].FindControl("txtFirstName");
    TextBox txtLastName = (TextBox)gridViewUsers.Rows[e.RowIndex].FindControl("txtLastName");
        
    string updateQuery = "update query";

    gridViewUsers.EditIndex = -1;
    BindGrid("UPDATE", updateQuery);
}
protected void gridViewUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    Label UserID = (Label)gridViewUsers.Rows[e.RowIndex].FindControl("lblUserID");
    string deleteQuery = "delete query";

    gridViewUsers.EditIndex = -1;
    BindGrid("DELETE", deleteQuery);
}
In these two events, first line is to get the primary key's value of the current row item being modified.
protected void gridViewUsers_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    gridViewUsers.EditIndex = -1;
    BindGrid();
}
Then my BindGrid method. I have two optional parameters here which will get query type and the query. If the query type is "UPDATE" or "DELETE", it will execute the query and in the finally block it will bind the GridView.
private void BindGrid(string queryType = "default", string query = "default")
{
    DataSet ds = null;

    try
    {
        if (queryType == "UPDATE" || queryType == "DELETE")
        {
            odbConnection.ExecQuery(query);
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        string selectQuery = "SELECT USER_ID,FIRST_NAME,LAST_NAME,GENDER From USERS";

        using (ds = oDBConnection.SelectQuery(selectQuery))
        {
            gridViewUsers.DataSource = ds;
            gridViewUsers.DataBind();
        }
    }
}

So that's all about ASP.NET GridView Row Edit mode. This is what you will get at the end.

gridViewUsers

gridViewUsers Edit Mode

Happy Coding.

Regards,
Jaliya

Wednesday, May 9, 2012

Installed Windows 8 Consumer Preview

Today I have installed Windows 8 Consumer Preview and I must say that it is one of the greatest windows experiences in my life. Windows 8 Consumer Preview is a total different operating system when compared to previous Windows operating systems and it is a really amazing.

Windows 8 Consumer Preview

What is Windows 8 Consumer Preview

On 29 February 2012, Microsoft released Windows 8 Consumer Preview, the beta version of Windows 8, build 8250. For the first time since Windows 95, the Start button is no longer present on the taskbar, though the Start screen is still triggered by clicking the bottom-left corner of the screen and by clicking Start in the Charm.

The Windows 8 Consumer Preview is a follow-up of the Windows 8 Developer Preview, which was released last September. While the Windows 8 Developer Preview was mainly aimed for developers and IT professionals, the Windows 8 Consumer Preview is aimed for all kind of users including IT professionals to end users.

The difference between the two is, the Consumer Preview includes more features such as wall-to-wall web browsing, full touch screen support, and of course the new look of the Windows 8 UI, making the preview closer to final product expected to come out later this year.

Installing Windows 8 Consumer Preview

Installing Windows 8 Consumer Preview is pretty much straight forward, one thing to note is if you are using VMware and if you try to install Windows 8 Consumer Preview on a version prior to VMware Workstation 8.0, you will get this error "HAL_INITIALIZATION_FAILED". Well I have faced this on VMware 7.0. But it was a clean installation on VMware Workstation 8.0.

HAL_INITIALIZATION_FAILED

Another fatal error you can possibly face, is "DPC WATCHDOG VIOLATION". The cause of this error as I found out is Windows 8 Consumer Preview can't communicate with one of the hardware devices connected your computer. For me it was my internet dongle, and first place I have configured my virtual machine's network as a Bridged connection with my physical computer. Then when Windows 8 is finalizing the installation, when readying it's devices it threw me this error. 

Second time I configured  my virtual machine's network as NAT with my physical computer. Then there was no error.

DPC WATCHDOG VIOLATION

So after successful installation, for a moment I really wanted to leave Windows 7 behind and move into Windows 8 even though it's still in beta stage. I am pretty sure with upcoming Windows 8 and with Visual Studio 11, the whole world will experience amazing applications that they have never seen before.

Happy Coding.

Regards,
Jaliya

Monday, April 23, 2012

Programming WCF - Creating a custom WCF Service and a Host

My last post was about Introduction to Windows Communication Foundation. Today I thought about writing something about how to do some nice programming using WCF and I will show you how to create a custom WCF Service and a Service Host using C#. I assume that you all have some knowledge of WCF programming, so I will be not explaining every single line of code here.

First I will start off by creating class library project and I will name it "WCFClassLibrary". In that project, I will create a class named "MyWcfService" and I will also create an Interface which is "IMyWcfService". Now in my "WCFClassLibrary", I will add a reference to the "System.ServiceModel.dll" and I am now going to modify my "IMyWcfService" interface.

I will be using "System.ServiceModel.dll" in my interface and since interfaces that represents WCF contracts needs to have [ServiceContract] attribute, I am modifying the interface as follows.
using System.ServiceModel;
namespace WCFClassLibrary
{
    [ServiceContract]
    interface IMyWcfService
    {
        [OperationContract]
        string MyTestMethod(string sHelloWorld);
    }
}
Then in my "MyWcfService" class, I am going to implement the IMyWcfService interface.
namespace WCFClassLibrary
{
    public class MyWcfService : IMyWcfService
    {
        public string MyTestMethod(string sHelloWorld)
        {
            return sHelloWorld;
        }
    }
}
Now I am done with implementing the service. Next what I have to do is implement the host application to host my service. For that I will create a console application. For that I will add a new Console Application project and I will name it "MyWcfHostConsoleApplication". I will add a reference to the "System.ServiceModel.dll" and "WCFClassLibrary.dll" project. Then I will add a Application configuration file and it's name is "App.config". So it's time modify the "App.config" file. Within,
<configuration></configuration>
I will start writing following code.
<system.serviceModel>
    <services>
        <service name="WCFClassLibrary.MyWcfService">
            <endpoint address="" binding="basicHttpBinding" contract="WCFClassLibrary.IMyWcfService">
            </endpoint>

            <host>
                <baseAddresses>
                    <add baseAddress="http://localhost:8080/MyWcfService"/>
                </baseAddresses>
            </host>
        </service>
    </services>
</system.serviceModel>
Now, I have to write code for hosting my service from inside my Main method. For that I will modify my Main method as follows.
using System;
using System.ServiceModel;
using WCFClassLibrary;

namespace MyWcfHostConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ServiceHost serviceHost = new ServiceHost(typeof(MyWcfService)))
            {
                serviceHost.Open();
                Console.ReadLine();
            }
        }
    }
}
Now when I type "http://localhost:8080/MyWcfService" and hit enter in by browser, what I will see is this,

Metadata publising for this service is currently disabled.

You will see that "Metadata  publishing for this service us currently disabled.". To enable Metadata  publishing what you will have to do is again modify the "App.config " as follows.
<system.serviceModel>
    <services>
        <service name="WCFClassLibrary.MyWcfService" behaviorConfiguration="MyWcfServiceMEXBehavior">
            <endpoint address="" binding="basicHttpBinding" contract="WCFClassLibrary.IMyWcfService">
            </endpoint>

            <!--MEX endpoint-->
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange">
            </endpoint>

            <host>
                <baseAddresses>
                    <add baseAddress="http://localhost:8080/MyWcfService"/>
                </baseAddresses>
            </host>
        </service>
    </services>

    <!--A behavior definition for MEX-->
    <behaviors>
        <serviceBehaviors>
            <behavior name="MyWcfServiceMEXBehavior">
                <serviceMetadata httpGetEnabled="True"/>
            </behavior>
        </serviceBehaviors>
    </behaviors>
</system.serviceModel>
Now again when I host and I type "http://localhost:8080/MyWcfService" and hit enter in by browser, I can see this.

MyWcfService
That's all. Now I can add a Service Reference to this service from my client applications and I can consume this service.

Appreciate your feedback.

Happy Coding.

Regards,
Jaliya

Sunday, April 22, 2012

Introduction to Windows Communication Foundation

Today I am going to write about Windows Communication Foundation (WCF). I am pretty sure you all must have used WCF services already in your applications to build  the application communication. Since WCF is a topic of itself I will be only covering the basics here and it's up for you to discover the inner nice things which are in topics I am covering here.

Windows Communication Foundation (WCF) code named "Indigo" is an API which was introduced with .NET 3.0 and it is specifically designed for the process of building distributed systems.

A Distributed system can be two networked computers or even two executables in same computer that needs to exchange data. Let's call these two ends a client and a service computer. So these client and service computers sometimes can be running same operating system using the same programming language or may be different.

Prior to .NET 3.0 there were several distributed APIs used by windows software developers.
  • DCOM
  • COM+/Enterprise Services
  • MSMQ(Microsoft Message Queuing)
  • .NET Remoting
  • XML Web Services

XML Web Services

XML Web Services are what we used before WCF come to the picture. Web services are components on a Web server that a client application can call by making HTTP requests across the Web. Unlike traditional brower-based web applications, a web services provides a way to expose the functionality of remote components using standard web protocols.

The initial release of .NET has been released with the "System.Web.Services" namespaces with superior support for XML Web Services. In most cases the programmer just had to apply [WebMethod] attribute to each public method which he needs to expose to outside world.

These Web Services encodes it's data in simple XML and can be accessed using simple HTTP. Of course, XML Web Services is not a perfect distributed API for in-house applications where you could use a TCP based protocol and binary based formatting of data.

Windows Communication Foundation

WCF is a distributed API represented primarily by "System.ServiceModel" namespace. Using WCF, you can expose services to callers using wide variety of techniques. For example, if you build an in-house application where all connected machines are windows based, you can use various TCP protocols to ensure the fastest possible performance. You can also expose this same service with the XML Web Service based protocol to allow external callers to leverage its functionality, regardless of the programming language or the operating system.

The Basic Composition of a WCF Application

WCF applications mainly contains three main assemblies.
  1. WCF Service assembly - This dll contains the classes and interfaces that represent the overall functionality that we want to expose to external callers.
  2. WCF service host - This is the entity that hosts the service assembly.
  3. WCF client - This is the application that consumes the service through an intervening proxy.

The ABC's of WCF

The hosts and clients communicate with each other through these ABC's which I am going explain in a second.
  • Address - Describes the location of the service.
  • Binding - WCF ships with a many different bindings that specify network protocols, encoding mechanisms, and transport layer.
  • Contract - Provides a description of each method exposed from the WCF service.

     WCF Contracts

Understanding the role of a contract is the key to building a WCF service. A contract is a standard way of describing what a service can do. Meanwhile, it is platform independent. In WCF there are 4 types of contracts,
  1. Service Contract
  2. Data Contract
  3. Fault Contract
  4. Message Contract

     WCF Bindings

Bindings specify how a Windows Communication Foundation (WCF) service endpoint communicates with other endpoints.


     WCF Address

Once we have establish the contracts and bindings, final stage is to specify the address for the WCF service. From a high level, WCF addresses can specify the following bits of information.
  • Scheme - Transport protocol.
  • MachineName - The full qualified domain of the machine.
  • Port - This is optional in many cases, for example the default for HTTP binding is port 80.
  • Path - The path to the WCF service.
So the address would be the in the format of,
Scheme://<MachineName>[:Port]/Path

     WCF Endpoints

All communication with a Windows Communication Foundation (WCF) service occurs through the endpoints of the service.


So that's the basics of some theoretical things in WCF. If you got all these things hard to understand, try apply these with some practical programming of WCF. I am pretty sure you will be fine then.

Appreciate your feedback.

Happy Coding.

Regards,
Jaliya

Sunday, April 15, 2012

Installed Microsoft Lync Server 2010

Last week for the first time in my life I have successfully installed and configured Microsoft Lync Server 2010. Lync was not at all my subject, but it was a pretty nice experience. I must say Thank You to one of my good old friend for helping me to make it happen. Thanks Kosala Kuruppu.

Happy Coding.

Regards,
Jaliya

Tuesday, April 3, 2012

Visual Studio Application Lifecycle Management(ALM)

Visual Studio ALM or Visual Studio Application Lifecycle Management is a collection of integrated software development tools developed by Microsoft. These tools include IDEs, testing tools, source control, work items, collaboration, metrics, and reporting tools.

If you consider Visual Studio editions, there are mainly four versions of Visual Studio. Visual Studio Test Professional, Visual Studio Professional, Visual Studio Premium and Visual Studio Ultimate.

Visual Studio Test Professional is mainly for Quality Assuarance guys and there is nothing interesing for developers there. Visual Studio Professional is the most basic edition among the three developer editions. Average powered edition is Visual Studio Premium. If you have Visual Studio Ultimate, then you have like you have got everything. It is the most powered, most featured Visual Studio edition you can ever have.

You can use Visual Studio ALM features in Visual Studio Premium or Visual Studio Ultimate in combination with Visual Studio Team Foundation Server. And the sad thing is Visual Studio Test Professional and Visual Studio Professional is not supported for Visual Studio ALM.

What is Visual Studio Team Foundation Server

Microsoft Visual Studio Team Foundation Server (TFS) is the collaboration platform at the core of the Visual Studio solution for application lifecycle management. TFS is mainly responsible for source control, data collection, reporting, and project tracking, and is intended for collaborative software development.

What we can do with Visual Studio ALM
  • Manage application's lifecycle by using the suite of tools in Visual Studio Premium and Visual Studio Ultimate in combination with Visual Studio Team Foundation Server.
  • Better understand customer needs and more effectively design, implement, and deploy code.
  • Plan and track the project. Enact processes and monitor their quality of the team.
  • Design functionality, either on top of existing assets or from scratch, by using architectural diagrams.
  • Write, unit test, debug, analyze, and profile the application by using tools that are integrated with the rest of the application lifecycle so that team can understand how their progress contributes to the project. Use version control to manage the source code and other files.
  • Build the application by using an integrated build system so that the team can ensure that quality gates have been met and verify that requirements have been fulfilled in each build.
  • Test the application by running manual or automated tests, including performance and stress tests. Manage testing systematically so that the team knows the software quality on any given day.
  • Deploy into virtual environments to enable more sophisticated development and testing.

Team Foundation Server & Visual Studio

Team Foundation Server & Visual Studio
For more information visit,

Happy Coding.

Regards,
Jaliya