由于应用程序开发中一般都会涉及到大量的增删改查业务,所以这个程序将简单演示如何在wcf中构建简单的增删改查服务。我们知道WCF是一组通讯服务框架,我将解决方案按大范围划分为服务端,客户端通过服务寄宿程序产生的代理来调用服务端的公开给客户端消费的方法。总个解决方案由五个项目工程:

  • Service:定义服务契约接口和实现服务契约,此项目类型为类库项目
  • Common:通用层定义数据访问的帮助类,此项目类型为类库项目
  • Entity:定义数据契约,也就是实体对象,此项目类型为类库项目
  • Host:服务寄宿程序,将Service服务程序寄宿在该程序中,此项目类型为控制台应用程序
  • Client:客户端程序,实现对服务的消费,此项目类型为web项目

2.实现程序

步骤一:建立数据库

为方便演示操作,我们建立一个简单的表,学生信息(Student),创建的脚本如下(此处我采用的是sql server数据库):

SET ANSI_NULLS ON
GO SET QUOTED_IDENTIFIERON
GO CREATE TABLE[dbo].[Student](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[Age] [int] NULL,
[Grade] [nvarchar](50) NULL,
[Address] [nvarchar](50) NULL,
CONSTRAINT [PK_Student] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

步骤二:建立Common层

新建一个空白解决方案,名称为WcfDemo,创建完成后新增一个类库文件命名为Common,再添加一个数据库访问帮助类DbHelperSQL:代码如下:

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Data.Common;
using System.Collections.Generic; namespace Common
{
public class DbHelperSQL
{
public static string connectionString ="server=.;database=test;uid=sa;pwd=sa123"; public static int ExecuteSql(stringSQLString)
{
using (SqlConnection connection =new SqlConnection(connectionString))
{
using (SqlCommand cmd = newSqlCommand(SQLString, connection))
{
try
{
connection.Open();
int rows =cmd.ExecuteNonQuery();
return rows;
}
catch(System.Data.SqlClient.SqlException e)
{
connection.Close();
throw e;
}
}
}
} public static SqlDataReaderExecuteReader(string strSQL)
{
SqlConnection connection = newSqlConnection(connectionString);
SqlCommand cmd = newSqlCommand(strSQL, connection);
try
{
connection.Open();
SqlDataReader myReader =cmd.ExecuteReader(CommandBehavior.CloseConnection);
return myReader;
}
catch(System.Data.SqlClient.SqlException e)
{
throw e;
} } public static DataSet Query(stringSQLString)
{
using (SqlConnection connection =new SqlConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
SqlDataAdapter command =new SqlDataAdapter(SQLString, connection);
command.Fill(ds,"ds");
}
catch(System.Data.SqlClient.SqlException ex)
{
throw newException(ex.Message);
}
return ds;
}
} } }

步骤三:建立Entity层

在WcfDemo解决方案上新建一个名称为Entity的类库项目,添加对System.Runtime.Serialization的引用,创建服务的数据契约。新增Student类,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization; namespace Entity
{
[DataContract]
public class Student
{
[DataMember]
public int ID { get; set; } [DataMember]
public string Name { get; set; } [DataMember]
public int Age { get; set; } [DataMember]
public string Grade { get; set; } [DataMember]
public string Address { get; set; }
}
}
步骤四:建立Service层

此项目需要对Common和Entity的引用,再添加对System.ServiceModel的引用,以创建服务契约。在该项目中添加IStudent接口,定义服务契约接口,代码如下:

using System.Collections.Generic;
using System.ServiceModel;
using Entity; namespace Service
{
[ServiceContract]
public interface IStudent
{
[OperationContract]
List<Student> GetInfo(stringstrWhere); [OperationContract]
bool Add(Student model); [OperationContract]
bool Update(Student model); [OperationContract]
bool Delete(int id); [OperationContract]
bool Exist(int id);
}
}

