Friday, December 6, 2013

Simple WCF service example for beginners.

Hi Friends,

Here I will explain what WCF (windows communication foundation) is,and how to implement simple example to understand,How to use WCf Service.

What WCF is ?

Windows Communication Foundation (WCF) is a technology for developing applications based on service-oriented architecture (SOA). WCF is implemented using a set of classes placed on top of the .NET Common Language Runtime (CLR). It addresses the problem of interoperability using .NET for distributed applications.


WCF is entirely based on the .NET framework. It is primarily implemented as a set of classes that correspond to the CLR in the .NET framework. However, WCF allows .NET application developers to build service-oriented applications. The WCF client uses Simple Object Access Protocol (SOAP) to communicate with the server. The client and server are independent of the operating system, hardware and programming platform, and communication takes place at a high level of abstraction.

Creating a simple WCF Service :-


Once you create application you got in solution explorer like below 

Now double click on Iservice1.cs and paste code below

 [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string
SampleMethod(string Name);
    } 






 Now double click on service1.svc and paste code below

public class Service1 : IService1
    {
        public string
SampleMethod(string Name)
        {
            return "Hello " + Name + " Welcome to your first WCF program";
        }
    } 





Know Press F5 and build solution




 Know right click on service1.svc and view in browser and copy url.

Now for calling your first WCF service take another new project.
To call WCF service there are many ways like using console app, windows app and web app but here I am going for console application.

Name it FirstWCFServiceConsole

 
After it in Solution explorer Right-Click on Add References and Click on Add Service refrences.

Window apperes like below paste url which you copies early in service view in browser.


Now paste code in Program.cs like below

ServiceReference1.Service1Client objService = new ServiceReference1.Service1Client();
            Console.WriteLine("Please Enter your Name");
            string Message = objService.SampleMethod(Console.ReadLine());
            Console.WriteLine(Message);
            Console.ReadLine();




 Now open app.config paste copied url in endpoint address="" like below

 
Now the console application



Ajax Cascading Dependent Dropdown list Bind from Database.

Hi Friends,

Here I will explain how to use Cascading dropdownlist with database using asp.net

First of all add three tables like below..

Country



State


City



After this add reference of AjaxControlToolKit.dll and AjaxMin.dll in you solution References like below,remeber both dll file must be added to references.




ON ASPX PAGE :-

Add Code code like below

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>



<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
    </asp:ToolkitScriptManager>
    <div>
        <table>
            <tr>
                <td>
                    Select Country:
                </td>
                <td>
                    <asp:DropDownList ID="ddlcountry" runat="server">
                    </asp:DropDownList>
                    <asp:CascadingDropDown ID="ccdCountry" runat="server" Category="Country" TargetControlID="ddlcountry"
                        PromptText="Select Country" LoadingText="Loading Countries.." ServiceMethod="BindCountryDetails"
                        ServicePath="~/AjaxCascadingDropDown.asmx">
                    </asp:CascadingDropDown>
                </td>
            </tr>
            <tr>
                <td>
                    Select State:
                </td>
                <td>
                    <asp:DropDownList ID="ddlState" runat="server">
                    </asp:DropDownList>
                    <asp:CascadingDropDown ID="ccdState" runat="server" Category="State" ParentControlID="ddlcountry"
                        TargetControlID="ddlState" PromptText="Select State" LoadingText="Loading States.."
                        ServiceMethod="BindStateDetails" ServicePath="~/AjaxCascadingDropDown.asmx">
                    </asp:CascadingDropDown>
                </td>
            </tr>
            <tr>
                <td>
                    Select Region:
                </td>
                <td>
                   <asp:DropDownList ID="ddlCity" runat="server">
                    </asp:DropDownList>
                     <asp:CascadingDropDown ID="ccdCity" runat="server" Category="City" ParentControlID="ddlState"
                        TargetControlID="ddlCity" PromptText="Select City" LoadingText="Loading City.."
                        ServiceMethod="BindCityDetails" ServicePath="~/AjaxCascadingDropDown.asmx">
                    </asp:CascadingDropDown>
                </td>
            </tr>
        </table>
    </div>
    

Now add a webservice in your project and name it  AjaxCascadingDropDown.asmx

Now open web service and paste namespaces like below

using System;
using System.Collections;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Collections.Specialized;
using AjaxControlToolkit;
using System.Configuration;
using System.Data; 


