我的第一个WCF程序
写WCF,VS需要一管理员身份呢启动,否则服务无法访问。
model层
using System;
using System.Runtime.Serialization; namespace MyModel
{
[DataContract]
public class User
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string UserName { get; set; }
[DataMember]
public string Password { get; set; }
[DataMember]
public string Truename { get; set; }
[DataMember]
public string Sex { get; set; }
[DataMember]
public DateTime Birthday { get; set; }
[DataMember]
public string Phone { get; set; }
[DataMember]
public string Email { get; set; }
[DataMember]
public DateTime CreateTime { get; set; }
}
}
using System.Runtime.Serialization; namespace MyModel
{
[DataContract]
public class FaultMessage
{
[DataMember]
public string Message { get; set; }
[DataMember]
public string ErrorCode { get; set; }
}
}
dao层
using MyDao.ModelRecords; namespace MyDao.Interface
{
public interface IUserDao
{
int Insert(UserRecord user);
void Delete(int id);
void Update(UserRecord user);
UserRecord GetUserById(int id);
}
}
using MyDao.Interface;
using MyDao.ModelRecords;
using MyUtil; using System;
using System.Data;
using System.Data.SqlClient;
using System.Globalization; namespace MyDao
{
public class UserDao : IUserDao
{
//private UserDao()
//{
// //:Empty
//} //private static UserDao userDao = new UserDao(); //public static UserDao Instance()
//{
// return userDao;
//}
public int Insert(UserRecord user)
{
int id = ;
SqlParameter[] parameters=new SqlParameter[];
parameters[] = new SqlParameter(Constants.USERNAME, user.UserName);
parameters[] = new SqlParameter(Constants.PASSWORD, user.Password);
parameters[] = new SqlParameter(Constants.TRUENAME, user.Truename);
parameters[] = new SqlParameter(Constants.SEX, user.Sex);
parameters[] = new SqlParameter(Constants.BIRTHDAY, user.Birthday);
parameters[] = new SqlParameter(Constants.PHONE, user.Phone);
parameters[] = new SqlParameter(Constants.EMAIL, user.Email);
id=Convert.ToInt32(MySqlHelper.ExecuteScalar(MySqlHelper.GetConnecting(),CommandType.StoredProcedure,Constants.INSERT_USER_RETURN_ID,parameters),CultureInfo.InvariantCulture); return id;
} public void Delete(int id)
{
SqlParameter[] parameters = new SqlParameter[];
parameters[] = new SqlParameter(Constants.ID, id);
MySqlHelper.ExecuteNonQuery(MySqlHelper.GetConnecting(), CommandType.StoredProcedure, Constants.DELETE_USER_BY_ID, parameters);
} public void Update(UserRecord user)
{
SqlParameter[] parameters = new SqlParameter[];
parameters[] = new SqlParameter(Constants.ID, user.Id);
parameters[] = new SqlParameter(Constants.PASSWORD, user.Password);
MySqlHelper.ExecuteNonQuery(MySqlHelper.GetConnecting(), CommandType.StoredProcedure, Constants.DELETE_USER_BY_ID, parameters);
} public UserRecord GetUserById(int id)
{
UserRecord user = new UserRecord();
SqlParameter[] parameters = new SqlParameter[];
parameters[] = new SqlParameter(Constants.ID, id);
DataTable dt = MySqlHelper.ExecuteDataTable(MySqlHelper.GetConnecting(), CommandType.StoredProcedure, Constants.GTE_USER_BY_ID, parameters); foreach (DataRow dr in dt.Rows)
{
DataRowConvertToUser(dr, user);
} return user;
} public void DataRowConvertToUser(DataRow dr, UserRecord user)
{
user.Id = int.Parse(dr[Constants.M_ID].ToString(), CultureInfo.InvariantCulture);
user.UserName = dr[Constants.M_USERNAME].ToString();
user.Password = dr[Constants.M_PASSWORD].ToString();
user.Truename = dr[Constants.M_TRUENAME].ToString();
user.Sex = dr[Constants.M_SEX].ToString();
user.Birthday = Convert.ToDateTime(dr[Constants.M_BIRTHDAY], CultureInfo.InvariantCulture);
user.Phone = dr[Constants.M_PHONE].ToString();
user.Email = dr[Constants.M_EMAIL].ToString();
user.CreateTime = Convert.ToDateTime(dr[Constants.M_CREATE_TIME], CultureInfo.InvariantCulture);
}
}
}
namespace MyDao
{
public class Constants
{
#region stored procedure field
public const string ID = "@id";
public const string USERNAME = "@userName";
public const string PASSWORD = "@password";
public const string TRUENAME = "@trueName";
public const string SEX = "@sex";
public const string BIRTHDAY = "@birthday";
public const string PHONE = "@phone";
public const string EMAIL = "@email";
#endregion #region stored procedure name
public const string INSERT_USER_RETURN_ID = "InsertUserReturenId";
public const string DELETE_USER_BY_ID = "DeleteUserById";
public const string UPDATE_USER = "UpdateUser";
public const string GTE_USER_BY_ID = "GetUserById";
#endregion #region user field
public const string M_ID = "ID";
public const string M_USERNAME = "UserName";
public const string M_PASSWORD = "Password";
public const string M_TRUENAME = "TrueName";
public const string M_SEX = "Sex";
public const string M_BIRTHDAY = "Birthday";
public const string M_PHONE = "Phone";
public const string M_EMAIL = "Email";
public const string M_CREATE_TIME = "CreateTime";
#endregion
}
}
using System; namespace MyDao.ModelRecords
{
public class UserRecord
{
public int Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Truename { get; set; }
public string Sex { get; set; }
public DateTime Birthday { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public DateTime CreateTime { get; set; }
}
}
manager层
拓展方法
using MyDao.ModelRecords;
using MyModel; namespace MyManager
{
public static class RecordUser
{
public static User ConvertToUser(this UserRecord userRecord)
{
User user = new User();
user.Id = userRecord.Id;
user.UserName = userRecord.UserName;
user.Password = userRecord.Password;
user.Truename = userRecord.Truename;
user.Sex = userRecord.Sex;
user.Birthday = userRecord.Birthday;
user.Phone = userRecord.Phone;
user.Email = userRecord.Email;
user.CreateTime = userRecord.CreateTime; return user;
} public static UserRecord ConvertToUserRecord(this User user)
{
UserRecord userRecord = new UserRecord();
userRecord.Id = user.Id;
userRecord.UserName = user.UserName;
userRecord.Password = user.Password;
userRecord.Truename = user.Truename;
userRecord.Sex = user.Sex;
userRecord.Birthday = user.Birthday;
userRecord.Phone = user.Phone;
userRecord.Email = user.Email;
userRecord.CreateTime = user.CreateTime; return userRecord;
}
}
}
using MyDao;
using MyDao.Interface;
using MyManager.Interface;
using MyModel; namespace MyManager
{
public class UserManager : IUserManager
{
private IUserDao userDao = new UserDao(); public int Insert(User user)
{
int id= userDao.Insert(user.ConvertToUserRecord()); return id;
} public void Delete(int id)
{
userDao.Delete(id);
} public void Update(User user)
{
userDao.Update(user.ConvertToUserRecord());
} public User GetUserById(int id)
{
return userDao.GetUserById(id).ConvertToUser();
}
}
}
contract层
using MyModel; using System.ServiceModel; namespace MyContract
{
[ServiceContract(Name = "UserService", Namespace = "http://www.artech.com/")]
public interface UserContract
{
[OperationContract]
[FaultContract(typeof(FaultMessage))]
int Insert(User user); [OperationContract]
[FaultContract(typeof(FaultMessage))]
void Delete(int id); [OperationContract]
[FaultContract(typeof(FaultMessage))]
void Update(User user); [OperationContract]
[FaultContract(typeof(FaultMessage))]
User GetUserById(int id);
}
}
service层:
using MyContract;
using MyManager;
using MyManager.Interface;
using MyModel; using System;
using System.ServiceModel; namespace MyServices
{
public class UserService : UserContract
{
private IUserManager userManager = new UserManager(); public int Insert(User user)
{
int id = ;
try
{
id = userManager.Insert(user);
}
catch (Exception ex)
{
throw new FaultException<FaultMessage>(new FaultMessage { ErrorCode = "insert", Message = ex.Message });
} return id;
} public void Delete(int id)
{
try
{
userManager.Delete(id);
}
catch (Exception ex)
{
throw new FaultException<FaultMessage>(new FaultMessage { ErrorCode = "delete", Message = ex.Message });
}
} public void Update(User user)
{
try
{
userManager.Update(user);
}
catch (Exception ex)
{
throw new FaultException<FaultMessage>(new FaultMessage { ErrorCode = "update", Message = ex.Message });
}
} public User GetUserById(int id)
{
try
{
return userManager.GetUserById(id);
}
catch (Exception ex)
{
throw new FaultException<FaultMessage>(new FaultMessage { ErrorCode = "getUserById", Message = ex.Message });
}
}
}
}
运行main
配置文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyRole" connectionString="Data Source=.;Initial Catalog=Role;User ID=sa;Password=sa"/>
</connectionStrings>
<system.serviceModel>
<services>
<service name="MyServices.UserService" behaviorConfiguration="behaviorUserService">
<host>
<baseAddresses>
<add baseAddress = "http://127.0.0.1:9999/UserService" />
</baseAddresses>
</host>
<endpoint address ="UserService" binding="wsHttpBinding" contract="MyContract.UserContract" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="behaviorUserService">
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
using MyServices;
using System;
using System.ServiceModel; namespace MyTest
{
class Program
{
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(UserService)))
{
host.Opened += delegate
{
Console.WriteLine("UserService已经启动,按任意键终止服务!");
}; host.Open();
Console.Read();
}
}
}
}
客户端程序:
配置文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<client>
<endpoint address="http://127.0.0.1:9999/UserService/UserService" binding="wsHttpBinding" contract="MyContract.UserContract" name="userService" />//这个地方需要注意,address与上面不同,它自动多加了一个UserService
</client> </system.serviceModel> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> </configuration>
service层:
using MyContract;
using MyModel;
using System.ServiceModel; namespace MyClientServics
{
public class UserServiceClient
{
ChannelFactory<UserContract> channelFactory = new ChannelFactory<UserContract>("userService");
public int Insert(User user)
{
UserContract proxy = channelFactory.CreateChannel();
int id = ;
id = proxy.Insert(user);
return id;
} public void Delete(int id)
{
//ChannelFactory<UserContract> channelFactory = new ChannelFactory<UserContract>("userService");
UserContract proxy = channelFactory.CreateChannel();//这句话必须放在方法里面,否则报错
proxy.Delete(id);
} public void Update(User user)
{
//ChannelFactory<UserContract> channelFactory = new ChannelFactory<UserContract>("userService");
UserContract proxy = channelFactory.CreateChannel();
proxy.Update(user);
} public User GetUserById(int id)
{
//ChannelFactory<UserContract> channelFactory = new ChannelFactory<UserContract>("userService");
UserContract proxy = channelFactory.CreateChannel();
return proxy.GetUserById(id);
}
}
}
客户端运行程序
public void InitLoad()
{
try
{
UserServiceClient userService = new UserServiceClient();
User user = userService.GetUserById();
MessageBox.Show(user.UserName);
}catch(FaultException<FaultMessage> ex)
{
MessageBox.Show(ex.Detail.ErrorCode + ":" + ex.Detail.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
} private void btnOk_Click(object sender, System.EventArgs e)
{
InitLoad();
}
我的第一个WCF程序的更多相关文章
- WCF入门教程2——创建第一个WCF程序
本节目标 掌握接口 理解契约式编程 创建宿主程序 创建客户端程序访问服务 什么是接口 认识一下接口 必须知道的接口特性 接口不可以被实例化(常作为类型使用) 实现类必须实现接口的所有方法(抽象类除外) ...
- 跟我一起学WCF(4)——第一个WCF程序
一.引言 前面几篇文章分享了.NET 平台下其他几种分布式技术,然而前面几种分布式技术专注于某一特定的领域,并且具有不同编程接口,这使得开发人员需要掌握多个API的使用.基于这样的原因,微软在.NET ...
- 我的第一个WCF程序,很简单适合我等菜鸟
1.首先我罗列一下网站搜索并经过自己理解的WCF的含义: 1)WCF:(WIndows Communication Foundation)是由微软是由微软发展的一组数据通信的应用开发接口,可以翻译为W ...
- 建立第一个wcf程序
使用管理员权限启动vs (否者将导致ServiceHost开启失败 权限不足) 1.创建一个空的控制台程序 2.添加程序集引用 System.ServiceModel 3.写入一些代码 如下 usin ...
- WCF学习笔记(一)---我的第一个WCF程序
一.创建WCF程序 1.创建一个控制台程序(WCFBlog) 2.添加wcf项目 3.将默认的IService1和Service1改成自己的名字 4.在ICalculateServic ...
- 第一个WCF程序
WCF的服务需要寄宿在进程中,我们把服务端的叫做宿主,为服务指定宿主指定的过程叫服务寄宿.有两种方式一种是自我寄宿(Self-Hosting),一种是IIS寄宿方式.Self-Hosting我们通过一 ...
- WCF初探-2:手动实现WCF程序
1.前言 上一篇,我们通过VS自带的模板引擎自动生成了一个wcf程序,接下来我们将手动实现一个wcf程序.由于应用程序开发中一般都会涉及到大量的增删改查业务,所以这个程序将简单演示如何在wcf中构建简 ...
- [转]我的第一个WCF
1:首先新建一个解决方案 2:右击解决方案添加一个控制台程序 3:对着新建好的控制台程序右击添加wcf服务 最后的结果: 有3个文件 app.config Iwcf_server.cs wcf_se ...
- 如何建立一个WCF服务并将其发布到IIS上
在我们的软件开发中,经常会连接到数据库中,如果是常规的操作,我们经常会将连接数据库的字符串写在配置文件中,然后去读取数据库的连接字符串,其实这种方式是非常不科学的,这会直接暴露我们的数据库,直接暴露我 ...
随机推荐
- linux 2.6.32文件系统 fd与file*之间的关系
给定如下一定情况: crash> files PID: TASK: ffff8817facd2100 CPU: COMMAND: "slabtop" ROOT: / CWD: ...
- 使用rgba设置输入框背景透明
项目中遇到要求输入框的背景设置透明度,但文字不受影响,如下图 输入框使用input标签 <input ref="searchText" type="search&q ...
- python小实例一:简单爬虫
本文所谓的爬虫就是通过本地远程访问url,然后将url的读成源代码形式,然后对源代码进行解析,获取自己需要的数据,相当于简单数据挖掘.本文实现的是将一个网页的图片爬出保存到本地的过程,例子很简单,用的 ...
- 102/107. Binary Tree Level Order Traversal/II
原文题目: 102. Binary Tree Level Order Traversal 107. Binary Tree Level Order Traversal II 读题: 102. 层序遍历 ...
- eclipse中配置Tomcat服务器以及新建项目
eclipse配置Tomcat服务器 http://jingyan.baidu.com/article/ca2d939dd90183eb6d31ce79.html eclipse中配置Tomcat服务 ...
- 第七次Scrum冲刺
第七次Scrum冲刺 1.今日完成的任务 队员 今日完成任务 刘佳 前端与后端对接 李佳 后端与数据库对接 周世元 数据库与后端对接 杨小妮 博客编写 许燕婷 管理团队当日及次日任务 陈水莲 综合测试 ...
- 导入maven框架报错
原因pom文件第一行报错X org.apache.maven.archiver.mavenarchiver.getmanifest怎么解决 解决: 原因就是你的maven的配置文件不是最新的 1.he ...
- 吴裕雄 06-MySQL选择数据库
实例以下实例选取了数据库 RUNOOB:use RUNOOB;注意:所有的数据库名,表名,表字段都是区分大小写的.所以你在使用SQL命令时需要输入正确的名称. 使用PHP脚本选择MySQL数据库PHP ...
- 用python对txt中文件读取,然后按顺序标号存入excel中
读取txt文件,然后存入excel中 import xlwt #从txt文件中读取内容,放到ftext1中 f1=open('/Users/XXX/Documents/pythonwork/tenso ...
- 机器学习之overfiting
有错欢迎指正,别让小弟继续错下去. 我们在使用机器学习过程中,经常会overfiting,overfiting的产生原因是noise.训练样本大的话,还好,不用考虑这个 问题.但是,当数据量小的时候, ...