Tuesday, 1 April 2014

CRUD Operation using WCF in Asp.Net

Ans:-
Here insert data into DB and Get Data from DB using WCF web services. In below UI of the application..


For this create one Website as->File->New Website->Give Website Name as WcfTesting->ok
                                              ->select Wcf Services from new template
                                              ->automatically 4 files will create in Solution Explorer
                                             ->as I) Service.cs and IService.cs in App_Code folder
                                                     II)App_Data folder
                                                     III)Service and Web.config file.

Then write code in

IService.cs:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

// NOTE: If you change the interface name "IService" here, you must also update the reference to "IService" in Web.config.
[ServiceContract]
public interface IService
{

[OperationContract]
    List<TestDetails> GetTestData();

[OperationContract]
    string InsertGetTestData(TestDetails testInfo);

    [OperationContract]
    string DeleteGetTestData(int id);

    [OperationContract]
    string UpdateGetTestData(TestDetails testInfo);

// TODO: Add your service operations here
}

// Use a data contract as illustrated in the sample below to add composite types to service operations.
public class TestDetails
{
    int id;
    string name = string.Empty;
    string descrptn = string.Empty;
    
    [DataMember]
    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    [DataMember]
    public int Id
    {
        get { return id; }
        set { id = value; }
    }
    [DataMember]
    public string Descrptn
    {
        get { return descrptn; }
        set { descrptn = value; }
    }

}

Web.Config:-

<connectionStrings>
<add name="conStr" connectionString="server=.;database=subsdb;user id=sa;pwd=123"/></connectionStrings>

Service.cs:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

// NOTE: If you change the class name "Service" here, you must also update the reference to "Service" in Web.config and in the associated .svc file.
public class Service : IService
{
    private string strConnection = ConfigurationManager.ConnectionStrings["conStr"].ToString();
    public List<TestDetails> GetTestData()
    {
        List<TestDetails> testdetails = new List<TestDetails>();
        using (SqlConnection con = new SqlConnection(strConnection))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("select * from test", con);

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    TestDetails testInfo = new TestDetails();
                    testInfo.Id = Convert.ToInt32(dt.Rows[i]["id"].ToString());
                    testInfo.Name = dt.Rows[i]["name"].ToString();
                    testInfo.Descrptn = dt.Rows[i]["descrptn"].ToString();

                    testdetails.Add(testInfo);
                }
            }
            con.Close();
        }
        return testdetails;
    }
    public string InsertGetTestData(TestDetails testInfo)
    {
        string strMessage = string.Empty;
        using (SqlConnection con = new SqlConnection(strConnection))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("insert into test(id,name,descrptn) values(@id,@name,@descrptn)", con);
            cmd.Parameters.AddWithValue("@id", testInfo.Id);
            cmd.Parameters.AddWithValue("@name", testInfo.Name);
            cmd.Parameters.AddWithValue("@descrptn", testInfo.Descrptn);

            int result = cmd.ExecuteNonQuery();
            if (result == 1)
            {
                strMessage = testInfo.Id + " Details inserted successfully";
            }
            else
            {
                strMessage = testInfo.Name + " Details not inserted successfully";
            }
            con.Close();
        }
        return strMessage;
    }
    public string DeleteGetTestData(int id)
    {
        string strMessage = string.Empty;
        using (SqlConnection con = new SqlConnection(strConnection))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("delete from test where id=@id", con);
            cmd.Parameters.AddWithValue("@id", id);

            int result = cmd.ExecuteNonQuery();
            if (result == 1)
            {
                strMessage = id + " Details Deleted successfully";
            }
            else
            {
                strMessage = id + " Details not Deleted successfully";
            }
            con.Close();
        }
        return strMessage;
    }
    public string UpdateGetTestData(TestDetails testInfo)
    {
        string strMessage = string.Empty;
        using (SqlConnection con = new SqlConnection(strConnection))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("update test set name=@name,descrptn=@descrptn where id=@id", con);
            cmd.Parameters.AddWithValue("@id", testInfo.Id);
            cmd.Parameters.AddWithValue("@name", testInfo.Name);
            cmd.Parameters.AddWithValue("@descrptn", testInfo.Descrptn);

            int result = cmd.ExecuteNonQuery();
            if (result == 1)
            {
                strMessage = testInfo.Id + " Details updated successfully";
            }
            else
            {
                strMessage = testInfo.Name + " Details not updated successfully";
            }
            con.Close();
        }
        return strMessage;
    }

}

