Friday, April 30, 2010

Handling large sets of data from WCF service in Silverlight application

I had the problem of handling data which is coming from my WCF web service to Silverlight application. When data is huge i got communication exception. I have googled on this and found a great article to handle huge amount of data.

Here is a great article by Syed Mehroz Alam. I found it very helpful.

Thursday, April 29, 2010

What is WCF?

 

A WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the world.

A Client is a program that exchanges messages with one or more Endpoints. A Client may also expose an Endpoint to receive Messages from a Service in a duplex message exchange pattern.

Service Endpoint:

A Service Endpoint has an Address, a Binding, and a Contract.

The Endpoint's Address is a network address where the Endpoint resides. The EndpointAddress class represents a WCF Endpoint Address.

The Endpoint's Binding specifies how the Endpoint communicates with the world including things like transport protocol (e.g., TCP, HTTP), encoding (e.g., text, binary), and security requirements (e.g., SSL, SOAP message security). The Binding class represents a WCF Binding.

The Endpoint's Contract specifies what the Endpoint communicates and is essentially a collection of messages organized in operations that have basic Message Exchange Patterns (MEPs) such as one-way, duplex, and request/reply. The ContractDescription class represents a WCF Contract.

The ServiceEndpoint class represents an Endpoint and has an EndpointAddress, a Binding, and a ContractDescription corresponding to the Endpoint's Address, Binding, and Contract, respectively

An EndpointAddress is basically a URI, an Identity, and a collection of optional headers.

An Endpoint's security identity is normally its URI; however, in advanced scenarios the identity can be explicitly set independent of the URI using the Identity address property.

The optional headers are used to provide additional addressing information beyond the Endpoint's URI. For example, address headers are useful for differentiating between multiple Endpoints that share the same address URI.

A Binding has a name, a namespace, and a collection of composable binding elements.
The presence of each binding element describes part of the how of communicating with the Endpoint. The TcpTransportBindingElement indicates that the Endpoint will communicate with the world using TCP as the transport protocol. ReliableSessionBindingElement indicates that the Endpoint uses reliable messaging to provide message delivery assurances. SecurityBindingElement indicates that the Endpoint uses SOAP message security.

For example, the ReliableSessionBindingElement has an Assurances property that specifies the required message delivery assurances, such as none, at least once, at most once, or exactly once.

A WCF Contract is a collection of Operations that specifies what the Endpoint communicates to the outside world. Each operation is a simple message exchange, for example one-way or request/reply message exchange.

The ContractDescription class is used to describe WCF Contracts and their operations. Within a ContractDescription, each Contract operation has a corresponding OperationDescription that describes aspects of the operation such as whether the operation is one-way or request/reply. Each OperationDescription also describes the messages that make up the operation using a collection of MessageDescriptions.

A ContractDescription is usually created from an interface or class that defines the Contract using the WCF programming model. This type is annotated with ServiceContractAttribute and its methods that correspond to Endpoint Operations are annotated with OperationContractAttribute. You can also build a ContractDescription by hand without starting with a CLR type annotated with attributes.

A duplex Contract defines two logical sets of operations: A set that the Service exposes for the Client to call and a set that the Client exposes for the Service to call. The programming model for defining a duplex Contract is to split each set in a separate type (each type must be a class or an interface) and annotate the contract that represents the service's operations with ServiceContractAttribute, referencing the contract that defines the client (or callback) operations. In addition, ContractDescription contains a reference to each of the types thereby grouping them into one duplex Contract.

Similar to Bindings, each Contract has a Name and Namespace that uniquely identify it in the Service's metadata.

Each Contract also has a collection of ContractBehaviors that are modules that modify or extend the contract's behavior. The next section covers behaviors in more detail.

For more details, visit this link at MSDN.

Debugging Silverlight applications

How to debug silverlight applications? Few of us will be having this problem and the issues is “Debugger not getting hit in the Silverlight project “. Here is the answer its pretty simple solution for this.

All Silverlight applications will have a hosting application which will be an ASP.NET web application or web site...

1. Right click the ASP.NET web application – -> Properties

2. In the properties window, select the tab Start Options.

3. In the debugger’s section, check the Silverlight checkbox.

image

4. Clik OK on the project properties window.

5. Hit F5. Now you will be able to debug the Silverlight project.

Hope this helps.

Wednesday, April 28, 2010

Key Press Event For Silverlight Textbox

This how we need to do to capture Key Press Event for Sliverlight text box. Attach KeyDown Event in XMAL code in MainPage.xaml file.

 

<TextBox x:Name="customer_name"

KeyDown="customer_name_KeyDown" VerticalAlignment="Top" TextWrapping="Wrap" FontSize="10.667" Width="120" Height="22"/>


In the codebehind you can check with the Key value like example shown below in MainPage.xaml.cs file.

private void customer_name_KeyDown(object sender, KeyEventArgs e)
        {
         
            if (e.Key == Key.Enter)
            {
                e.Handled = true;
            }
            else
            {
                e.Handled = false;
            }
        }
 

Unable to start debugging. The Silverlight managed debugging package isn’t installed.

If you installed latest version of Silverlight (Silverlight 4), it may break the your current silverlight development environment. After in the Silverlight 4 installation, if you try to debug any Silverlight 3 project, you will get a message from Visual Studio 2008, saying “Unable to start debugging. The Silverlight managed debugging package isn’t installed.”

image

To fix this error, install the Silverlight Developer Run time. You can get it from here : http://go.microsoft.com/fwlink/?LinkID=188039.

It worked for me. Hope this helps for you.

Monday, April 26, 2010

