标签:on() oda pil 代理类 cts 3.4 分享 文件 div
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
namespace RoomReservationContracts
{
/// <summary>
/// 数据协定
/// </summary>
[DataContract]
public class RoomReservation : INotifyPropertyChanged
{
private int _id;
private string _roomName;
private DateTime _startTime;
private DateTime _endTime;
private string _contact;
private string _text;
/// <summary>
///要通过WCF服务发送数据, 引入DataContract 和 DataMember 特性对该类进行注解
/// </summary>
[DataMember]
public int Id
{
get { return _id; }
set { SetProperty(ref _id, value); }
}
[DataMember]
[StringLength(45)]
public string RoomName
{
get { return _roomName; }
set { SetProperty(ref _roomName, value); }
}
[DataMember]
public DateTime StartTime
{
get { return _startTime; }
set { SetProperty(ref _startTime, value); }
}
[DataMember]
public DateTime EndTime
{
get { return _endTime; }
set { SetProperty(ref _endTime, value); }
}
[DataMember]
[StringLength(45)]
public string Contact
{
get { return _contact; }
set { SetProperty(ref _contact, value); }
}
[DataMember]
[StringLength(45)]
public string Text
{
get { return _text; }
set { SetProperty(ref _text, value); }
}
/// <summary>
/// 接口需实现的事件方法
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// 得知属性发生变更时(定义为protected virtual 允许子类覆写本方法)
/// </summary>
/// <param name="propertyName">属性字段</param>
protected virtual void OnNotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// 设置属性
/// </summary>
/// <typeparam name="T">传入的类型参数</typeparam>
/// <param name="item">字段名</param>
/// <param name="value">字段值</param>
/// <param name="propertyName"></param>
protected virtual void SetProperty<T>(ref T item,T value,[CallerMemberName] string propertyName = null)
{
//如果两个类型的对象T 是否不等
if (!EqualityComparer<T>.Default.Equals(item, value))
{
item = value;
OnNotifyPropertyChanged(propertyName);
}
}
}
}
using System;
using System.ServiceModel;
namespace RoomReservationContracts
{
/// <summary>
/// 服务协定
/// </summary>
[ServiceContract(Namespace ="http://www.myfirstwcfservice.com/RoomReservation/2017")]
public interface IRoomService
{
[OperationContract]
bool ReserveRoom(RoomReservation roomReservation);
[OperationContract]
RoomReservation[] GetRoomReservations(DateTime fromTime, DateTime dateTime);
}
}
本实例中使用自定义的数据访问类,基于反射实现的数据访问接口。采用该类添加RoomReservationData 类库,实现具体操作协定。
using System;
using RoomReservationContracts;
using Net.BCloudSoft.Core.DataAccess;
using System.Data;
using System.Collections.Generic;
namespace RoomReservationData
{
/// <summary>
/// 实现服务类
/// </summary>
public class RoomReservationRepository
{
/// <summary>
/// 预订房间
/// </summary>
/// <param name="roomReservation"></param>
public bool ReserveRoom(RoomReservation roomReservation)
{
try
{
IDataAccess dataAccess = DataAccessFactory.Instance().GetDataAccess("server=127.0.0.1;database=wcfstudy_db;uid=root;pwd=admin;");
string insertSql = string.Format("INSERT INTO wcfstudy_db.roomreservations VALUES" +
"({0},‘{1}‘,‘{2}‘,‘{3}‘,‘{4}‘,‘{5}‘)",
roomReservation.Id,
roomReservation.RoomName,
roomReservation.StartTime,
roomReservation.EndTime,
roomReservation.Contact,
roomReservation.Text);
dataAccess.ExecuteNonQuery(insertSql);
return true;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 获取所有预订信息
/// </summary>
/// <param name="fromTime"></param>
/// <param name="toTime"></param>
/// <returns></returns>
public RoomReservation[] GetReservations(DateTime fromTime,DateTime toTime)
{
try
{
IDataAccess dataAccess = DataAccessFactory.Instance().GetDataAccess("MySqlDataAccess");
DataTable dt = dataAccess.ExecuteDataTable(string.Format("SELECT * FROM [wcfstudy_db].[roomreservations] WHERE [StartTime] > ‘{0}‘ AND [EndTime] <‘{1}‘", fromTime, toTime));
List<RoomReservation> list = new List<RoomReservation>();
foreach (DataRow row in dt.Rows)
{
RoomReservation roomReservation = new RoomReservation();
roomReservation.Id = int.Parse(row["Id"].ToString());
roomReservation.RoomName = row["RoomName"].ToString();
roomReservation.StartTime = Convert.ToDateTime(row["StartTime"]);
roomReservation.EndTime = Convert.ToDateTime(row["EndTime"]);
roomReservation.Contact = row["Contact"].ToString();
roomReservation.Text = row["Text"].ToString();
list.Add(roomReservation);
}
return list.ToArray();
}
catch (Exception ex)
{
throw ex;
}
}
}
}
using System;
using RoomReservationContracts;
using RoomReservationData;
using System.ServiceModel;
namespace RoomReservationService
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class RoomReservationService : IRoomService
{
/// <summary>
/// 获取所有预订信息
/// </summary>
/// <param name="fromTime">开始时间</param>
/// <param name="dateTime">结束时间</param>
/// <returns></returns>
public RoomReservation[] GetRoomReservations(DateTime fromTime, DateTime dateTime)
{
RoomReservationRepository repository = new RoomReservationRepository();
return repository.GetReservations(fromTime, dateTime);
}
/// <summary>
/// 预订房间
/// </summary>
/// <param name="roomReservation"></param>
/// <returns></returns>
public bool ReserveRoom(RoomReservation roomReservation)
{
RoomReservationRepository repository = new RoomReservationRepository();
return repository.ReserveRoom(roomReservation);
}
}
}
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" />
</system.web>
<!-- 部署服务库项目时,必须将配置文件的内容添加到
主机的 app.config 文件中。System.Configuration 不支持库的配置文件。 -->
<system.serviceModel>
<services>
<!--service 节点中 配置 实现类-->
<service name="RoomReservationService.RoomReservationService">
<!--contract 节点中配置接口类-->
<endpoint address="" binding="basicHttpBinding" contract="RoomReservationContracts.IRoomService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8733/Design_Time_Addresses/RoomReservationService/Service1/" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- 为避免泄漏元数据信息,
请在部署前将以下值设置为 false -->
<serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/>
<!-- 要接收故障异常详细信息以进行调试,
请将以下值设置为 true。在部署前设置为 false
以避免泄漏异常信息 -->
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
(4)使用WCF服务宿主和WCF测试客户端
查看数据库,可知数据已经完成写入操作
(5)创建定制的服务宿主
using System; using System.ServiceModel; using System.ServiceModel.Description; using RoomReservationService; using static System.Console; /// <summary> /// 自定义服务宿主 /// </summary> namespace RoomReservationHost { public class Program { internal static ServiceHost _serviceHost = null; /// <summary> /// 开启服务监听 /// </summary> internal static void StartService() { try { //ServiceHost的构造函数第二个参数定义了服务的基地址,可以设置默认绑定,HTTP //的默认值是basicHttpBinding _serviceHost = new ServiceHost(typeof(RoomReservationService.RoomReservationService), new Uri("http://localhost:9000/RoomReservation")); _serviceHost.Description.Behaviors.Add( new ServiceMetadataBehavior { //获取设置一个值,指示是否发布服务元数据以使用Http/Get请求进行检索。 HttpGetEnabled = true }); } catch (AddressAccessDeniedException) { WriteLine("地址禁止访问,使用netsh.exe 注册监听端口"); throw; } } /// <summary> /// 停止服务监听 /// </summary> internal static void StopService() { if(_serviceHost != null && _serviceHost.State== CommunicationState.Opened) { _serviceHost.Close(); } } static void Main() { StartService(); WriteLine("服务正在运行,请退出"); ReadLine(); StopService(); } } }
根据数据协定把RoomReservation 引入到RoomReservationClient 中,RoomServiceClient 是RoomReservationService的客户端代理类(RoomServiceClient 是由上图执行后生成的),该客户端包含由操作协定定义的方法,使用这个客户端,可以将会议室预定信息发送给正在运行的服务。
using System; using System.Windows; using RoomReservationClient.RoomReservationService; namespace RoomReservationClient { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { private RoomReservationService.RoomReservation _roomReservation; public MainWindow() { InitializeComponent(); _roomReservation.StartTime = DateTime.Now; _roomReservation.EndTime = DateTime.Now.AddHours(1); this.DataContext = _roomReservation; } private async void onReserveRoom(object sender, RoutedEventArgs e) { //RoomServiceClient 是客户端的代理,该客户端包含由操作协定定义的方法,使用这个客户端, //可以将会议室预定信息发送给正在运行的服务。 var client = new RoomServiceClient(); bool reserved = await client.ReserveRoomAsync(_roomReservation); client.Close(); if (reserved) { MessageBox.Show("实体保存成功!"); } } } }
6、最后
参考的案例还有诊断及与客户端共享协定程序集两部分内容,两部分内容的具体实现并没有跟着书本完成,有兴趣的同学可以自行查看,参考的源代码路径为http://www.wrox.com/go/professionalcsharp6
标签:on() oda pil 代理类 cts 3.4 分享 文件 div
原文地址:http://www.cnblogs.com/cklovefan/p/7956449.html