WCF 开发示例向导 -- 经典推荐!

这篇文章简要介绍了Windows communication Foundation (WCF),以及如何在应用程序中调用WCF 服务,非常适合WCF 的初学者。 --- CodeProject.com WCF 开发向导经典推荐!!! http://forum.EntLib.com 开源ASP.NET 论坛小组奉献。
 
WCF 简介
Windows Communication Foundation (WCF) 是.NET Framework 的扩展,用来创建互连的系统。WCF 提供了创建安全的、可靠的、事务服务的统一框架,WCF 整合和扩展了现有分布式系统的开发技术,如Microsoft .Net Remoting、Web Services、Web Services Enhancements (WSE)等等,来开发统一的可靠系统。WCF 框架可以实现SOA架构的松散耦合的应用程序,
 

WCF 简化了构建SOA架构应用的工作,同时通过统一Enterprise Services、Messaging、.Net Remoting、Web Services、WSE 等技术,降低开发复杂度。WCF服务可以通过属性Attribute进行配置,提高灵活性和效率,支持大量的Web Services标准,如XML、XSD、SOAP、Xpath、WSDL等标准和规范,如WS-Addressing、WS-Policy、WS-Security、WS-Trust、WS-Secure、WS-Reliable Messaging、WS-Atomic Transaction、WS-Coordination等等。下图描绘了Windows communication Foundation (WCF) 框架模型:



WCF 通信模型

WCF 遵从客户/服务端模型在应用程序间建立通信,客户端程序通过服务端公布的Endpoints端点来直接访问服务。Endpoints 是发送或接收消息的一个地址,每一个服务WCF Service可以有多个Endpoints。



 
WCF 服务由如下几个主要组件组成,下图表示了这些组件如何进行交互:
  • Service Contract
  • Operation Contract
  • Data Contract
  • Data Member



Service Contract
Service Contract 定义了会话中的消息方向和类型,用一个接口或类订阅WCF的Service Contract。Service Contract 是外部应用程序访问服务方法的一个通道,在一个服务中至少应该有一个ServiceContract。ServiceContract的定义如下:
    [ServiceContract]
    public interface IWCFForumService
    {
        [OperationContract]
        string GetMessage(int messageID);
 
        [OperationContract]
        IEnumerable GetMessageInfo(int messageID);
    }
http://forum.EntLib.com 开源ASP.NET论坛小组备注:这里的示例代码采用开源论坛EntLib_BBS数据库,你可以很方便地改用其他数据库。
 
上述接口的ServiceContract attribute 表明这是一个Service Contract,同时Service Contract定义了服务中可用的方法,WCF 服务中的方法与Web services 中的方法比较类似。IWCFForumService 是Forum 的Service接口,公布了服务中所有的OperationContract 方法给外部系统。
 
Operation Contract
Operation Contract 定义了WCF 服务中提供给外部系统访问的方法。OperationContract attribute 需要应用到这些方法上,就像Web services 中的Web method 一样。Operation Contract 的示例代码参考IWCFForumService 接口定义。
 
Data Contract
Data Contract 定义了一系列DataMember,作为一个组合类型(Composite type)在ServiceContract 中使用。通过应用DataContract attribute给一个类来定义Data Contract,Data Contract需要通过serializer 进行序列化。通过应用DataMember attribute 到成员变量上,DataMember 成员变量需要序列化。MessageInfo – Data Contract 的定义如下:
    [DataContract]
    public class MessageInfo
    {
        private int _messageID;
        private DateTime _postedDate;
        private string _message;
        [DataMember]
        public int MessageID
        {
            get { return _messageID; }
            set { _messageID = value; }
        }
        [DataMember]
        public DateTime PostedDate
        {
            get { return _postedDate; }
            set { _postedDate = value; }
        }
        [DataMember]
        public string Message
        {
            get { return _message; }
            set { _message = value; }
        }
    }

 
