写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程序的更多相关文章

  1. WCF入门教程2——创建第一个WCF程序

    本节目标 掌握接口 理解契约式编程 创建宿主程序 创建客户端程序访问服务 什么是接口 认识一下接口 必须知道的接口特性 接口不可以被实例化(常作为类型使用) 实现类必须实现接口的所有方法(抽象类除外) ...

  2. 跟我一起学WCF(4)——第一个WCF程序

    一.引言 前面几篇文章分享了.NET 平台下其他几种分布式技术,然而前面几种分布式技术专注于某一特定的领域,并且具有不同编程接口,这使得开发人员需要掌握多个API的使用.基于这样的原因,微软在.NET ...

  3. 我的第一个WCF程序,很简单适合我等菜鸟

    1.首先我罗列一下网站搜索并经过自己理解的WCF的含义: 1)WCF:(WIndows Communication Foundation)是由微软是由微软发展的一组数据通信的应用开发接口,可以翻译为W ...

  4. 建立第一个wcf程序

    使用管理员权限启动vs (否者将导致ServiceHost开启失败 权限不足) 1.创建一个空的控制台程序 2.添加程序集引用 System.ServiceModel 3.写入一些代码 如下 usin ...

  5. WCF学习笔记(一)---我的第一个WCF程序

    一.创建WCF程序   1.创建一个控制台程序(WCFBlog)   2.添加wcf项目   3.将默认的IService1和Service1改成自己的名字   4.在ICalculateServic ...

  6. 第一个WCF程序

    WCF的服务需要寄宿在进程中,我们把服务端的叫做宿主,为服务指定宿主指定的过程叫服务寄宿.有两种方式一种是自我寄宿(Self-Hosting),一种是IIS寄宿方式.Self-Hosting我们通过一 ...

  7. WCF初探-2:手动实现WCF程序

    1.前言 上一篇,我们通过VS自带的模板引擎自动生成了一个wcf程序,接下来我们将手动实现一个wcf程序.由于应用程序开发中一般都会涉及到大量的增删改查业务,所以这个程序将简单演示如何在wcf中构建简 ...

  8. [转]我的第一个WCF

    1:首先新建一个解决方案 2:右击解决方案添加一个控制台程序 3:对着新建好的控制台程序右击添加wcf服务 最后的结果: 有3个文件 app.config  Iwcf_server.cs wcf_se ...

  9. 如何建立一个WCF服务并将其发布到IIS上

    在我们的软件开发中,经常会连接到数据库中,如果是常规的操作,我们经常会将连接数据库的字符串写在配置文件中,然后去读取数据库的连接字符串,其实这种方式是非常不科学的,这会直接暴露我们的数据库,直接暴露我 ...

随机推荐

  1. 关于GC.Collect在不同机器上表现不一致问题

    2019.1.17,昨天项目更新后策划反应: 游戏卡,表现为:每走几步就卡一下.前天还没有. 但在我本机测试中,却没有任何卡顿感. QC同学的机器也卡.我去看了下,打开Profiler,没开deep, ...

  2. 【BUG记录】记一次游戏越来越卡的BUG

    U3D的MOBA项目,测试过程中,10分钟以后,游戏帧率开始缓慢下降,约3-5分钟后,由60帧下降到小于10帧,编辑器模式. 打开profiler,看到CPU占用非常高,每帧都有24K的GC, 时间占 ...

  3. centos7启动iptables时报Job for iptables.service failed because the control process exited with error cod

    centos7启动iptables时报Job for iptables.service failed because the control process exited with error cod ...

  4. 如何在Windows下安装MYSQL,并截图说明

    说明 : window 下安装 mysql 虽然简单,但是细节不注意就会安装失败,特别是配置服务器时,Current Root Password:为空:如果输入密码了在后面安装会报错.(不知道设置这个 ...

  5. 开发一个FTP软件

    一.开发一个多并发的FTP server 需求: .允许同时支持多用户在线 .用户认证 .用户空间配额 .权限限制 .可上传下载.上传下载过程中显示进度条 .用户可远程切换目录.查看服务端文件列表等 ...

  6. 获取字段唯一值工具- -ArcPy和Python案例学习笔记

    获取字段唯一值工具- -ArcPy和Python案例学习笔记   目的:获取某一字段的唯一值,可以作为工具使用,也可以作为函数调用 联系方式:谢老师,135-4855-4328,xiexiaokui# ...

  7. repo 原理

    Android源代码工程用repo来进行管理,本质是多个git仓的整合. 感谢https://blog.csdn.net/stoic163/article/details/78790349 1.Gen ...

  8. socket编程的同步、异步与阻塞、非阻塞示例详解

     socket编程的同步.异步与阻塞.非阻塞示例详解之一  分类: 架构设计与优化 简介图 1. 基本 Linux I/O 模型的简单矩阵 每个 I/O 模型都有自己的使用模式,它们对于特定的应用程序 ...

  9. Android 抓取LOG的几种命令【转】

    通常调试时候需要抓取log信息,下面几种通过ADB命令来抓取log的方法: USB连接上手机,手机需要其他操作:然后运行ADB工具:输入不同的命令即可抓取对应的LOG信息. 抓取radio LOG信息 ...

  10. pandas 读取大文件 read_table C-engine CParserError: Error tokenizing data

    解决办法: pd_data = pd.read_table(comment_file,header=None,encoding='utf-8', engine='python') 官网解析: engi ...