博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
WCF初探-2:手动实现WCF程序
阅读量:4576 次
发布时间:2019-06-08

本文共 11674 字,大约阅读时间需要 38 分钟。

1.前言

 

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

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

      

 

2.实现程序

步骤一:建立数据库

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

SET ANSI_NULLS ONGO SET QUOTED_IDENTIFIERONGO 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
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
GetInfo(string strWhere) { List
listData = newList
(); string strSql = "select * fromstudent"; DataTable dt=DbHelperSQL.Query(strSql).Tables[0]; if (null != dt &&dt.Rows.Count > 0) { for (int i = 0; i
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,代码如下:

 服务寄宿程序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会自动生成对服务的应用配置文件和代理类,如果需要手动生成,可以参考。添加MainForm.aspx页面,前端代码如下:

<%@ PageLanguage="C#" AutoEventWireup="true"CodeBehind="MainForm.aspx.cs"EnableEventValidation="false" Inherits="Client.MainForm" %>  
var prevselitem = null; function selectx(row) { if (prevselitem != null) { prevselitem.style.backgroundColor = '#ffffff'; } row.style.backgroundColor ='PeachPuff'; prevselitem = row; }
       
           
         

编号

姓名

年龄

年级

家庭地址

后台代码如下:

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(" ");                BindData();            }            else            {               Response.Write(" ");            }        }         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程序,我没有讲太多的原理,这个在网络上可以搜索到很多对概念的解释,我这个以实际操作为准,对平时学习的一个积累,如有不当之处,欢迎指出,共同学习进步。

 

转载于:https://www.cnblogs.com/wangweimutou/p/3833091.html

你可能感兴趣的文章
两个集合相减怎么算_你家使用的防火窗(耐火窗)质量合格吗?怎么判断好坏呢?...
查看>>
ue4加载本地图片_UE4引擎初始化原理详细讲解
查看>>
python整数作为条件_Python整数类型(int)详解
查看>>
如何开搓饵不掉钩_别限制鱼钩的选择,详谈弹簧钩在实战做钓的选择和应用
查看>>
lisp自动生成中垂线_【翻译】自动柯里化Rust函数
查看>>
心电图心电轴怎么计算_基础心电图速成宝典
查看>>
怎样对流媒体进行压力测试_企业怎样通过新媒体进行引流推广?
查看>>
msf win10漏洞_永恒之黑:CVE20200796漏洞复现
查看>>
华为nova5iotg功能使用_华为手机录屏功能和投屏功能都那么强大,说没用过真的合适吗?...
查看>>
卡路里消耗软件_精心计算卡路里,效果却不如意。减重的你其实可以用一个“手掌”来轻松搞定。...
查看>>
外接显示器设置_iPad Pro 2018/2020 Type-C to DP外接显示器的一点体验 「Soomal」
查看>>
选中内容_小技法:防止对话框中的编辑框内容自动被选中
查看>>
vue前端验证输入_vue实现6位验证码输入框的实例代码
查看>>
tewa600agm是千兆吗_请问电信天翼网关光纤猫超级用户 型号tewa-600aem/tewa600agm
查看>>
jpa transaction 回滚_如何让Spring @Transactional回滚所有未捕获的异常?
查看>>
教改系统 源码_教务管理信息系统源代码
查看>>
wps右键失效_鼠标左键失灵右键代替左键怎么设置
查看>>
cc2530单片机的内核是什么_ZigBee技术开发:CC2530单片机原理及应用简介,目录书摘...
查看>>
学完python基础后该学什么专业_没有基础该怎么学Python,学完后好不好找工作
查看>>
keepalived 多个应用_keepalived 实现 Java 服务的高可用(主备切换)
查看>>