[WCF Step by Step 读书笔记] Chapter01 WCF 介绍
下面通过搭建一个书中完整的WCF的例子阐述WCF:
1. 建立一个ASP.NET WebSite的的空工程ProductService。
2. 添加一个Class Library的工程,删除其.cs文件,添加一个ADO.NET Entity Model,从数据库选择AdventureWorks数据库,用到的两张表为Product和ProductInventory。其余使用默认值。
3. 在ProductService工程里添加对第二步Class Library的引用。
4. 在ProductService空工程里添加WCF Service项。这个时候,我们会发现项目里多了一个App_Code文件夹,里面存放着IService.cs和Service.cs两个文件,同时多出了一个Service.svc的文件。
5. 将IService.cs和Service重命名为IProductService和ProductService。
6. IProductService的内容为:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;namespace Products
{
// Data contract describing the details of a product passed to client applications
[DataContract]
public class ProductData
{
[DataMember]
public string Name;[DataMember]
public string ProductNumber;[DataMember]
public string Color;[DataMember]
public decimal ListPrice;
}// Service contract describing the operations provided by the WCF service
[ServiceContract]
public interface IProductsService
{
// Get the product number of every product
[OperationContract]
List<string> ListProducts();// Get the details of a single product
[OperationContract]
ProductData GetProduct(string productNumber);// Get the current stock level for a product
[OperationContract]
int CurrentStockLevel(string productNumber);// Change the stock level for a product
[OperationContract]
bool ChangeStockLevel(string productNumber, short newStockLevel, string shelf, int bin);
}
}这里对WCF Service可以提供的方法和数据类型进行了定义。WCF的runtime在收到相应的请求的Message以后,可以将其中内容传递给这些标注了[OperationContract]的方法,而返回操作时,也可以将结果通过runtime打包到message里返回。
[ServiceContract]表明这是这个类是用来提供WCF的Runtime需要运行的类。而[OperationContract]则是这个Runtime所能执行到方法。这两个Attribute都位于System.ServiceModel名空间里面。
而[DataContract]和[DataMember]用于对需要在Host和Client之间进行传递的数据对象的类型进行定义。他们位于System.Runtime.Serialization名空间里面。可见DataContract修饰的是Class,而DataMember修饰的是Field。
7. ProductService的内容是:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;using System.Data.Entity;
using ProductsEntityModel;namespace Products
{
// WCF service that implements the service contract
// This implementation performs minimal error checking and exception handling
public class ProductsServiceImpl : IProductsService
{
public List<string> ListProducts()
{
// Create a list for holding product numbers
List<string> productsList = new List<string>();try
{
// Connect to the AdventureWorks database by using the Entity Framework
using (AdventureWorksEntities database = new AdventureWorksEntities())
{
// Fetch the product number of every product in the database
var products = from product in database.Products
select product.ProductNumber;productsList = products.ToList();
}
}
catch
{
// Ignore exceptions in this implementation
}// Return the list of product numbers
return productsList;
}public ProductData GetProduct(string productNumber)
{
// Create a reference to a ProductData object
// This object will be instantiated if a matching product is found
ProductData productData = null;try
{
// Connect to the AdventureWorks database by using the Entity Framework
using (AdventureWorksEntities database = new AdventureWorksEntities())
{
// Find the first product that matches the specified product number
Product matchingProduct = database.Products.First(
p => String.Compare(p.ProductNumber, productNumber) == 0);productData = new ProductData()
{
Name = matchingProduct.Name,
ProductNumber = matchingProduct.ProductNumber,
Color = matchingProduct.Color,
ListPrice = matchingProduct.ListPrice
};
}
}
catch
{
// Ignore exceptions in this implementation
}// Return the product
return productData;
}public int CurrentStockLevel(string productNumber)
{
// Obtain the total stock level for the specified product.
// The stock level is calculated by summing the quantity of the product
// available in all the bins in the ProductInventory table.// The Product and ProductInventory tables are joined over the
// ProductID column.int stockLevel = 0;
try
{
// Connect to the AdventureWorks database by using the Entity Framework
using (AdventureWorksEntities database = new AdventureWorksEntities())
{
// Calculate the sum of all quantities for the specified product
stockLevel = (from pi in database.ProductInventories
join p in database.Products
on pi.ProductID equals p.ProductID
where String.Compare(p.ProductNumber, productNumber) == 0
select (int)pi.Quantity).Sum();
}
}
catch
{
// Ignore exceptions in this implementation
}// Return the stock level
return stockLevel;
}public bool ChangeStockLevel(string productNumber, short newStockLevel,
string shelf, int bin)
{
// Modify the current stock level of the selected product
// in the ProductInventory table.
// If the update is successful then return true, otherwise return false.// The Product and ProductInventory tables are joined over the
// ProductID column.try
{
// Connect to the AdventureWorks database by using the Entity Framework
using (AdventureWorksEntities database = new AdventureWorksEntities())
{
// Find the ProductID for the specified product
int productID =
(from p in database.Products
where String.Compare(p.ProductNumber, productNumber) == 0
select p.ProductID).First();// Find the ProductInventory object that matches the parameters passed
// in to the operation
ProductInventory productInventory = database.ProductInventories.First(
pi => String.Compare(pi.Shelf, shelf) == 0 &&
pi.Bin == bin &&
pi.ProductID == productID);// Update the stock level for the ProductInventory object
productInventory.Quantity += newStockLevel;// Save the change back to the database
database.SaveChanges();
}
}
catch
{
// If an exception occurs, return false to indicate failure
return false;
}// Return true to indicate success
return true;
}
}
}这里是对IProductServic定义的方法的具体实现。
8. 在Service.svc里面将其内容改为:
<%@ ServiceHost Language="C#" Debug="true" Service="Products.ProductsServiceImpl" CodeBehind="~/App_Code/ProductsService.cs" %>
注意这里ServiceHost表明IIS将作为这个WCF的Runtime,提供的Service的具体内容是实现了Product.ProductServiceImpl这个类型,而这个类的代码在ProductsService.cs这个文件里面。
9. 在网站的web.config的配置文件里添加connectionString(这里的ConnectionString实际上可以直接从ClassLibrary工程的App.config直接拷贝过来):
<connectionStrings>
<add name="AdventureWorksEntities" connectionString="metadata=res://*/ProductsModel.csdl|res://*/ProductsModel.ssdl|res://*/ProductsModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLExpress;Initial Catalog=AdventureWorks;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" /></connectionStrings>
注意这里metadata可能会发生链接错误的情况,这时候可以直接将其值改为metadata=res://*/,这样所有的assembly都会成为考虑对象。
10. 右键点击Service.svc运行,将浏览器出现的地址添加到WcfTestClient中,查看WCF提供的相应方法能否运行。
注意如果Visual Studio内的WCF能够运行,但是在IIS上部署以后从数据库得不到数据,注意查看应用程序池的Identity,查看其权限是否足够。
转载于:https://www.cnblogs.com/charrli/archive/2011/02/17/1957363.html
[WCF Step by Step 读书笔记] Chapter01 WCF 介绍相关推荐
- WCF 4 高级编程 - 读书笔记
第2章 服务契约与数据契约 在SOA架构中,契约提供了服务通信所必需的元数据.契约用来定义数据类型.操作.消息交换模式和消息交换使用的传输协议.契约通常是XML格式发布的.在WCF中,服务元数据通常是 ...
- 【读书笔记】iOS-iCloud介绍
iCloud是一种面向消费者市场的云存储服务,苹果公司已经做了大量的工作让用户能够平滑过渡到iCloud,不过对开发者而言这意味着新的负担. 怎样使用iCloud? 你可以使用2种方式在你的应用中使用 ...
- 《算法图解》读书笔记
这是一本很入门的算法书,介绍的东西还算简单明了,大体补充了一些自己没理解的东西. 粗略地看了一下,感觉还是"纸上得来终觉浅,绝知此事要躬行!" <<算法图解>&g ...
- ZYNQ PS端模块读书笔记-XADC
作者:ShownSun 工作室:时沿科技 文章目录 ZYNQ PS端模块读书笔记-XADC 1 介绍 1.1 特色 1.2 系统视角 1.3 PS-XADC接口框图 1.4 编程指南 2 功能描述 2 ...
- 《设计模式与游戏完美开发》——第六周读书笔记
在上一周的读书笔记中我介绍了中介者模式,本周的读书笔记来介绍一下桥接模式. 前言 现在流行的游戏都是有武器的.一个游戏不可能让玩家从头打到尾都是一把''小手枪''.例如,现在特别火的<贪婪洞窟2 ...
- MDX Step by Step 读书笔记 - 个人专题(一) 如何理解 MDX 查询中WHERE 条件如何对应Cube 中的切片轴 Slicer Axis...
这篇文章原本应该写在第四章的读书笔记里, 但是篇幅太长,而且主要示例和图解都是基于我自己的理解, 所以单独成文(可以先看看第四章读书笔记内容). 这一部分基础内容我个人觉得非常重要, 之前看过一次 M ...
- 转~MDX Step by Step 读书笔记(四) - Working with Sets
查阅我的其它有关 MDX 的学习笔记 - <<Microsoft SQL Server 2008 MDX Step by Step>> 学习笔记连载目录 1. Set - 元 ...
- pro git读书笔记
pro git读书笔记 起步 三种区域以及三种状态 Git 项目有三个工作区域的概念:工作目录,暂存区域以及Git 仓库 工作目录是我们用来修改文件的目录,是对项目的某个版本独立提取出来的内容 暂存区 ...
- iText in Action 2nd4.2节(Changing the properties of a cell)读书笔记
前言 PdfPCell类继承于Rectangle类,因此也继承了很多修改边框和背景色的属性和方法,后续我们会讨论到,但现在我们先要说明PdfPCell的内容模式.在iText的内部PdfPCell的内 ...
最新文章
- opencv findContours 崩溃CrtDbgBreak
- ASP.NET应用程序与页面生命周期
- leetcode 394. Decode String | 394. 字符串解码(用栈做表达式转换)
- sqlplus环境配置(login.sql)
- java应用部署docker_Docker部署JavaWeb项目实战
- java 设计模式 prototype_Java设计模式之Prototype原型模式
- dev_t的主次编号
- css用边框实现圆角矩形
- 《视觉SLAM十四讲》课后习题—ch7(更新中……)
- 爱创课堂每日一题第三十三天- 如何评价AngularJS和BackboneJS?
- RecyclerView 数据刷新的几种方式 局部刷新 notify MD
- 阿里巴巴 Java 性能调优手册
- 软件开发各类文档模板
- WebView文件下载
- python图像质量评价_OpenCV--Python 图像质量评价.docx
- jenkins 插件_Jenkins通过Ruby插件赢得了新的皇冠
- QDateTime 和tm 的时间显示
- 【面试题】单链表的操作2
- crtsiii型无砟轨道板_北京雄安城际全线轨道贯通:全程设5座车站,1小时通勤,“刷脸”进站...
- 由先序遍历和中序遍历得到后序遍历和层次遍历(二叉树)