Data Member
DataMember attribute 可以应用到私有成员变量(Private member)上,需要序列化和反序列化,可以访问存取。DataMember的用法参考上面MessageInfo 的定义。

使用Visual Studio 2008 创建WCF 应用程序
这里简要说明操作步骤: New Project 类型 – 选择WCF Service Application,默认的项目中包含有IService1.cs, Service1.svc , Service1.svc.cs, web.config 等文件。
 
其中IServices1 接口有ServiceContract attribute,并且其中的方法也定义了OperationContract attribute。Service1 是IService1 接口的具体实现,Endpoints 和其他行为属性在web.config 配置文件的system.serviceModel 节点定义。
 
如果你改变services 的名称,你需要同时更改 web.config 配置文件中的相关配置,否则外部系统不能识别服务。
 
 
定制默认的WCF 服务
现在我们根据实际示例项目的需求,更改默认的WCF 服务。第一步是对现有的服务文件进行改名,或删除现有的文件,然后增加新的文件。在本示例程序中,我们采用第一种方法,对现有的文件进行改名。
 
对IService1.cs 改名为IWCFForumService.cs,Service1.svc 改名为 WCFForumService.svc。代码文件Service1.svc.cs 会自动更名为 WCFForumService.svc.cs。下一步,需要更改web.config 的相关配置。
         <services>
              <service behaviorConfiguration="WcfServiceEntlib.ServiceBehavior" name="WcfServiceEntlib.WCFForumService">
                   <endpoint address="" binding="wsHttpBinding" contract="WcfServiceEntlib.IWCFForumService">
                   </endpoint>
                   <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
              </service>
         </services>
 
同时,对IWCFForumService.cs 代码进行修改,代码如下。另外,增加DataContact 类 – MessageInfo.cs,其中的成员变量通过DataMemeber 进行标识,MessageInfo 将作为DataContract 在 IWCFForumService 中使用。MessageInfo 是一个独立的类,标识为public,允许外部系统访问。
 
WCFForumService 则是对 IWCFForumService接口的实现类,代码如下:
        private string strConn = ConfigurationManager.ConnectionStrings["EntLibForum"].ConnectionString;
 
        public string GetMessage(int messageID)
        {
            string msg = string.Empty;
 
            string strSelect = "Select Message From yaf_message where MessageID=" + messageID.ToString();
 
            using (SqlConnection connection = new SqlConnection(strConn))
            {
                SqlCommand command = new SqlCommand(strSelect, connection);
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                try
                {
                    if (reader.Read())
                    {
                        msg = reader["Message"].ToString().Trim();
                    }
                }
                finally
                {
                    // Always call Close when done reading.
                    reader.Close();
                }
            }
 
            return msg;
        }
 
        public MessageInfo GetMessageInfo(int messageID)
        {
            MessageInfo messageInfo = null;
            string strSelect = "Select * From yaf_message where MessageID=" + messageID.ToString();
 
            using (SqlConnection connection = new SqlConnection(strConn))
            {
                SqlCommand command = new SqlCommand(strSelect, connection);
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                try
                {
                    if (reader.Read())
                    {
                        messageInfo = new MessageInfo();
                        messageInfo.MessageID = messageID;
                        messageInfo.Message = reader["Message"].ToString().Trim();
                        messageInfo.PostedDate = Convert.ToDateTime(reader["Posted"]);
                    }
                }
                finally
                {
                    // Always call Close when done reading.
                    reader.Close();
                }
            }
           
            return messageInfo;
        }
 
 
