Introduction: In previous WCF article i explained What is Wcf Service and How to create and consume Wcf Services in asp.net . In this article i am going to demonstrate with example how to bind, save/insert, edit, update and delete from gridview from sql server database using wcf service in asp.net.
So basically this article will demonstrate with example the following:
- Step by step procedure/example to create wcf service
- How to consume/access wcf service
- How to bind/Load/Fill gridview from Sql server database using wcf service
- How to perform insert, edit, update and delete operation on gridview using wcf service
Click on image to enlarge |
Description: In some of my previous articles i clearly demonstrated with examples How to Bind,Save,Edit,Update,Cancel,Delete,Paging example in GridView in asp.net and How to create crystal reports in visual studio 2010 using asp.net and How to Convert Rupees,Currency or Numbers to Words in Asp.net C# and How to Get age in years,months,days,hours and seconds from DOB in asp.net C#,Vb.Net.
Here in this article first i will create the wcf service having bind, save, edit, update and delete methods then i will create the consuming application that will consume these methods.
Implementation: So let's start an application to understand.
- Open Visual Studio -> Go to File menu -> New -> Project -> Select WCF Service Application and give it name "WcfServiceDemo" as shown in image below.
Click on image to enlarge |
- Two files IService1.cs and Service1.svc will be added under the project in the solution explorer. Service1.svc.cs file will be opened by default.
- Before moving further we need to create the database and table from where data is to be retrieved and saved.
Click on image to enlarge |
- So create the database in sql server and name it "MyDataBase" or whatever you want. In this database create a table as shown in image on the right side and name it "UserReg". Note: UserRegId column is set to Primary key and Identity specification is set to yes with Identity increment and Identity seed equal to 1.
- In the web.config file create the connection string as:
<connectionStrings>
<add name="ConStr" connectionString="Data Source=LocalServer;Initial Catalog=MyDataBase;Integrated Security=True"/>
</connectionStrings>
- Now open the Iservices1.cs file and remove all the default code and declare the Service Contracts, Operation Contracts and Data Contracts:
First include the following namespaces:
using System.Data;
using System.Data.SqlClient;
namespace WcfServiceDemo
{
[ServiceContract]
public interface IService1
{
[OperationContract]
string InsertUserRegDetails(RegDetails regdet);
[OperationContract]
DataSet GetUserRegDetails();
[OperationContract]
DataSet FetchUpdatedRecords(RegDetails regdet);
[OperationContract]
string UpdateUserRegDetails(RegDetails regdet);
[OperationContract]
bool DeleteUserRegDetails(RegDetails regdet);
}
// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class RegDetails
{
int p_UserRegId;
string p_FirstName = string.Empty;
string p_LastName = string.Empty;
string p_EmailId = string.Empty;
string p_pwd = string.Empty;
string p_contact = string.Empty;
[DataMember]
public int UserRegId
{
get { return p_UserRegId; }
set { p_UserRegId = value; }
}
[DataMember]
public string FirstName
{
get { return p_FirstName; }
set { p_FirstName = value; }
}
[DataMember]
public string LastName
{
get { return p_LastName; }
set { p_LastName = value; }
}
[DataMember]
public string EmailId
{
get { return p_EmailId; }
set { p_EmailId = value; }
}
[DataMember]
public string Password
{
get { return p_pwd; }
set { p_pwd = value; }
}
[DataMember]
public string ContactNo
{
get { return p_contact; }
set { p_contact = value; }
}
}
}
- Now open the Service.svc.cs file and remove the default code and define the methods declared in the IService1.cs above.
First include the following namespaces:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace WcfServiceDemo
{
public class Service1 : IService1
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);
public string InsertUserRegDetails(RegDetails regdet)
{
string Status;
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("insert into UserReg(FirstName,LastName,EmailId,Password,ContactNo) values(@FirstName,@LastName,@EmailId,@Password,@ContactNo)", con);
cmd.Parameters.AddWithValue("@FirstName", regdet.FirstName);
cmd.Parameters.AddWithValue("@LastName", regdet.LastName);
cmd.Parameters.AddWithValue("@EmailId", regdet.EmailId);
cmd.Parameters.AddWithValue("@Password", regdet.Password);
cmd.Parameters.AddWithValue("@ContactNo", regdet.ContactNo);
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
Status = regdet.FirstName + " " + regdet.LastName + " registered successfully";
}
else
{
Status = regdet.FirstName + " " + regdet.LastName + " could not be registered";
}
con.Close();
return Status;
}
public DataSet GetUserRegDetails()
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("Select * from UserReg", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
cmd.ExecuteNonQuery();
con.Close();
return ds;
}
public DataSet FetchUpdatedRecords(RegDetails regdet)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("select * from UserReg where UserRegId=@UserRegId", con);
cmd.Parameters.AddWithValue("@UserRegId", regdet.UserRegId);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
cmd.ExecuteNonQuery();
con.Close();
return ds;
}
public string UpdateUserRegDetails(RegDetails regdet)
{
string Status;
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("update UserReg set FirstName=@FirstName,LastName=@LastName,EmailId=@EmailId, Password=@Password,ContactNo=@ContactNo where UserRegId=@UserRegId", con);
cmd.Parameters.AddWithValue("@UserRegId", regdet.UserRegId);
cmd.Parameters.AddWithValue("@FirstName", regdet.FirstName);
cmd.Parameters.AddWithValue("@LastName", regdet.LastName);
cmd.Parameters.AddWithValue("@EmailId", regdet.EmailId);
cmd.Parameters.AddWithValue("@Password", regdet.Password);
cmd.Parameters.AddWithValue("@ContactNo", regdet.ContactNo);
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
Status = "Record updated successfully";
}
else
{
Status = "Record could not be updated";
}
con.Close();
return Status;
}
public bool DeleteUserRegDetails(RegDetails regdet)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("delete from UserReg where UserRegId=@UserRegId", con);
cmd.Parameters.AddWithValue("@UserRegId", regdet.UserRegId);
cmd.ExecuteNonQuery();
con.Close();
return true;
}
}
}
- Now in the solutions explorer Right click on Service1.svc and click on "View in Browser" option as shown in image below:
Click on image to enlarge |
- It will appear as shown in image below:
- Copy the Service URL. It will be used while consuming this wcf service. In our case http://localhost:1237/Service1.svc. as shown in image above.
Note: Keep it running to test because our wcf service is not running online.
How to create consuming application
- Now let’s create a Consuming application that will consume/access the methods from the wcf service to retrieve and insert data into database.
- Open visual studio ->go to File menu-> New ->Select Website and name it "WcfServiceDemoConsumingApp" as shown in image below:
- Now Go to Website menu -> Add new Item -> Web form as shown in image below:
Click on image to enlarge |
- Now to consume the methods of the wcf service we need to add the service reference. So In solution explorer right click on project -> Add Service Reference as shown in image below.
Click on the image to enlarge |
- A new window will appear as shown in image below:
Click on image to enlarge |
- Paste the copied Service url i.e. http://localhost:1237/Service1.svc as shown in image below.
Click on image to enlarge |
- Click on GO. Expand the Services and click on Iservice1. It will list all the functions/methods created in Services. ServiceReference1 is the name of the namespace. You can also change it but I have kept it default. Click on Ok button. Reference has been added to the solution explorer.
- Now it's time to design the page. In the <Form> tag of design page(default.aspx) design the web page as:
<div>
<fieldset style="width:500px">
<legend>Enter Registration Details </legend>
<table >
<tr>
<td>
First Name</td>
<td>
<asp:TextBox ID="txtFirstName" runat="server" style="margin-right: 59px"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Last Name</td>
<td>
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Email Id</td>
<td>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Password</td>
<td>
<asp:TextBox ID="txtPwd" runat="server" TextMode="Password"
onprerender="txtPwd_PreRender"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Contact Number</td>
<td>
<asp:TextBox ID="txtContact" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td class="style1">
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel"
onclick="btnCancel_Click" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Label ID="lblStatus" runat="server" Text="" style="color: #FF3300"></asp:Label>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td colspan="2">
<asp:GridView ID="grdWcfTest" runat="server" AutoGenerateColumns="False"
DataKeyNames="UserRegId" CellPadding="5" ForeColor="#333333">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Name" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#Eval("FirstName") + " " + Eval("LastName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email Id" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblEmail" runat="server" Text='<%#Eval("EmailId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Password" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblPwd" runat="server" Text='<%#Eval("Password") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Contact No." ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblContact" runat="server" Text='<%#Eval("ContactNo") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:ImageButton ID="imgBtn" runat="server" CausesValidation="false" CommandArgument='<%#Eval("UserRegId") %>'
OnCommand="imgEdit_Command" ImageUrl="~/Images/edit.png"
ToolTip="Edit" />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:ImageButton ID="imgDel" runat="server" CausesValidation="false" CommandArgument='<%#Eval("UserRegId") %>'
CommandName="Delete" OnCommand="imgDel_Command" ImageUrl="~/Images/delete.png"
ToolTip="Delete" OnClientClick="return confirm('Are you sure you want to delete?')" />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
</td>
</tr>
</table>
</fieldset>
</div>
Note: I have used two images edit.png and delete.png in this example to show in gridview for editing and deleting operation and placed that in Images folder. You can search on google for similar images and add a folder in root directory of your project and name it Images. add the images in this folder.
- In the code file (default.aspx.cs) write the code as:
First include the following namespaces:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using ServiceReference1;
then write the code as:
ServiceReference1.Service1Client obj = new ServiceReference1.Service1Client();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindRegRecordsInGrid();
}
}
private void BindRegRecordsInGrid()
{
DataSet ds = new DataSet();
ds = obj.GetUserRegDetails();
grdWcfTest.DataSource = ds;
grdWcfTest.DataBind();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (btnSubmit.Text == "Update")
{
UpdateRegDetails();
}
else
{
SaveRegDetails();
}
}
private void UpdateRegDetails()
{
RegDetails regDet = new RegDetails();
regDet.UserRegId = Convert.ToInt32(ViewState["UserRegId"].ToString());
regDet.FirstName = txtFirstName.Text.Trim();
regDet.LastName = txtLastName.Text.Trim();
regDet.EmailId = txtEmail.Text.Trim();
regDet.Password = txtPwd.Text.Trim();
regDet.ContactNo = txtContact.Text.Trim();
obj.UpdateUserRegDetails(regDet);
lblStatus.Text = obj.UpdateUserRegDetails(regDet);
ClearControls();
BindRegRecordsInGrid();
}
private void ClearControls()
{
txtFirstName.Text = string.Empty;
txtLastName.Text = string.Empty;
txtEmail.Text = string.Empty;
txtPwd.Text = string.Empty;
txtContact.Text = string.Empty;
btnSubmit.Text = "Submit";
txtFirstName.Focus();
}
private void SaveRegDetails()
{
RegDetails regDet = new RegDetails();
regDet.FirstName = txtFirstName.Text.Trim();
regDet.LastName = txtLastName.Text.Trim();
regDet.EmailId = txtEmail.Text.Trim();
regDet.Password = txtPwd.Text.Trim();
regDet.ContactNo = txtContact.Text.Trim();
lblStatus.Text = obj.InsertUserRegDetails(regDet);
ClearControls();
BindRegRecordsInGrid();
}
protected void imgEdit_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
{
RegDetails regDet = new RegDetails();
regDet.UserRegId = int.Parse(e.CommandArgument.ToString());
ViewState["UserRegId"] = regDet.UserRegId;
DataSet ds = new DataSet();
ds = obj.FetchUpdatedRecords(regDet);
if (ds.Tables[0].Rows.Count > 0)
{
txtFirstName.Text = ds.Tables[0].Rows[0]["FirstName"].ToString();
txtLastName.Text = ds.Tables[0].Rows[0]["LastName"].ToString();
txtEmail.Text = ds.Tables[0].Rows[0]["EmailId"].ToString();
txtPwd.Text = ds.Tables[0].Rows[0]["Password"].ToString();
txtContact.Text = ds.Tables[0].Rows[0]["ContactNo"].ToString();
btnSubmit.Text = "Update";
}
}
protected void imgDel_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
{
RegDetails regDet = new RegDetails();
regDet.UserRegId = int.Parse(e.CommandArgument.ToString());
if (obj.DeleteUserRegDetails(regDet) == true)
{
lblStatus.Text = "Record deleted Successfully";
}
else
{
lblStatus.Text = "Record couldn't be deleted";
}
BindRegRecordsInGrid();
}
protected void btnCancel_Click(object sender, EventArgs e)
{
ClearControls();
lblStatus.Text = string.Empty;
}
protected void txtPwd_PreRender(object sender, EventArgs e)
{
txtPwd.Attributes.Add("value",txtPwd.Text);
}
- Notice that in the web.config file the address, binding and contract is automatically added in the Consuming application.
Now run the Consuming application and enjoy with your wcf application. But make sure the wcf service we created earlier is also running.
Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned for more technical updates."
50 comments
Click here for commentsNice Post, but provide its sample as well for users
ReplyThanks
Thanks for your appreciation and suggestion. I will also provide the sample as soon as possible. Stay tuned for more updates like this..
ReplyI like your post, thanks for sharing this, but I got many errors when I tried to view the service.csv in my browser,
ReplyThis article is tested and working..But if you are getting any error then please let me know..I'll help you resolve that..
ReplyEverything is fine...I did as shown but this line shows error
Replyobj.UpdateUserRegDetails(regDet);
obj.InsertUserRegDetails(regDet);
obj.FetchUpdatedRecords(regDet);
obj.DeleteUserRegDetails(regDet)
Can you please post some more articles on WCF..
ReplyLike upload file into database using WCF,and covering all aspects of WCF
is your wcf service running at the time when you run the consuming application? Please check. I also suggest you to please match all of you code with the article. If you still face problems then send your complete project on my email id: lalit24rocks@gmail.com .I will sort out your errors and send back to you.
ReplySure..and thanks for the suggestions.I'll post as per your suggestion very soon. Stay tuned for more updates on WCF..
ReplySuperb Article. Very Clear Explanation.
Replythanks for the appreciation..stay tuned and subscribe for more updates like this.
Replythanks for the appreciation..stay tuned and subscribe for more updates like this.
Replynice tuto,
Replycould you please save my life by sending me the project.zip at the address below
carloune1@gmail.com
Hello Carloune..i will create the downloadable of this article very soon..so keep reading..:)
Replysir Its very nice Article. I am also getting the update from your bolg in my Inbox. but Now a days you are posting anything in webcodeexpert... you are great sir.
ReplyHello Faisal Hasan..thanks for appreciating my blog and articles..due to busy schedule i am unable to post articles daily..but soon i will post more useful articles..so keep reading..:)
Replysir...first off all thanks for give user friendly code of WCF, second is .. Really very outstanding & user friendly programming Article layout.... & defined easy step for developers. thank you so much sir.... present day i'm waiting your new updates related to .net Technology "jai shree krishna"
Replyhello hitesh..thanks for your appreciations and i am very happy you liked this article..keep reading for more useful updates.."jai shree krishna.".:)
ReplyThank You sir! With the help of your sample service i have creating my first WCF Service successfully.
ReplyHello Ravi..i am glad my article helped you in creating your first WCF Service..keep reading :)
Replyhello sir, i have Problem in my gmail inbox your update mail is automatically gone in my Social tag. what should i do for this to come inbox directly coz i dont check my social tag. Please revert me thanks in advance
ReplyHi faisal..i think this is the gmail feature of categorizing the emails..so the solutions is to check your social tab also..:)
ReplyIf i got the option to receive the updates directly to primary tab then i will tell you definitely..
I got the solution, right click on the update email -> Move to tab -> Primary -> then it will say "The conversation has been moved to primary. Do this for for future message from noreply@blogger.com? ." Click on yes. Now you will receive the updates on primary inbox tab.
ReplyDear Lilit Sir, can you send me ebooks on asp.net or links from which I can download these books....
ReplyKindly reply me on azeemwaalikhan@gmail.com.... Thanks
Hello sir. How are sir. Yes it's G mail feature of categorizing the emails. I got the solution for this. Its simple just drag and drop to primary category then you will asked The conversation has been moved to primary. Do this for for future message from noreply@blogger.com? ." Click on yes.
ReplyHi Faisal..i am happy you got the easy solution.. I also posted another solution in response to your this query some days ago.. :)
ReplyVery Nice Thanks a lot
ReplyYour welcome Azhar..keep reading for more useful updates like this...:)
Replyprotected void txtPwd_PreRender(object sender, EventArgs e)
Reply{
txtPwd.Attributes.Add("value",txtPwd.Text);
}
Hello Sir,
Replyit's really a nice post. Thanks. I need more help from you. I want to consume this web service using jQuery. How to do that. If possible can you please send me any example regarding this at sonawane.nilesh27@yahoo.co.in
Hi - Great article - A question on performance... I noticed you are using a DataSet to grab data from SQL server... wouldn't a data reader be more efficient to populate a class ? I understand that under the hood, a data reader is being used to populate the data set anyway. If this is not correct, please let me know. Thanks again
Replyhi sir, nice article, but i have a doubt on my publishing,
Replyi published the service and application on Server1 ie., http://Server1/myservice as Service Reference
but unfortunately the Server name was changed as HrServer , then now how can i consume the service methods??. Is it the procedure is same??, i meant to say that i have to rebuild the whole application after doing the New Service references(http://HrServer/myservice) of each Page again??
i dont know whether my publishing process is correct or not, pls let me know :-(
hi sir, nice article, but i have a doubt,
Replyi have published the service and application on Server1 ie., http://Server1/myservice as Service Reference
but unfortunately the Server name was changed as HrServer , then now how can i consume the service methods??. Is it the procedure is same, i meant to say that i have to rebuild the whole application after doing the New Service references(http://HrServer/myservice) of each Page again??
i dont know whether my publishing process is correct or not, pls let me know
Thank You sir! With the help of your sample service i have creating my first WCF Service successfully.
ReplyHello priyanka..i am glad my article helped you in creating your first CCF service..keep reading for more useful updates like this...:)
ReplyThanksss, you rescued my life:) I am going to learn this topic too detailed
ReplyYou rescued my life:)
ReplyThank you so much. I achieved my first wcf service app.
I will continue this topic absolutely
Hi yunus celik..thanks for sharing your feedback..i am so glad my article helped you to learn about WCF..stay connected and keep reading for more useful updates like this..:)
Replyyour welcome yunus..
Replyplease change the meaning of " fro" to for in below line.
ReplyNote: I have used two images edit.png and delete.png in this example to show in gridview fro
Thanks Sonu for notifying me the spelling error..i have made the correction..
ReplyHad to debug default installed database or 2014 when installing SSDT (SQL Server Database Tools for VS 2012), then fix the connection string and add it to the web config. After that works great. Have a slight issues with occasional error in IIS on hosting side, returns a 500 error. Restarting clears it and all runs smoothly again. FANTASTIC tutorial otherwise. Easy to replicate and deploy. Helped me ALOT!!!!
ReplyThanks for your feedback..stay connected and keep reading..
Replysuper pu super
ReplyThanks
ReplySuper sir Thank You Very Much
ReplyThanks for appreciating my work..Stay connected for more useful updates like this..
ReplyPlease explain the bindings clearly...
Replysir i have read nd run the wcf both tutorial very nice . i have send u some query in mail so please read mail nd suggest me .
ReplySuperb bro..please keep posting..
ReplyThanks for you feedback..I am glad you liked this article..stay connected and keep reading...
ReplyIf you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..