Tuesday 10 September 2013

Example of WCF to Insert,Update,Delete in Gridview using WCF Service in Asp.Net





Description :-

            In this Example we Explain that How to Create WCF Service for Insert,update,Delete Record in gridview.

Here is some link that is very useful for same programming like :-

to show Example of insert,update,delete in gridview using LINQ please click here insert,update,delete using Linq

to show Example of insert,update,delete in gridview using Naming Container please click here Naming Container for insert update Delete in Gridview

to show Example of insert,update,delete in gridview using Modal Popup please click here insert,update,delete in Modal Popup

 to show Example of insert,update,delete in gridview using Stored Procedure please click here insert,update,delete through stored Procedure

  to show Example of insert,update,delete in XML File and bind to Gridview please click here insert,upadte,delete in XML File

  to show Example of insert,update,delete in gridview using Three Tier Architecture please click here Three Tier Architecture For insert,update,Delete


Step 1:- Create the following Table in your sqlserver Database with name poll.


Step 2:- Create the WCF service application follow this steps
           
    Go to Visual Studio
    New-> Select a project->WCF Service Application and give name service and click on ok button.

Step 3:-now three file are automatocally created in solution explorer like
IService.cs
              Service.svc
              Service.svc.cs

Step 4:- For inserting data into the database you need to write the following code in the IService1.cs file which contains the two sections:

    OperationContract
    DataContract

The OperationContract section is used to add service operations and a DataContract is used to add types to the service operations.

Step 5:- now paste the Following code in the Iservice.cs File

  using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Web;

using System.Text;

using System.Data.SqlClient;

using System.Data;



namespace WCFServiceForInsert

{

    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.

    [ServiceContract]

    public interface IService1

    {

        [OperationContract]

        string InsertUserDetails(poll userInfo);



        [OperationContract]

        DataSet  SelectUserDetails();



        [OperationContract]

        bool DeleteUserDetails(poll userInfo);



        [OperationContract]

        DataSet UpdateUserDetails(poll userInfo);



        [OperationContract]

        void UpdateRegistrationTable(poll userInfo);

    }



    // Use a data contract as illustrated in the sample below to add composite types to service operations.

    [DataContract]

    public class poll

    {

        int Id;

        string Name;

        string Question;

        string Salary;

      







        [DataMember]

        public int ID

        {

            get { return Id; }

            set { Id = value; }

        }



        [DataMember]

        public string NAME

        {

            get { return Name; }

            set { Name = value; }

        }

        [DataMember]

        public string QUESTION

        {

            get { return Question; }

            set { Question = value; }

        }

        [DataMember]

        public string SALARY

        {

            get { return Salary; }

            set { Salary = value; }

        }

       

    }

}
  
Step 6:- now paste the Following code in the Service.svc.cs File

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Runtime.Serialization;

    using System.ServiceModel;

    using System.ServiceModel.Web;

    using System.Text;

    using System.Data.SqlClient;

    using System.Data;



    namespace WCFServiceForInsert
    {

        // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.

        public class Service1 : IService1
        {



            public DataSet SelectUserDetails()
            {

                SqlConnection con = new SqlConnection("Data Source=SQLDB;Persist Security Info=True;User ID=Demoh;Password=Demo1@");

                con.Open();

                SqlCommand cmd = new SqlCommand("Select * from poll", con);

                SqlDataAdapter sda = new SqlDataAdapter(cmd);

                DataSet ds = new DataSet();

                sda.Fill(ds);

                cmd.ExecuteNonQuery();

                con.Close();

                return ds;

            }



            public bool DeleteUserDetails(poll userInfo)
            {

                SqlConnection con = new SqlConnection("Data Source=SQLDB;Persist Security Info=True;User ID=Demoh;Password=Demo1@");

                con.Open();

                SqlCommand cmd = new SqlCommand("delete from poll where UserID=@UserID", con);

                cmd.Parameters.AddWithValue("@ID", userInfo.ID);

                cmd.ExecuteNonQuery();

                con.Close();

                return true;

            }



            public DataSet UpdateUserDetails(poll userInfo)
            {

                SqlConnection con = new SqlConnection("Data Source=SQLDB;Persist Security Info=True;User ID=Demoh;Password=Demo1@");

                con.Open();

                SqlCommand cmd = new SqlCommand("select * from poll where UserID=@UserID", con);

                cmd.Parameters.AddWithValue("@ID", userInfo.ID);

                SqlDataAdapter sda = new SqlDataAdapter(cmd);

                DataSet ds = new DataSet();

                sda.Fill(ds);

                cmd.ExecuteNonQuery();

                con.Close();

                return ds;

            }



            public void UpdateRegistrationTable(poll userInfo)
            {



                SqlConnection con = new SqlConnection("Data Source=SQLDB;Persist Security Info=True;User ID=Demoh;Password=Demo1@");

                con.Open();

                SqlCommand cmd = new SqlCommand("update poll set Name=@Name,Question=@Question,Salary=@Salary where Id=@ID", con);

                cmd.Parameters.AddWithValue("@ID", userInfo.ID);

                cmd.Parameters.AddWithValue("@Name", userInfo.NAME);

                cmd.Parameters.AddWithValue("@Question", userInfo.QUESTION);

                cmd.Parameters.AddWithValue("@Salary", userInfo.SALARY);

              

                cmd.ExecuteNonQuery();

                con.Close();

            }



            public string InsertUserDetails(poll userInfo)
            {

                string Message;

                SqlConnection con = new SqlConnection("Data Source=SQLDB;Persist Security Info=True;User ID=Demoh;Password=Demo1@");

                con.Open();

                SqlCommand cmd = new SqlCommand("insert into poll(Name,Question,Salary) values(@Name,@Question,@Salary)", con);

                cmd.Parameters.AddWithValue("@Name", userInfo.NAME);

                cmd.Parameters.AddWithValue("@Question", userInfo.QUESTION);

                cmd.Parameters.AddWithValue("@Salary", userInfo.SALARY);

              

                int result = cmd.ExecuteNonQuery();

                if (result == 1)
                {

                    Message = userInfo.NAME + " Details inserted successfully";

                }

                else
                {

                    Message = userInfo.NAME + " Details not inserted successfully";

                }

                con.Close();

                return Message;

            }

        }

    }


