INSERT,UPDATE,DELETE IN WINDOWS COMMUNICATION FOUNDATION

INSERT,UPDATE,DELETE IN WCF

Visual studio 2008àfileànewàprojectàwcfservicesà

WCF SERVICES HAVE TWO PAGES:
1.SERVICE.CS
2.ISERVICE

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;



public class Service : IService
{
    SqlConnection con = new SqlConnection("Data Source=PRIYA\\sqlexpress;Initial Catalog=master;Integrated Security=True");
        public List<UserDetails> GetUserDetails(string Username)
    {
        List<UserDetails> userdetails = new List<UserDetails>();
                SqlConnection con = new SqlConnection("Data Source=PRIYA\\sqlexpress;Initial Catalog=master;Integrated Security=True");

        {
            con.Open();
            SqlCommand cmd = new SqlCommand("select * from UserInformation", con);
           
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dtresult = new DataTable();
            da.Fill(dtresult);
            if (dtresult.Rows.Count > 0)
            {
                for (int i = 0; i < dtresult.Rows.Count; i++)
                {
                    UserDetails userInfo = new UserDetails();
                    userInfo.UserName = dtresult.Rows[i]["UserName"].ToString();
                    userInfo.FirstName = dtresult.Rows[i]["FirstName"].ToString();
                    userInfo.LastName = dtresult.Rows[i]["LastName"].ToString();
                    userInfo.Location = dtresult.Rows[i]["Location"].ToString();
                    userdetails.Add(userInfo);
                }
            }
            con.Close();
        }
        return userdetails;
    }
    public string InsertUserDetails(UserDetails userInfo)
    {
        string strMessage = string.Empty;
       
        SqlConnection con = new SqlConnection("Data Source=PRIYA\\sqlexpress;Initial Catalog=master;Integrated Security=True");

        {
            con.Open();
            SqlCommand cmd = new SqlCommand("insert into UserInformation(UserName,FirstName,LastName,Location) values(@Name,@FName,@LName,@Location)", con);
            cmd.Parameters.AddWithValue("@Name", userInfo.UserName);
            cmd.Parameters.AddWithValue("@FName", userInfo.FirstName);
            cmd.Parameters.AddWithValue("@LName", userInfo.LastName);
            cmd.Parameters.AddWithValue("@Location", userInfo.Location);
            int result = cmd.ExecuteNonQuery();
            if (result == 1)
            {
                strMessage = userInfo.UserName + " Details inserted successfully";
            }
            else
            {
                strMessage = userInfo.UserName + " Details not inserted successfully";
            }
            con.Close();
        }
        return strMessage;
    }
    public string UpdateUserDetails(UserDetails userIn)
    {
        string strMessage = string.Empty;
       
        SqlConnection con = new SqlConnection("Data Source=PRIYA\\sqlexpress;Initial Catalog=master;Integrated Security=True");

        {
            con.Open();
            SqlCommand cmd1 = new SqlCommand("update UserInformation set FirstName=@FName,LastName=@LName,Location=@Location where UserName= @Name", con);
            cmd1.Parameters.AddWithValue("@Name", userIn.UserName);
            cmd1.Parameters.AddWithValue("@FName", userIn.FirstName);
            cmd1.Parameters.AddWithValue("@LName", userIn.LastName);
            cmd1.Parameters.AddWithValue("@Location", userIn.Location);
            int result = cmd1.ExecuteNonQuery();
            if (result == 1)
            {
                strMessage = userIn.UserName + " Details Updated successfully";
            }
            else
            {
                strMessage = userIn.UserName + " Details not Notupdated successfully";
            }
            con.Close();
        }
        return strMessage;
    }


    public string SelectUserDetails(UserDetails usersel)
    {
        string strMessage = string.Empty;
       
        SqlConnection con = new SqlConnection("Data Source=PRIYA\\sqlexpress;Initial Catalog=master;Integrated Security=True");

        {
            con.Open();
            SqlCommand cmd1 = new SqlCommand("select * from Userinformation where UserName= @Name", con);
           
            SqlDataReader dr = cmd1.ExecuteReader();
            dr.Read();

            usersel.FirstName = dr[1].ToString();
            usersel.LastName = dr[2].ToString();
            usersel.Location = dr[3].ToString();
           
               
            con.Close();
        }
        return strMessage;
    }

    }

 ANOTHER PAGE

ISERVICE.CS


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

 [ServiceContract]
public interface IService
{
    [OperationContract]
    List<UserDetails> GetUserDetails(string Username);

    [OperationContract]
    string InsertUserDetails(UserDetails userInfo);

    [OperationContract]
    string UpdateUserDetails(UserDetails userIn);

    [OperationContract]
    string SelectUserDetails(UserDetails usersel);

  

   
}

// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class UserDetails
{
    string username = string.Empty;
    string firstname = string.Empty;
    string lastname = string.Empty;
    string location = string.Empty;

    [DataMember]
    public string UserName
    {
        get { return username; }
        set { username = value; }
    }
    [DataMember]
    public string FirstName
    {
        get { return firstname; }
        set { firstname = value; }
    }
    [DataMember]
    public string LastName
    {
        get { return lastname; }
        set { lastname = value; }
    }
    [DataMember]
    public string Location
    {
        get { return location; }
        set { location = value; }
    }
}
RUN THE APPLICATION:


COPY THE URL : http://localhost:3811/Service1.svc