namespace DailyTask
{
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.Web.Script.Services.ScriptService()]
    public class AjaxCascadingDropDown : System.Web.Services.WebService
    {
        private static string strconnection = ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString();
       
        SqlConnection concountry = new SqlConnection(strconnection);
        public AjaxCascadingDropDown()
        {

        }
        [WebMethod]
        public CascadingDropDownNameValue[] BindCountryDetails(string knownCategoryValues, string category)
        {
            concountry.Open();
            SqlCommand cmdcountry = new SqlCommand("select * from task6CountryTable", concountry);
            cmdcountry.ExecuteNonQuery();
            SqlDataAdapter dacountry = new SqlDataAdapter(cmdcountry);
            DataSet dscountry = new DataSet();
            dacountry.Fill(dscountry);
            concountry.Close();
            List<CascadingDropDownNameValue> countrydetails = new List<CascadingDropDownNameValue>();
            foreach (DataRow dtrow in dscountry.Tables[0].Rows)
            {
                string CountryID = dtrow["CountryId"].ToString();
                string CountryName = dtrow["CountryName"].ToString();
                countrydetails.Add(new CascadingDropDownNameValue(CountryName, CountryID));
            }

            return countrydetails.ToArray();
        }



        [WebMethod]
        public CascadingDropDownNameValue[] BindStateDetails(string knownCategoryValues, string category)
        {
            int countryID;
            StringDictionary countrydetails = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
            countryID = Convert.ToInt32(countrydetails["Country"]);
            concountry.Open();
            SqlCommand cmdstate = new SqlCommand("select * from task6StateTable where CountryID=@CountryID", concountry);
            cmdstate.Parameters.AddWithValue("@CountryID", countryID);
            cmdstate.ExecuteNonQuery();
            SqlDataAdapter dastate = new SqlDataAdapter(cmdstate);
            DataSet dsstate = new DataSet();
            dastate.Fill(dsstate);
            concountry.Close();
            List<CascadingDropDownNameValue> statedetails = new List<CascadingDropDownNameValue>();
            foreach (DataRow dtrow in dsstate.Tables[0].Rows)
            {
                string StateID = dtrow["StateID"].ToString();
                string StateName = dtrow["StateName"].ToString();
                statedetails.Add(new CascadingDropDownNameValue(StateName, StateID));
            }
            return statedetails.ToArray();
        }


        [WebMethod]
        public CascadingDropDownNameValue[] BindCityDetails(string knownCategoryValues, string category)
        {
            int stateID;
            StringDictionary statedetails = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
            stateID = Convert.ToInt32(statedetails["State"]);
            concountry.Open();
            SqlCommand cmdcity = new SqlCommand("select * from task6CityTable where StateID=@StateID", concountry);
            cmdcity.Parameters.AddWithValue("@StateID", stateID);
            cmdcity.ExecuteNonQuery();
            SqlDataAdapter dacity = new SqlDataAdapter(cmdcity);
            DataSet dscity = new DataSet();
            dacity.Fill(dscity);
            concountry.Close();
            List<CascadingDropDownNameValue> citydetails= new List<CascadingDropDownNameValue>();
            foreach (DataRow dtrow in dscity.Tables[0].Rows)
            {
                string CityID = dtrow["CityID"].ToString();
                string CityName = dtrow["CityName"].ToString();
                citydetails.Add(new CascadingDropDownNameValue(CityName, CityID));
            }
            return citydetails.ToArray();
        }

    }


In Your Web.Config paste code like below :-

<connectionStrings>
    <add name="ApplicationServices" connectionString="Data Source=10.1.1.1;Initial Catalog=DailyTaskoskar;Persist Security Info=True;User ID=Username;Password=password" providerName="System.Data.SqlClient"/>
   
  </connectionStrings> 


 

 

Export gridview data to Excel in asp.net C# .

Hi Friends,

Here I will explain how to export gridview data to Excel using asp.net in c#.I have one gridview that has filled with user details now I need to export gridview data toexcel . To implement this functionality first we need to design aspx page like this



ON ASPX PAGE :-

<div>
    <asp:ImageButton ID="imgbtnExport" runat="server" BorderColor="White" ToolTip="Export Data" ImageUrl="~/Excel-icon.png"
                                        OnClick="imgbtnExport_Click" />
    <table>
    <tr>
                <td colspan="2">
                    <asp:GridView ID="gvRecords" AutoGenerateColumns="False" runat="server" >
                        <Columns>

<asp:BoundField DataField="Id" HeaderText="Id" HeaderStyle-BackColor="Orange" />
                                                        <asp:BoundField DataField="fullname" HeaderText="Full Name" HeaderStyle-BackColor="Orange" />
                            <asp:BoundField DataField="DOB" HeaderText="DOB" HeaderStyle-BackColor="Orange"/>
                            <asp:BoundField DataField="Gender" HeaderText="Gender" HeaderStyle-BackColor="Orange"/>
                            <asp:BoundField DataField="MobileNo" HeaderText="Mobile No." HeaderStyle-BackColor="Orange"/>
                            <asp:BoundField DataField="Salary" HeaderText="Salary" HeaderStyle-BackColor="Orange"/>
                            <asp:BoundField DataField="Isactive" HeaderText="Isactive" HeaderStyle-BackColor="Orange"/>
                            <asp:TemplateField HeaderText="Remove" HeaderStyle-BackColor="Orange">
                                <ItemTemplate>
                                    <asp:LinkButton ID="Label2" runat="server" >Remove</asp:LinkButton>
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>
                </td>
            </tr>
            </table>
    </div>


ON CODE BEHIND ASPX.CS :-

First of all take your grid view data in viewstate like below..

public void fillDataGrid()
        {
            DataSet ds = new DataSet();
            ds = manager.GetRecords();           
            gvRecords.DataSource = ds.Tables[0];
            ViewState["Export"] = ds.Tables[0];
            gvRecords.DataBind();
        }


protected void imgbtnExport_Click(object sender, ImageClickEventArgs e) // Image Button To Export Grid Recod
        {
            string date = DateTime.Now.ToString("MM-dd-yyyy");

            Response.Clear();
            Response.Buffer = true;

            Response.AddHeader("content-disposition", "attachment;filename=ExcelData.xls");
            Response.Charset = "";

            Response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);

            gvRecords.AllowPaging = false;
            DataTable ds = ViewState["Export"] as DataTable;

            DataGrid dg = new DataGrid();
            dg.HeaderStyle.ForeColor = System.Drawing.Color.Blue;
            dg.DataSource = ds;
            dg.DataBind();
            dg.RenderControl(hw);

            string style = @"<style> .textmode { mso-number-format:\@; } </style>";
            Response.Write(style);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }


Now you can export your grid view data on excel sheet.



Save it and then open.