再添加EFStudent类,实现对IStudent接口的实现,代码如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Common;
using Entity; namespace Service
{
public class EFStudent:IStudent
{
public List<Student>GetInfo(string strWhere)
{
List<Student> listData = newList<Student>();
string strSql = "select * fromstudent";
DataTable dt=DbHelperSQL.Query(strSql).Tables[0];
if (null != dt &&dt.Rows.Count > 0)
{
for (int i = 0; i <dt.Rows.Count; i++)
{
Student model = newStudent();
model.ID =Convert.ToInt32(dt.Rows[i]["ID"]);
model.Name =dt.Rows[i]["Name"].ToString();
model.Age =Convert.ToInt32(dt.Rows[i]["Age"]);
model.Grade =dt.Rows[i]["Grade"].ToString();
model.Address =dt.Rows[i]["Address"].ToString();
listData.Add(model);
}
}
return listData;
} public bool Add(Student model)
{
StringBuilder strSql = newStringBuilder();
strSql.Append(" insert intostudent values ");
strSql.Append(" ( ");
strSql.Append(" " +model.ID + ", ");
strSql.Append(" '" +model.Name + "', ");
strSql.Append(" " +model.Age + ", ");
strSql.Append(" '" +model.Grade + "', ");
strSql.Append(" '" +model.Address + "' ");
strSql.Append(" ) "); int rows =DbHelperSQL.ExecuteSql(strSql.ToString());
if (rows > 0)
{
return true;
}
else
{
return false;
}
} public bool Update(Student model)
{
StringBuilder strSql = newStringBuilder();
strSql.Append(" update studentset ");
strSql.Append(" Name= '"+ model.Name + "', ");
strSql.Append(" Age= " +model.Age + ", ");
strSql.Append(" Grade= '" +model.Grade + "', ");
strSql.Append(" Address='" + model.Address + "' ");
strSql.Append(" WhereID=" + model.ID + " "); int rows =DbHelperSQL.ExecuteSql(strSql.ToString());
if (rows > 0)
{
return true;
}
else
{
return false;
}
} public bool Delete(int id)
{
StringBuilder strSql = new StringBuilder();
strSql.Append(" delete fromstudent where ID=" + id + " ");
int rows =DbHelperSQL.ExecuteSql(strSql.ToString());
if (rows > 0)
{
return true;
}
else
{
return false;
}
} public bool Exist(int id)
{
StringBuilder strSql = newStringBuilder();
strSql.Append(" select ID fromstudent where ID=" + id + " ");
DataTable dt =DbHelperSQL.Query(strSql.ToString()).Tables[0];
if (null != dt &&dt.Rows.Count > 0)
{
return true;
}
else
{
return false;
}
}
}
}

步骤五:建立Host层,对Service进行寄宿

此项目需要对Service项目的引用,并添加对using System.ServiceModel的引用,添加寄宿的服务配置文件App.config,代码如下:

<?xmlversion="1.0"?>
<configuration>
<system.serviceModel>
<services>
<servicename="Service.EFStudent"behaviorConfiguration="EFStudentBehavior">
<host>
<baseAddresses>
<addbaseAddress="http://127.0.0.1:1234/EFStudent/"/>
</baseAddresses>
</host> <endpoint address="" binding="wsHttpBinding"contract="Service.IStudent"/>
<endpoint address="mex"binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services> <behaviors>
<serviceBehaviors>
<behaviorname="EFStudentBehavior">
<serviceMetadatahttpGetEnabled="True"/>
<serviceDebugincludeExceptionDetailInFaults="True"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel> <startup>
<supportedRuntime version="v4.0"sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>