NEXT CREATE WEB APPLICATION:

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 id="Head1" runat="server">
<title>Untitled Page</title>
<style type="text/css">
.style1 {
height: 26px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table align="center">
<tr>
<td colspan="2" align="center">
<b>User Registration</b>
</td>
</tr>
<tr>
<td>
UserName:
</td>
<td>
<asp:TextBox ID="txtUserName" runat="server"/>
</td>
</tr>
<tr>
<td>
FirstName:
</td>
<td>
<asp:TextBox ID="txtfname" runat="server"/>
</td>
</tr>
<tr>
<td>
LastName:
</td>
<td>
<asp:TextBox ID="txtlname" runat="server"/>
</td>
</tr>
<tr>
<td class="style1">
Location:
</td>
<td class="style1">
<asp:TextBox ID="txtlocation" runat="server"/>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Update" />
    <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="select" />
</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">
<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="UserName" DataField="UserName" />
<asp:BoundField HeaderText="FirstName" DataField="FirstName" />
<asp:BoundField HeaderText="LastName" DataField="LastName" />
<asp:BoundField HeaderText="Location" DataField="Location" />
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

OPEN SOLUTION WINDOW---->ADD SERVICE REFERENCES

PASTE THE URL





DEFAULT.ASPX.CS(CODE BEHIND PAGE)
CODE BEHIND PAGE:
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 ServiceReference1; //THIS IS YOUR SERVICE REFERENCE
using System.Collections.Generic;

public partial class _Default : System.Web.UI.Page
{
    ServiceReference1.ServiceClient objService = new ServiceReference1.ServiceClient();
//YOU CALL THE SERVICE REFERNCE.
    //ServiceReference1.ServiceClient objService = new ServiceClient();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindUserDetails();
        }
    }
    protected void BindUserDetails()
    {
        IList<UserDetails> objUserDetails = new List<UserDetails>();
        objUserDetails = objService.GetUserDetails("");
        gvDetails.DataSource = objUserDetails;
       
        gvDetails.DataBind();
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        UserDetails userInfo = new UserDetails();
        userInfo.UserName = txtUserName.Text;
        userInfo.FirstName = txtfname.Text;
        userInfo.LastName = txtlname.Text;
        userInfo.Location = txtlocation.Text;
        string result = objService.InsertUserDetails(userInfo);
        lblResult.Text = result;
        BindUserDetails();
        txtUserName.Text = string.Empty;
        txtfname.Text = string.Empty;
        txtlname.Text = string.Empty;
        txtlocation.Text = string.Empty;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        UserDetails userIn = new UserDetails();
        userIn.UserName = txtUserName.Text;
        userIn.FirstName = txtfname.Text;
        userIn.LastName = txtlname.Text;
        userIn.Location = txtlocation.Text;
        string result = objService.UpdateUserDetails(userIn);
        lblResult.Text = result;
        BindUserDetails();
        txtUserName.Text = string.Empty;
        txtfname.Text = string.Empty;
        txtlname.Text = string.Empty;
        txtlocation.Text = string.Empty;
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        UserDetails usersel = new UserDetails();
        //userIn.UserName = txtUserName.Text;
        usersel.FirstName = txtfname.Text;
        usersel.LastName = txtlname.Text;
        usersel.Location = txtlocation.Text;
        string result = objService.SelectUserDetails(usersel);
        BindUserDetails();
    }
}
CHANGE WEBCONFIG(END POINTS)
WEB.CONFIG:
<?xml version="1.0"?>
<configuration>


    <configSections>
      <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
        <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
          <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
          <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
            <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere" />
            <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
            <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
            <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
          </sectionGroup>
        </sectionGroup>
      </sectionGroup>
    </configSections


    <appSettings/>
  <connectionStrings >
    <add name="dbconnection" connectionString="Data Source=PRIYA\\sqlexpress;Initial Catalog=master;Integrated Security=True"/>


  </connectionStrings>
 
    <system.web>
        -->
        <compilation debug="true">

          <assemblies>
            <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
            <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
            <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
          </assemblies>

        </compilation>
        <authentication mode="Windows" />
       
       

      <pages>
        <controls>
          <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        </controls>
      </pages>

      <httpHandlers>
        <remove verb="*" path="*.asmx"/>
        <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
      </httpHandlers>
      <httpModules>
        <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </httpModules>


    </system.web>

    <system.codedom>
      <compilers>
        <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4"
                  type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
          <providerOption name="CompilerVersion" value="v3.5"/>
          <providerOption name="WarnAsError" value="false"/>
        </compiler>
        <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4"
                  type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
          <providerOption name="CompilerVersion" value="v3.5"/>
          <providerOption name="OptionInfer" value="true"/>
          <providerOption name="WarnAsError" value="false"/>
        </compiler>
      </compilers>
    </system.codedom>

    <system.webServer>
      <validation validateIntegratedModeConfiguration="false"/>
      <modules>
        <add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </modules>
      <handlers>
        <remove name="WebServiceHandlerFactory-Integrated"/>
        <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode"
             type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode"
             type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </handlers>
    </system.webServer>


  <system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="WSHttpBinding_IService" closeTimeout="00:01:00"
          openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
          bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
          maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text"
          textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
            maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <reliableSession ordered="true" inactivityTimeout="00:10:00"
            enabled="false" />
          <security mode="Message">
            <transport clientCredentialType="Windows" proxyCredentialType="None"
              realm="" />
            <message clientCredentialType="Windows" negotiateServiceCredential="true"
              algorithmSuite="Default" establishSecurityContext="true" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:3541/WCFService1/Service.svc"
        binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService"
        contract="ServiceReference1.IService" name="WSHttpBinding_IService">
        <identity>
          <dns value="localhost" />
        </identity>
      </endpoint>
    </client>
    <services>
      <service name="Service" behaviorConfiguration="ServiceBehavior">
        <!-- Service Endpoints -->
        <endpoint address="" binding="wsHttpBinding" contract="IService">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <serviceThrottling maxConcurrentCalls="65536" maxConcurrentSessions="65536" maxConcurrentInstances="65536" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>