Deploying WCF Service in IIS : no svc MIME Type

I have started My First SilverLight application with WCF Service. When i want to deploy on IIS, i got this error saying no MIME type for this extension SVC not found. It is happening because this MIME type is not registered IIS.

Exception Details:

Server Error in Application “Default Web Site/MyFirstSLApp”
HTTP Error 404.3 – Not Found
Description: The page you are requesting cannot be served because of the Multipurpose Internet Mail Extensions (MIME) map policy that is configured on the Web server. The page you requested has a file name extension that is not recognized, and is not allowed.
Error Code: 0×80070032

I tried IIS MIME Types and I couldn’t found an application mapping for SVC file. After doing some goggling I found the fix.  You can resolve this using WCF Installation utility which comes with .Net Framework 3.0. Run the command prompt as Administrator, go to the Windows Communication Foundation folder in c:\Windows\Microsoft.NET\Framework\v3.0\ folder. Execute the servicemodelreg.exe with -i or /i switch.

wcf 

After the installation this try reloading the Page. It will fix this issue.

Wednesday, April 07, 2010

GridView Export from ASP.NET

Common method for Exporting gird content 

#region Methods : ExportGridView & PrepareControlForExport
    /// <summary>
    /// Purpose : To Export GridView in Excel format.
    /// </summary>
    /// <param name="strFileName">Execl File name</param>
    /// <param name="gv">Grid View</param>
    /// <param name="isRemove">If false, wont check the remove column</param>
    /// <param name="arrayList">List of columns to hide {1,2,3}</param>
    /// <param name="removeColumn">Column to remove</param>
    public void ExportGridView(string strFileName, GridView gv, bool isRemove, ArrayList arrayList)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader(
            "content-disposition", string.Format("attachment; filename={0}", strFileName));
        HttpContext.Current.Response.ContentType = "application/ms-excel";

        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);

        Table tableExport = new Table();
        // Setting line borders to the exported grid
        tableExport.GridLines = GridLines.Both;

        if (isRemove == false)
        {
            if (gv.HeaderRow != null)
            {
                this.PrepareControlForExport(gv.HeaderRow);
                tableExport.Rows.Add(gv.HeaderRow);
            }
            foreach (GridViewRow row in gv.Rows)
            {
                this.PrepareControlForExport(row);
                tableExport.Rows.Add(row);
            }
            if (gv.FooterRow != null)
            {
                this.PrepareControlForExport(gv.FooterRow);
                tableExport.Rows.Add(gv.FooterRow);
            }

        }
        else
        {
            if (arrayList.Count > 0)
            {
                    if (gv.HeaderRow != null)
                    {
                        this.PrepareControlForExport(gv.HeaderRow);
                        tableExport.Rows.Add(gv.HeaderRow);
                        for (int removeColumn = 0; removeColumn < arrayList.Count; removeColumn++)
                        {
                            gv.HeaderRow.Cells.Remove(gv.HeaderRow.Cells[Int32.Parse(arrayList[removeColumn].ToString())]);
                        }
                    }
                    foreach (GridViewRow row in gv.Rows)
                    {
                        this.PrepareControlForExport(row);
                        for (int removeColumn = 0; removeColumn < arrayList.Count; removeColumn++)
                        {
                            row.Cells.Remove(row.Cells[Int32.Parse(arrayList[removeColumn].ToString())]);
                        }
                        tableExport.Rows.Add(row);
                    }
                    if (gv.FooterRow != null)
                    {
                        this.PrepareControlForExport(gv.FooterRow);
                        tableExport.Rows.Add(gv.FooterRow);
                        for (int removeColumn = 0; removeColumn < arrayList.Count; removeColumn++)
                        {
                            gv.FooterRow.Cells.Remove(gv.FooterRow.Cells[Int32.Parse(arrayList[removeColumn].ToString())]);
                        }
                    }
            }
        }

        tableExport.RenderControl(htw);
        HttpContext.Current.Response.Write(sw.ToString().Trim());
        HttpContext.Current.Response.End();

    }

    /// <summary>
    /// Prepaing the control for export
    /// Customize your controls depening on your logic    ///
    /// </summary>
    /// <param name="control"></param>
    private void PrepareControlForExport(Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            Control current = control.Controls[i];
            if (current is LinkButton)
            {
                control.Controls.Remove(current);
                if ((current as LinkButton).Style["display"] != "none" && (current as LinkButton).Visible)
                {
                    control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text.Trim()));
                }
            }
            else if (current is ImageButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText.Trim()));
            }
            else if (current is HyperLink)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text.Trim()));
            }
            else if (current is DropDownList)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text.Trim()));
            }
            else if (current is CheckBox)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
            }
            else if (current is HtmlAnchor)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as HtmlAnchor).InnerText.Trim()));
            }
            else if (current is Label)
            {
                control.Controls.Remove(current);
                if ((current as Label).Style["display"] != "none" && (current as Label).Visible)
                {
                    control.Controls.AddAt(i, new LiteralControl((current as Label).Text.Trim()));
                }
            }

            if (current.HasControls())
            {
                this.PrepareControlForExport(current);
            }
        }
    }
    #endregion Methods : ExportGridView & PrepareControlForExport

 

Sample code to call code behind

   ArrayList list = new ArrayList();
            DraftsGridView.AllowPaging = false;
            BindDrafts("StartDateTime", ASCENDING);
         // Add list of columns that are to be hidden. If you not need any columns
        //then just send list object without adding any and set the third parameter to false
            list.Add(3);
            common.ExportGridView("Drafts.xls", DraftsGridView, true, list);