我的第一个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上
在我们的软件开发中,经常会连接到数据库中,如果是常规的操作,我们经常会将连接数据库的字符串写在配置文件中,然后去读取数据库的连接字符串,其实这种方式是非常不科学的,这会直接暴露我们的数据库,直接暴露我 ...
随机推荐
- 点击li往数组添加对应li的id再点击移除,根据是否有class判断
if($(this).hasClass('click')){ $(this).removeClass('click'); var idAPP = $(this).attr('id'), index = ...
- angularjs 请求数据转换为Form Data传参
在angularjs中配置好服务,有时传参会导致后台借不到值或者后台直接报错: 这就与后台框架有关,如果后台是以public ModelAndView接收接口传过来的参数,这种情况,前台传参的形式比较 ...
- 第六次Scrum冲刺
第六次Scrum冲刺 1.成员今日完成情况 队员 今日完成任务 刘佳 前端构建 李佳 后端设计 周世元 数据设计 杨小妮 博客编写 许燕婷 管理团队当日及次日任务 陈水莲 性能测试用例设计 曾丽丽 性 ...
- Hibernate 再接触 多对多单向双向关联
情景:一个老师可能有多个学生,一个学生也可能有多个老师 多对一单向: 例如老师知道自己教哪些学生,学生却不知道自己被哪些老师教 方法:使用第三张表 分别存两张表的id annotation Stude ...
- ArcGIS特殊标注效果的简单实现
1. 普通纯色背景:例如望仙亭,水垄沟: 方法: 2. 背景+边框 例如进入点 方法:
- effective C++学习二(仅供个人学习记录,本文摘录effective C++)
条款 2:尽量用<iostream>而不用<stdio.h> scanf 和 printf 很轻巧,很高效,你也早就知道怎么用它们,这我承 认.但尽管他们很有用,事实上 sca ...
- Oracle 未能加载文件或程序集Oracle.DataAccess
原文地址;https://www.cnblogs.com/xuekai-to-sharp/p/3586071.html 关键是引用DLL:Oracle.DataAccess.dll DLL文件的路径: ...
- C# 模拟多线程下载文件
原地址:http://www.cnblogs.com/Opiece/p/4803836.html 客户端 public static string strContent = ""; ...
- hdu3826-Squarefree number-(欧拉筛+唯一分解定理)
Squarefree number Time Limit: 10000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Other ...
- Delphi 语言
自1995年Borland公司发布Delphi 1.0以来,Delphi受到很多开发者的亲睐,到1999年发布Delphi5,Delphi以其开发快捷.控件丰富.易于上手等优势吸引了众多的开发者,用户 ...