承载和测试WCF 服务
WCF 服务可以部署在IIS 6.0、Windows Activation Service (WAS) with vista 和 IIS 7.0。本示例中,我们采用IIS 6.0部署WCF 服务。编译、运行WCF 示例程序,从IE浏览器显示的文件列表,选择WCFForumService.svc 文件。



 
如果没有客户端程序,你不能直接测试WCF 服务,就像web service 一样。
Microsoft 提供了一个简单的方法来测试WCF 服务 – WcfTestClient 工具(关于该工具的具体介绍,请参考文章: http://forum.entlib.com/Default.aspx?g=posts&t=233 )。如果WCF 服务承载在WCF Service Host (WcfSvcHost.exe) ,WcfTestClient 工具将自动打开并运行。你也可以通过命令行来运行WcfTestClient 工具,脚本如下:
 
C :/> WcfTestClient http://localhost:4691/WCFForumService.svc
 
http://localhost:4691/WCFForumService.svc 是等待测试的WCF 服务地址。WcfTestClient 在左侧面板显示暴露的方法,同时在右上侧面板也可以输入参数。当输入参数后,点击Invoke 按钮,将调用指定的WCF 方法,在右下侧面板显示结果。


调用 WCF 服务
WCF 服务可以由客户端的应用程序来调用,因此调用WCF 服务的第一步是创建WCF 客户端程序和相关的配置文件。 Service Model Metadata 工具(Svcutil.exe)是一个命令行工具,可以用来创建WCF 客户端。另外,也可以通过增加Service 引用来创建WCF 客户端,本示例程序采用这种方法。
 
 
创建WCF 客户端
在 Visual Studio 2008 – Windows Form Application 项目中,增加Service 引用。在弹出的Add Service Reference 窗口,输入相应的WCF Service 的地址。示例窗口如下:
 

 
点击 OK 按钮后,项目文件如下,增加了WCFForumServiceReference 的引用:
 


 
使用 WCF Client
创建 WCF Client 实例与WCF 服务进行交互。如下代码创建了 WCF Client Proxy 实例对象:
WCFForumServiceClient wcfForumServiceClient = new
     WCFForumServiceClient("WSHttpBinding_IWCFForumService");
 
WCFForumServiceClient 是增加WCF 服务引用时,自动生成的WCF Client 类。WSHttpBinding 是端点绑定方法,在web.config 配置文件中进行指定,IWCFForumService 是WCF 服务接口对象。
 
在创建并实例化 WCF Client Proxy 代理对象后,就可以像访问Web Service 一样,访问WCF 公布的方法了。 调用GetTOP10Messages() 和 GetMessage() 方法的示例代码如下:
        private void btnRetrieveMessage_Click(object sender, EventArgs e)
        {
            MessageInfo[] messageList = new MessageInfo[]{};
 
            messageList = wcfForumServiceClient.GetTOP10Messages();
 
            grdTop10.DataSource = messageList;
            grdTop10.Columns[0].DataPropertyName = "MessageID";
            grdTop10.Columns[0].HeaderText = "MessageID";
            grdTop10.Columns[1].DataPropertyName = "Message";
            grdTop10.Columns[1].HeaderText = "帖子内容";
            grdTop10.Columns[1].Width = 300;
            grdTop10.Columns[2].DataPropertyName = "PostedDate";
            grdTop10.Columns[2].HeaderText = "发布时间";
 
        }
 
        private void btnRetrieveSpecifiedMessage_Click(object sender, EventArgs e)
        {
            if (CheckValid())
            {
                int iMessageID = int.Parse(txtMessageID.Text.Trim());
 
                lblMessage.Text = wcfForumServiceClient.GetMessage(iMessageID);
            }
        }
 
WCF 客户端示例程序运行界面如下:
 



这仅仅是WCF (Windows Communication Foundation ) 框架的一个入门示例文章。欢迎访问 http://forum.EntLib.com 开源ASP.NET 论坛,有更多资源和文章。
 
 
Reference:
1. Codeproject.com, Windows Communication Foundation (WCF) Overview, by Deepthi Viswanathan Nair
http://www.codeproject.com/KB/WCF/WCFOverview.aspx
 
 

WCF_Tutorial_EntLib_20080924.zip

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值