首页 > 代码库 > 我的第一个WCF程序

我的第一个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 = 0;            SqlParameter[] parameters=new SqlParameter[7];            parameters[0] = new SqlParameter(Constants.USERNAME, user.UserName);            parameters[1] = new SqlParameter(Constants.PASSWORD, user.Password);            parameters[2] = new SqlParameter(Constants.TRUENAME, user.Truename);            parameters[3] = new SqlParameter(Constants.SEX, user.Sex);            parameters[4] = new SqlParameter(Constants.BIRTHDAY, user.Birthday);            parameters[5] = new SqlParameter(Constants.PHONE, user.Phone);            parameters[6] = 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[1];            parameters[0] = 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[2];            parameters[0] = new SqlParameter(Constants.ID, user.Id);            parameters[1] = 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[1];            parameters[0] = 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 = 0;            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 = 0;            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(30);                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程序