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