After Completion upto this Build this Website and then run and copy that url For consuming this services to another Web application/Console application...

So i am creating another Website here to consume above WCF services.

For this create one Website as->File->New Website->Give Website Name as Website1->ok
                                              ->add new Item->In here add New Web Page from new template
                                                as(Default.aspx)

For consuming above services into this website,Right click and select Add Service References and then Paste above copied link and then clicked go.....and then give service name as....ServiceReference1.And then add this ServiceReference1 to Namespace.

Then write code in

Default.aspx:-

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Call Wcf Service to the Website Page</title>
</head>
<body>
    <form id="form1" runat="server">
   <div>
<table align="center">
<tr>
<td colspan="2" align="center">
<b>Test Table(id,name,desrptn) Details</b>
</td>
</tr>
<tr>
<td>
ID:
</td>
<td>
<asp:TextBox ID="txtId" runat="server"/>
</td>
</tr>
<tr>
<td>
Name:
</td>
<td>
<asp:TextBox ID="txtName" runat="server"/>
</td>
</tr>
<tr>
<td>
Desc:
</td>
<td>
<asp:TextBox ID="txtDesc" runat="server"/>
</td>
</tr>

<tr>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Save" onclick="btnSubmit_Click" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="lblResult" runat="server"/>
</td>
</tr>
<tr>
<td colspan="2">
<asp:GridView runat="server" ID="gvDetails" AutoGenerateColumns="false" DataKeyNames="id"
        AutoGenerateDeleteButton="True" onrowdeleting="gvDetails_RowDeleting" 
        AutoGenerateEditButton="True" onrowupdating="gvDetails_RowUpdating" 
        onrowcancelingedit="gvDetails_RowCancelingEdit" 
        onrowediting="gvDetails_RowEditing">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField HeaderText="ID" DataField="id" />
                
                <asp:TemplateField HeaderText="Name"  SortExpression="name">
                <EditItemTemplate>
                    <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblName" runat="server" Text='<%# Bind("name") %>'></asp:Label>
                </ItemTemplate>
              </asp:TemplateField>
            
              <asp:TemplateField HeaderText="Description"  SortExpression="descrptn">
                <EditItemTemplate>
                    <asp:TextBox ID="txtDesc" runat="server" Text='<%# Bind("descrptn") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblDesc" runat="server" Text='<%# Bind("descrptn") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

Default.aspx.cs:-

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using ServiceReference1;

public partial class _Default : System.Web.UI.Page
{

    ServiceReference1.ServiceClient proxy = new ServiceClient();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindTestDetails();
        }
    }
    void BindTestDetails()
    {
        gvDetails.DataSource = proxy.GetTestData();
        gvDetails.DataBind();
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        TestDetails testInfo = new TestDetails();
        testInfo.Id = Convert.ToInt32(txtId.Text);
        testInfo.Name = txtName.Text;
        testInfo.Descrptn = txtDesc.Text;

        string result = proxy.InsertGetTestData(testInfo);
        lblResult.Text = result;
        BindTestDetails();
        txtId.Text = string.Empty;
        txtName.Text = string.Empty;
        txtDesc.Text = string.Empty;
        }
    protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int testid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["id"].ToString());
        string result = proxy.DeleteGetTestData(testid);
        lblResult.Text = result;
        BindTestDetails();

    }
    protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        TestDetails testInfo = new TestDetails();
        testInfo.Id = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["id"].ToString());

        GridViewRow objGVR = (GridViewRow)gvDetails.Rows[e.RowIndex];

        TextBox txtobjName = (TextBox)objGVR.FindControl("txtName");
        TextBox txtObjDesc = (TextBox)objGVR.FindControl("txtDesc");

        testInfo.Name = txtobjName.Text;
        testInfo.Descrptn = txtObjDesc.Text;

        string result = proxy.UpdateGetTestData(testInfo);
        lblResult.Text = result;
        gvDetails.EditIndex = -1;
        BindTestDetails();
    }
    protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gvDetails.EditIndex = e.NewEditIndex;
        BindTestDetails();
    }
    protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gvDetails.EditIndex = -1;
        BindTestDetails();
    }
    
}


Create Table:-

create table test(id int,name varchar(30),descrptn varchar(30))



1 comment:

  1. Is Aoki no Tengoku (Toto Site) - AveP.org
    From 토토카지노사이트 the creator, Tojo.net 온라인카지노 is the website site where you can play games and read your favourite Tojo.net romanized art.

    ReplyDelete