Step 7:- Press F5 to run the service. A WCF Test Client form will be displayed and it will load the service.
Step 8:- Now double-click the InserUserDetails() method under IService1. The InserUserDetails tab will be displayed.
Step 9:- The service was added successfully.

Now open the service in the browser.

Now right-click on the service1.vcs -> open in browser:

Step 9:- Now copy the URL.
http://localhost:2268/Service1.svc

Step 10: Create web Application (Accessing the Service)

Now, you have to create a web site.

    Go to Visual Studio 2010
    New-> Select a website application
    Click OK
Step 11:- Now add a new page to the website:

    Go to the Solution Explorer
    Right-click on the Project name
    Select add new item
    Add new web page and give it a name
    Click OK


Step 12:- When we click on the add the service reference the following window will be opened:
Step 13:- Now paste the above URL in the address and click on the go button.
Click on the Ok Button. Now the reference has been added in the Solution Explorer.
Now create a new website and drag and drop controls onto the aspx page. The aspx code is the following:
using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data;

using ServiceReference1;

using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;




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

    ServiceReference1.Service1Client objServiceClientobjService = new ServiceReference1.Service1Client();

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {

            showdata();

        }

    }



    private void showdata()
    {

        DataSet ds = new DataSet();

        ds = objServiceClientobjService.SelectUserDetails();

        CategoriesGridView.DataSource = ds;

        CategoriesGridView.DataBind();



    }

    protected void Button1_Click(object sender, EventArgs e)
    {

        if (Button1.Text == "Update")
        {

            updateuserdetail();

            txtsalary.Text = string.Empty;
            txtname.Text = string.Empty;
            txtquestion.Text = string.Empty;
          
            Button1.Text = "Submit";

        }

        else
        {

            insertuserdetail();

            showdata();

        }

    }



    private void insertuserdetail()
    {

        UserDetails userInfo = new UserDetails();

        userInfo.Name =txtname.Text

     

        userInfo.Question =  txtsalary.Text;

        userInfo.Question = txtquestion.Text;

        string result = objServiceClientobjService.InsertUserDetails(userInfo);

        LabelMessage.Text = result;

        showdata();

    }



    protected void CategoryButtonDelete_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
    {

        UserDetails userInfo = new UserDetails();

        userInfo.ID = int.Parse(e.CommandArgument.ToString());

        objServiceClientobjService.DeleteUserDetails(userInfo);

        showdata();

    }



    protected void CategoryImageButtonEdit_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
    {



        UserDetails userInfo = new UserDetails();

        userInfo.ID = int.Parse(e.CommandArgument.ToString());

        ViewState["UserId"] = userInfo.ID;

        DataSet ds = new DataSet();

        ds = objServiceClientobjService.UpdateUserDetails(userInfo);



        if (ds.Tables[0].Rows.Count > 0)
        {

            txtname.Text = ds.Tables[0].Rows[0]["Name"].ToString();

            txtquestion.Text = ds.Tables[0].Rows[0]["Question"].ToString();

            txtsalary.Text = ds.Tables[0].Rows[0]["Salary"].ToString();

         

            Button1.Text = "Update";

        }

    }



    private void updateuserdetail()
    {

        UserDetails userInfo = new UserDetails();



        userInfo.UserID = int.Parse(ViewState["Id"].ToString());

        userInfo.Name = txtname.Text;

        userInfo.Question = txtquestion.Text;

        userInfo.Salary = txtsalary.Text;

     

        objServiceClientobjService.UpdateRegistrationTable(userInfo);

        showdata();

    }

}
 

0 comments:

Post a Comment