服务寄宿程序Host的Program.cs的代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Service; namespace Host
{
class Program
{
static void Main(string[] args)
{
try
{
using (ServiceHost host = newServiceHost(typeof(EFStudent)))
{
host.Opened += delegate
{
Console.WriteLine("StudentService已经启动,按任意键终止!");
}; host.Open();
Console.Read();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
}
}

此时,可以编译程序,找到Host项目生成目录,运行Host.exe,就可以对服务进行寄宿,如果寄宿成功,在浏览器中输入http://127.0.0.1:1234/EFStudent地址,就可以看到如下图所示页面:

步骤六:建立Web客户端

新建一个空Client的Web引用程序,添加对服务的引用,输入刚才在浏览器中输入的地址,然后点击发现前往按钮就可以发现服务了,点击确定添加对服务的引用,vs会自动生成对服务的应用配置文件和代理类,如果需要手动生成,可以参考WCF初探—1:认识wcf。添加MainForm.aspx页面,前端代码如下:

<%@ PageLanguage="C#" AutoEventWireup="true"CodeBehind="MainForm.aspx.cs"EnableEventValidation="false" Inherits="Client.MainForm" %>

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

<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title></title>
<scripttype="text/javascript">
var prevselitem = null;
function selectx(row) {
if (prevselitem != null) {
prevselitem.style.backgroundColor = '#ffffff';
}
row.style.backgroundColor ='PeachPuff';
prevselitem = row; }
</script>
</head>
<body>
<form id="form1"runat="server">
<asp:GridView ID="GridView1"runat="server" AutoGenerateColumns="False"
onrowdeleting="GridView1_RowDeleting"
onrowdatabound="GridView1_RowDataBound"
onrowcommand="GridView1_RowCommand">
<Columns>
<asp:TemplateFieldHeaderText="编号">
<ItemTemplate>
<asp:LabelID="lbl_id" runat="server" Text='<%#Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundFieldDataField="Name" HeaderText="姓名" />
<asp:BoundField DataField="Age"HeaderText="年龄"/>
<asp:BoundFieldDataField="Grade" HeaderText="年级" />
<asp:BoundFieldDataField="Address" HeaderText="家庭地址" />
<asp:CommandFieldHeaderText="删除"ShowDeleteButton="True" />
<asp:TemplateFieldHeaderText="编辑">
        <ItemTemplate>
            <asp:LinkButtonID="lbtID"
CommandName="lbtn" runat="server"ForeColor="Blue" Text="编辑">
</asp:LinkButton>
          </ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView> <p>编号<asp:TextBox ID="txt_id"runat="server"></asp:TextBox></p>
<p>姓名<asp:TextBox ID="txt_name"runat="server"></asp:TextBox></p>
<p>年龄<asp:TextBox ID="txt_age"runat="server"></asp:TextBox></p>
<p>年级<asp:TextBox ID="txt_grade"runat="server"></asp:TextBox></p>
<p>家庭地址<asp:TextBox ID="txt_address"runat="server"></asp:TextBox></p>
<asp:Button ID="btnAdd"runat="server" Text="保存" onclick="btnAdd_Click" />
</form> </body>
</html>

后台代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Client.ServiceReference; namespace Client
{
public partial class MainForm :System.Web.UI.Page
{
StudentClient proxy = newStudentClient();
protected void Page_Load(object sender,EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
} private void BindData()
{
Student[] listData =proxy.GetInfo("");
this.GridView1.DataSource =listData.ToList();
this.GridView1.DataBind();
} protected void btnAdd_Click(objectsender, EventArgs e)
{
Student model = new Student();
model.ID =Convert.ToInt32(this.txt_id.Text);
model.Name = this.txt_name.Text;
model.Age =Convert.ToInt32(this.txt_age.Text);
model.Grade = this.txt_grade.Text;
model.Address =this.txt_address.Text;
if (proxy.Exist(model.ID))
{
proxy.Update(model);
}
else
{
proxy.Add(model);
} BindData();
} protected voidGridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{ int id =Convert.ToInt16(((GridView1.Rows[e.RowIndex].FindControl("lbl_id") asLabel).Text));
bool flag = proxy.Delete(id);
if (flag)
{
Response.Write("<Script>alert(' 删除成功!')</Script> ");
BindData();
}
else
{
Response.Write("<Script>alert(' 删除失败!')</Script> ");
}
} protected voidGridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType ==DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onclick", e.Row.ClientID.ToString() +".checked=true;selectx(this)");//点击行变色 }
} protected voidGridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName =="lbtn")
        {
          GridViewRow gvrow =(GridViewRow)(((LinkButton)e.CommandSource).NamingContainer); //获取被点击的linkButton所在的GridViewRow
          int index =gvrow.RowIndex; //获取到行索引 RowIndex this.txt_id.Text =(GridView1.Rows[index].Cells[0].FindControl("lbl_id") asLabel).Text.Trim();
        this.txt_name.Text=GridView1.Rows[index].Cells[1].Text.Trim();
this.txt_age.Text =GridView1.Rows[index].Cells[2].Text.Trim();
this.txt_grade.Text =GridView1.Rows[index].Cells[3].Text.Trim();
this.txt_address.Text =GridView1.Rows[index].Cells[4].Text.Trim();         }     
} }

手动实现WCF[转]的更多相关文章

  1. 【Win 10应用开发】手动调用WCF服务

    调用服务最简单的方法就是,直接在VS里面添加服务引用,输入服务的地址即可,无论是普通Web服务,还是WCF服务均可.VS会根据获取到的元数据,自动生成客户端代码. 如果服务的调用量很大,应用广泛,可以 ...

  2. WCF初探-2:手动实现WCF程序

    1.前言 上一篇,我们通过VS自带的模板引擎自动生成了一个wcf程序,接下来我们将手动实现一个wcf程序.由于应用程序开发中一般都会涉及到大量的增删改查业务,所以这个程序将简单演示如何在wcf中构建简 ...

  3. 手动配置WCF宿主的.config文件遇到的几种错误

    今天尝试用控制台应用程序作为WCF宿主,遇到几个问题,这几个问题虽然都不难,但寻找解决方案相当费时费力,做记录. WCF标准的配置文件为: <system.serviceModel>    ...

  4. 创建一个简单的WCF程序2——手动开启/关闭WCF服务与动态调用WCF地址

    一.创建WCF服务器 1.创建WCF服务器的窗体应用程序 打开VS2010,选择文件→新建→项目菜单项,在打开的新建项目对话框中,依次选择Visual C#→Windows→Windows窗体应用程序 ...

  5. WCF初探文章列表

    WCF初探-1:认识WCF WCF初探-6:WCF服务配置 WCF初探-2:手动实现WCF程序 WCF初探-7:WCF服务配置工具使用 WCF初探-3:WCF消息交换模式之单向模式 WCF初探-8:W ...

  6. WCF初探-24:WCF序列化和反序列化

    前言 WCF包含很多封装的内部机制,这些是我们在编写程序时不会经常看到的.比如上一篇讲解的Message.这一篇我将讲解WCF的另一种内部机制,WCF的序列化和反序列化.通常我们在编写WCF服务程序的 ...

  7. Silverlight动态设置WCF服务Endpoint

    2013-02-02 05:57 by jv9, 1763 阅读, 3 评论, 收藏, 编辑 去年12月收到一位朋友的邮件,咨询Silverlight使用WCF服务,应用部署后一直无法访问的问题,通过 ...

  8. WCF序列化与反序列化问题

    转自:http://www.cnblogs.com/wangweimutou/p/4505447.html WCF包含很多封装的内部机制,这些是我们在编写程序时不会经常看到的.比如上一篇讲解的Mess ...

  9. WCF相关

    1.WCF初探-1:认识WCF(概览)2.WCF初探-2:手动实现WCF程序3.WCF精通系列4.无废话WCF系列教程

随机推荐

  1. LoadRunner脚本设计、场景设计和结果分析

    本次笔记主要记录LoadRunner脚本设计.场景设计和结果分析   1. 脚本设计       录制模式            手工模式:插入步骤.手动编写       1.1  脚本增强:     ...

  2. linux线程的实现【转】

    转自:http://www.cnblogs.com/zhaoyl/p/3620204.html 首先从OS设计原理上阐明三种线程:内核线程.轻量级进程.用户线程 内核线程 内核线程就是内核的分身,一个 ...

  3. SSH 无密码远程执行脚本

    ssh无密码登录及远程执行脚本要使用公钥与私钥.linux下可以用用ssh-keygen生成公钥/私钥对,下面我以CentOS7为例. 测试环境:机器A(10.0.224.80):机器B(192.16 ...

  4. Hudson(Jenkins)持续集成插件开发环境搭建

    Hudson持续集成插件开发环境搭建 第一步安装java jdk,至于版本的话推荐1.6以上吧.安装好jdk设置环境变量,确保你在cmd中输入java -version有提示你jdk的版本信息等,也就 ...

  5. Python之检查URL

    # -*- coding: utf-8 -*- import os,sys import time import sys import pycurl #URL="http://www.bai ...

  6. android user版本默认开启调试模式

    由于项目需要,需要发布版本默认开启调试模式,修改方式如下: 1.开启开发者模式 context.getSharedPreferences(DevelopmentSettings.PREF_FILE,C ...

  7. Runnable和Thread的区别 (转)

    在java中可有两种方式实现多线程,一种是继承 Thread类,一种是实现Runnable接口:Thread类是在java.lang包中定义的.一个类只要继承了Thread类同时覆写了本类中的 run ...

  8. Network-POJ3694并查集+LCA

    Network Time Limit: 5000MS   Memory Limit: 65536K       Description A network administrator manages ...

  9. iOS开发中的内存分配(堆和栈)

    进程的内存分区 所有进程(执行的程序)都必须占用一定数量的内存,它或是用来存放从磁盘载入的程序代码,或是存放取自用户输入的数据等等.不过进程对这些内存的管理方式因内存用途不一而不尽相同,有些内存是事先 ...

  10. logstash filter grok 用法

    在elk+filebeat都安装好,且明白了基本流程后,主要的就是写logstash的filter了,以此来解析特定格式的日志 logstash的filter是用插件实现的,grok是其中一个,用来解 ...