Interface:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
using System.ServiceModel.Activation;
[DataContract(Name = "Usersdetail",
Namespace = "")]
[KnownType(typeof(UserSkills))]
public class UserDataContract
{
[DataMember(Name = "Uid",
Order = 1)]
public Int32
UserId;
[DataMember(Name = "UserFirstName",
Order = 2)]
public string
FirstName;
[DataMember(Name = "UserLastName",
Order = 3)]
public string
LastName;
[DataMember(Name = "UserEmail",
Order = 4)]
public string Email;
[DataMember(Name = "UserCourse",
Order = 5)]
public string Course;
[DataMember(Name = "UserPicture",
Order =6)]
public string
Picture;
[DataMember(Name = "SkillsInfo",
Order = 6)]
public List<UserSkills> SkillsInfo;
}
[DataContract]
public class UserSkills
{
[DataMember(Name = "SkillID",
Order = 1)]
public Int32
SkillID;
[DataMember(Name = "Uid",
Order = 1)]
public Int32
UserId;
[DataMember(Name = "Skills",
Order = 2)]
public string
Skills;
}
[ServiceContract]
public interface ICURDService
{
[OperationContract]
[WebGet(UriTemplate = "/getAllEmployes",
ResponseFormat = WebMessageFormat.Json)]
List<UserDataContract>
GetEmploy();
[OperationContract]
[WebGet(UriTemplate = "/getEmployeeDetails/{id}",
ResponseFormat = WebMessageFormat.Json)]
UserDataContract GetEmpDetail(string id);
[OperationContract]
[WebInvoke(UriTemplate = "/CreateEmp",
Method = "POST",RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
int InsertData(UserDataContract
obj);
[OperationContract]
[WebInvoke(UriTemplate = "/UpdateEmp",
Method = "PUT", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
int Updatedata(UserDataContract
obj);
[OperationContract]
[WebInvoke(UriTemplate = "/DeleteEmp/{empid}",
Method = "DELETE", RequestFormat =
WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
int DeleteData(string
empid);
}
Service :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
using System.ServiceModel.Activation;
using WCF_CURD_Operations;
using System.Transactions;
[AspNetCompatibilityRequirements(RequirementsMode
= AspNetCompatibilityRequirementsMode.Required)]
public class CURDService : ICURDService
{
List<UserDataContract>
objlist = new List<UserDataContract>();
UserDataContract _users;
UserSkills _userskills;
List<UserSkills>
_lstSkills;
public List<UserDataContract> GetEmploy()
{
WCF_CURD_Operations.LinqTestEntities1
ctx = new WCF_CURD_Operations.LinqTestEntities1();
var em = from s in ctx.users
select s;
foreach (user u in em)
{
_users = new
UserDataContract();
_users.UserId = u.UserId;
_users.FirstName = u.FirstName;
_users.LastName = u.LastName;
objlist.Add(_users);
}
return objlist;
}
public UserDataContract
GetEmpDetail(string id)
{
int uid = Convert.ToInt32(id);
WCF_CURD_Operations.LinqTestEntities1
ctx = new WCF_CURD_Operations.LinqTestEntities1();
// get employee details
var em = (from s in ctx.users
where s.UserId == uid
select s).FirstOrDefault();
// get employee skills details
var S = (from skills in ctx.userSkills
where skills.userid == uid
select skills).ToList();
_lstSkills = new List<UserSkills>();
// add skills details in list object
foreach (var emp in S)
{
_userskills = new UserSkills();
_userskills.UserId = Convert.ToInt32(emp.userid);
_userskills.SkillID = emp.SkillID;
_userskills.Skills = emp.Skills;
_lstSkills.Add(_userskills);
}
_users = new UserDataContract();
_users.UserId = em.UserId;
_users.FirstName = em.FirstName;
_users.LastName = em.LastName;
_users.Email = em.Email;
_users.Course = em.Course;
_users.Picture = em.Pic;
_users.SkillsInfo = _lstSkills; // asign list
skills object
return _users;
}
public int
InsertData(UserDataContract obj)
{
int result=0;
WCF_CURD_Operations.LinqTestEntities1
ctx = new WCF_CURD_Operations.LinqTestEntities1();
user obj2 = new
user();
obj2.FirstName = obj.FirstName.Trim();
obj2.LastName = obj.LastName.Trim();
obj2.Email = obj.Email.Trim();
obj2.Course = obj.Course.Trim();
obj2.Pic = obj.Picture.Trim();
// int? intIdt = ctx.users.Max(u =>
(int?)u.UserId);
try
{
ctx.AddTousers(obj2); // saving Employee data
ctx.SaveChanges();
//saving Skills data
WCF_CURD_Operations.LinqTestEntities1
ctx_insertSkills = new WCF_CURD_Operations.LinqTestEntities1();
int w = obj.SkillsInfo.Count;
for (Int32
i = 0; i < obj.SkillsInfo.Count; i++)
{
userSkill objskill = new userSkill();
objskill.userid =
obj2.UserId;
objskill.Skills =
obj.SkillsInfo[i].Skills.ToString();
ctx_insertSkills.AddTouserSkills(objskill);
ctx_insertSkills.SaveChanges();
}
// return employee ID which we help us to bind
event in front end
result = obj2.UserId;
}
catch (Exception
ex)
{
result = 0;
}
return result;
}
public int
Updatedata(UserDataContract obj)
{
int result = 0;
// Update Employee data
WCF_CURD_Operations.LinqTestEntities1
ctx = new WCF_CURD_Operations.LinqTestEntities1();
var u = (from o in ctx.users
where o.UserId == obj.UserId
select o).First();
u.FirstName = obj.FirstName;
u.LastName = obj.LastName;
u.Email = obj.Email;
u.Course = obj.Course;
u.Pic
= obj.Picture;
result = ctx.SaveChanges();
// Delete skills data because multiple skills rows for same
user
WCF_CURD_Operations.LinqTestEntities1
ctx_delete = new WCF_CURD_Operations.LinqTestEntities1();
var query = from p in ctx_delete.userSkills
where p.userid == obj.UserId
select p;
foreach (userSkill
p in query)
{
ctx_delete.DeleteObject(p);
}
ctx_delete.SaveChanges();
// Insert New Skills for user
WCF_CURD_Operations.LinqTestEntities1
ctx_insertSkills = new WCF_CURD_Operations.LinqTestEntities1();
int w = obj.SkillsInfo.Count;
for (Int32 i = 0;
i < obj.SkillsInfo.Count; i++)
{
userSkill objskill = new
userSkill();
objskill.userid = obj.UserId;
objskill.Skills = obj.SkillsInfo[i].Skills.ToString();
ctx_insertSkills.AddTouserSkills(objskill);
ctx_insertSkills.SaveChanges();
}
result = 1;
return result;
}
public int
DeleteData(string empid)
{
int result = 0;
using (WCF_CURD_Operations.LinqTestEntities1
ctx = new WCF_CURD_Operations.LinqTestEntities1())
{
int EmpID = Convert.ToInt32(empid);
var query_D = (from b
in ctx.users
where b.UserId == EmpID
select b).First();
try
{
// delete user data
ctx.DeleteObject(query_D);
result = ctx.SaveChanges();
// Delete skills data
WCF_CURD_Operations.LinqTestEntities1
ctx_delete = new WCF_CURD_Operations.LinqTestEntities1();
var query = from
p in ctx_delete.userSkills
where p.userid == EmpID
select p;
foreach (userSkill
p in query)
{
ctx_delete.DeleteObject(p);
}
ctx_delete.SaveChanges();
}
catch (Exception
ex)
{
result = 0;
}
}
return result;
}
}
Web config :
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Data.Entity,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
</system.web>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="WebHttpBindingHTTP" crossDomainScriptAccessEnabled="true"></binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="CURDEndPointBehavior">
<!--This element specifies the WebHttpBehavior on an endpoint through
configuration-->
<!--Avoid AddressFilter mismatch at the EndpointDispatcher-->
<!-- This element Make help enable so that we can check methods by
just typing /help at the end of servic url like
-http://localhost:54445/CURDService.svc/help -->
<!--This help page lists a description of each operation, request and
response formats, and schemas.-->
<webHttp faultExceptionEnabled="true" defaultBodyStyle="Wrapped" helpEnabled="true" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="CURDServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<!--This element help us to check internal error occer in service -->
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="false" aspNetCompatibilityEnabled="true" />
<services>
<service name="CURDService" behaviorConfiguration="CURDServiceBehavior">
<endpoint address="" binding="webHttpBinding" behaviorConfiguration="CURDEndPointBehavior" contract="ICURDService"></endpoint>
</service>
</services>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<connectionStrings>
<add name="LinqTestEntities1" connectionString="metadata=res://*/Model2.csdl|res://*/Model2.ssdl|res://*/Model2.msl;provider=System.Data.SqlClient;provider
connection string="data
source=.\SQLEXPRESS;attachdbfilename=|DataDirectory|\LinqTest.mdf;integrated
security=True;connect timeout=30;user instance=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
Model :
Client :
<%@ Page
Language="C#"
AutoEventWireup="true"
CodeBehind="Default.aspx.cs"
Inherits="CURD_Client.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">
<script src="Scripts/jquery-1.8.3.min.js"
type="text/javascript"></script>
<script language="javascript">
$(document).ready(function () {
//****** Show Loading Message during Ajax
Operations************//
$("#loading").ajaxStart(function () {
$(this).show();
}).ajaxStop(function () {
$(this).hide();
});
//******Get Employee Details during first page
load************//
GetEmployee();
//****** Insert Details************//
$('#btnAddEmp').click(function
() {
InsertEmployee();
});
//****** Update Details************//
$('#UpdateEmp').click(function
() {
UpdateEmployee();
});
//****** Just to hide Message at top quickly (default 2
seconds) ************//
$('#message').click(function
() {
$(this).fadeOut();
$(this).html('');
});
});
function GetEmployee() {
$('#MainCategory').html('');
$.ajax({
async: false,
type: "GET", // Method GET
contentType: "application/json;
charset=utf-8",
url: 'CURDService.svc/getallemployes',
// service calling function
data: {},
dataType: "json", // Type JSON
error: function (msg) {
alert('Service call failed: ' +
msg.status + ' Type :' + msg.statusText);
},
success: function (msg) {
// Service Calling success method
// here we are using msg.GetEmployResult
because ur json data in this format
//{"GetEmployResult":[{"Uid":78,"UserFirstName":"test","UserLastName":"test","UserEmail":null,"UserCourse":null,"SkillsInfo":null,"UserPicture":null}]}
var result = msg.GetEmployResult;
/// loop for appending List and ankor
element with data
$.each(result, function (index, output)
{
$('#MainCategory').append($('<li/>',
{
}).append($('<a/>', {
'id': output.Uid,
'href':
'#',
'text': output.UserFirstName + " " + output.UserLastName + " "
})));
});
//*****************************Bind event
when any user click in List Item******************//
$('#MainCategory li a').bind('click', function
() {
//
Calling get detail function by padding parameter Emp ID
getEmployeedetails($(this).attr('id'));
});
}
});
}
function getEmployeedetails(EmpID) {
ClearAllControls();
$.ajax({
async: false,
type: "GET",
contentType: "application/json;
charset=utf-8",
url: 'CURDService.svc/getemployeedetails/'
+ EmpID,
data: {},
dataType: "json",
error: function
(msg2) {
alert('Service call failed: ' +
msg2.status + ' Type :' + msg2.statusText);
},
success: function (msg2) {
var HTML = "";
$.each(msg2, function (index, output2) {
var
skills = "";
//
getting Skills From Object
$.each(output2.SkillsInfo, function
(index, output3) {
skills = skills +
output3.Skills + ',';
});
skills =
skills.substring(0, skills.length - 1); // remove
last charecter ","
HTML = HTML + "<table style='width:400px;'>";
HTML = HTML + "<tr>"
HTML = HTML + "
<td> User FirstName</td>";
HTML = HTML + "
<td>" + output2.UserFirstName + " </td>";
HTML = HTML + "
<td rowspan='4'><img style='width:100px;height:100px'
src='" + output2.UserPicture + "'></td>";
HTML = HTML + "
</tr>";
HTML = HTML + "<tr>";
HTML = HTML + "
<td>User LasName</td>";
HTML = HTML + "
<td>" + output2.UserLastName + "</td>";
HTML = HTML + "</tr>";
HTML = HTML + " <tr>";
HTML = HTML + " <td>User Email</td>";
HTML = HTML + "
<td>" + output2.UserEmail + "</td>";
HTML = HTML + " </tr>";
HTML = HTML + " <tr>";
HTML = HTML + "
<td>Course</td>";
HTML = HTML + "
<td>" + output2.UserCourse + "</td>";
HTML = HTML + " </tr>";
HTML = HTML + " <tr>";
HTML = HTML + " <tr>";
HTML = HTML + "
<td>Skils</td>";
HTML = HTML + "
<td><p>" + skills + "</p></td>";
HTML = HTML + " </tr>";
HTML = HTML + " <tr>";
HTML = HTML + "
<td><a href='#' id='" + output2.Uid + "' class='clsedit'>Edit details</a>
</td>";
HTML = HTML + "
<td><a href='#' id='" + output2.Uid + "' class='clsdelete'>delete record</a>
</td>";
HTML = HTML + " </tr>";
HTML = HTML + " </table>";
});
$('#Details').html('');
$(HTML)
.appendTo('#Details')
.find('a.clsdelete')
.click(function
() {
$(this).parents('table').slideUp('slow').html();
var GetCurrentID = $(this).attr('id');
$('#MainCategory li').each(function
(index) {
if (GetCurrentID == $(this).children('a').attr('id'))
{
var retvalue = DeleteEmployee($(this).children('a').attr('id'));
if (retvalue == 0) {
$('#message').html('Unable
to delete').slideDown().delay(2000).slideUp("slow");
}
else {
$('#message').html('Record
deleted').slideDown().delay(2000).slideUp("slow");
$(this).remove().fadeOut();
}
}
});
});
//Binding event to display information in
text boxes
// function return information and display
in controls
$('#Details')
.find('a.clsedit')
.click(function
() {
getEmployeedetailstoEdit($(this).attr('id'));
});
}
});
}
function getEmployeedetailstoEdit(EmpID) {
ClearAllControls();
$.ajax({
async: false,
type: "GET",
contentType: "application/json;
charset=utf-8",
url: 'CURDService.svc/getemployeedetails/'
+ EmpID,
data: {},
dataType: "json",
error: function (msg2) {
alert('Service call failed: ' +
msg2.status + ' Type :' + msg2.statusText);
},
success: function (msg2) {
$.each(msg2, function (index, output2) {
$("#FirstName").val(output2.UserFirstName);
$("#LasName").val(output2.UserLastName);
$("#Email").val(output2.UserEmail);
$("#Course").val(output2.UserCourse);
$("#Pic").val(output2.UserPicture);
$("#UserID").val(EmpID);
//Default
selection of skills which belongs to current user
$.each(output2.SkillsInfo,
function (index, output3) {
// checking each item
$('#Slkills option').each(function
(i) {
// if matches with return slikk then change attribute
to selectec
if (output3.Skills == $(this).val())
{
$(this).attr("selected",
"selected");
}
});
});
//**************************************************//
});
}
});
}
//Function to insert details
function InsertEmployee() {
// validation for Firstname and last name
if ($("#FirstName").val()
== "" || $("#LasName").val()
== "") {
$('#message').html('Please enter FirstName and LastName.').slideDown().delay(2000).slideUp("slow");
}
else {
// Createing Skills object
SkillsInfo = [];
$("#Slkills option:selected").each(function () {
item = {}
item["SkillID"] = "1"; // for
testing purpose
item["Skills"] = $(this).text();
item["Uid"] = "1";
// for testing purpose
SkillsInfo.push(item);
});
// Json text to be passed
var jsonText = JSON.stringify({ "obj": { "Uid":
0, "UserFirstName": $("#FirstName").val(), "UserLastName": $("#LasName").val(), "UserEmail":
$("#Email").val(), "UserCourse": $("#Course").val(),
"UserPicture": $("#Pic").val(), "SkillsInfo":
SkillsInfo} });
$.ajax({
async: false,
type: "POST",
contentType: "application/json;
charset=utf-8",
url: 'CURDService.svc/CreateEmp',
data: jsonText,
dataType: "json",
error: function (msg) {
alert('Service call failed: ' + msg.status + ' Type :' + msg.statusText);
},
success: function (msg) {
$.each(msg, function (index, output) {
if (output == 0) {
}
else {
// display messsage after insert record
$('#message').html('Record
created').slideDown().delay(2000).slideUp("slow");
// Appending new inserted record in list
$('#MainCategory').append($('<li/>',
{
}).append($('<a/>', {
'id': output,
'href': '#',
'text': $("#FirstName").val()
+ " " + $("#LasName").val()
+ "
"
})));
//
clear all textboxes
ClearAllControls();
}
});
//*****************************Bind
event to last Li element******************//
$('#MainCategory li:last a').bind('click', function
() {
getEmployeedetails($(this).attr('id'));
});
}
});
}
}
function UpdateEmployee() {
if ($("#FirstName").val()
== "" || $("#LasName").val()
== "") {
$('#message').html('Please enter FirstName and LastName.').slideDown().delay(2000).slideUp("slow");
}
else {
SkillsInfo = [];
$("#Slkills option:selected").each(function () {
item = {}
item["SkillID"] = "1"; // for
testing purpose
item["Skills"] = $(this).text();
item["Uid"] = "1"; // for
testing purpose
SkillsInfo.push(item);
});
var jsonText = JSON.stringify({ "obj": { "Uid":
$("#UserID").val(), "UserFirstName": $("#FirstName").val(), "UserLastName": $("#LasName").val(), "UserEmail":
$("#Email").val(), "UserCourse": $("#Course").val(),
"UserPicture": $("#Pic").val(), "SkillsInfo":
SkillsInfo} });
$.ajax({
async: false,
type: "PUT",
contentType: "application/json;
charset=utf-8",
url: 'CURDService.svc/UpdateEmp',
data: jsonText,
dataType: "json",
error: function (msg) {
alert('Service call failed: ' + msg.status + ' Type :' + msg.statusText);
},
success: function (msg) {
$.each(msg, function (index, output) {
if (output == 0) {
}
else {
$('#message').html('Record
Updated').slideDown().delay(2000).slideUp("slow");
// on successfull update calling get all enployees function
// and show details as well
GetEmployee();
getEmployeedetails($("#UserID").val());
ClearAllControls()
}
});
//*****************************Bind
event to last Li element******************//
$('#MainCategory li:last a').bind('click', function
() {
getEmployeedetails($(this).attr('id'));
});
//*****************************End
of Bind event******************//
}
});
}
}
function ClearAllControls() {
$("#FirstName").val('');
$("#LasName").val('');
$("#Email").val('');
$("#Course").val('');
$("#Pic").val('');
$("#UserID").val('');
$('#Slkills option').each(function
(i) {
$(this).attr("selected",
false);
});
}
function DeleteEmployee(Empid) {
ClearAllControls()
var Success = 0;
$.ajax({
async: false,
type: "DELETE",
contentType: "application/json;
charset=utf-8",
url: 'CURDService.svc/DeleteEmp/' +
Empid,
data: {},
dataType: "json",
error: function (msg) {
alert('Service call failed: ' +
msg.status + ' Type :' + msg.statusText);
},
success: function (msg) {
$.each(msg, function (index, output) {
Success = output;
});
}
});
return Success;
}
</script>
<style type="text/css">
#loading {
position: absolute;
width: 14%;
height: 110px;
top:73px;
text-align: center;
left: 432px;
}
#message
{
height:50px;
width:100%;
position: absolute;
background-color:Yellow;
color:Red;
left:0px;
top:0px;
text-align :center;
display:none;
}
.style1
{
width: 162px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div id="message"></div>
<div id="loading">
<img src="http://a1.ec-images.myspacecdn.com/images02/101/2860416838444d48899d484ae92ddfa8/l.gif"
/>
</div>
<br />
<br />
<div style="width:807px">
<table>
<tr>
<td> FirstName:</td>
<td class="style1"><input id="FirstName">
<input id="UserID" type="hidden">
</td>
<td rowspan="5" valign="top">Skills<br />
<select id="Slkills"
multiple="multiple"
style="width :175px; height: 116px;"
name="D1" >
<option id="Asp">Asp</option>
<option id="Asp.Net">Asp.Net</option>
<option id="Jquery">Jquery</option>
<option id="MVC">MVC</option>
<option id="WCF">WCF</option>
<option id="SilverLight">SilverLight</option>
</select>
</td>
</tr>
<tr>
<td>LasName:</td>
<td class="style1"><input id="LasName"></td>
</tr>
<tr>
<td>Course:</td>
<td class="style1"><input id="Course"></td>
</tr>
<tr>
<td>Email:</td>
<td class="style1"><input id="Email"></td>
</tr>
<tr>
<td>Pic Path:</td>
<td class="style1"><input id="Pic"></td>
</tr>
<tr>
<td></td>
<td class="style1"><input id="btnAddEmp" value="Add Employee" type="button"/>
</td>
<td>
<input id="UpdateEmp"
value="Update
Employee" type="button"/></td>
</tr>
</table>
<br />
.
<ul id="MainCategory" style="width:200px; float:left">
</ul>
<div id="Details"
style="width:400px; float:right"></div>
</div>
</form>
</body>
</html>
OutPut :
good work..as well hardwork .Lavi.
ReplyDeletehi lavi,
ReplyDeleteyour mail id please.
i am follower of your blog.
waiting for your articles.