WCF简单三层框架

4 篇文章 0 订阅
4 篇文章 0 订阅

1.总体预览

2.WCF.Contract层

类IArea:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Data;
using Model;

namespace WCF.Contract
{
    [ServiceContract]
    public interface IArea
    {
        [OperationContract]
        List<Area> GetArea();

        [OperationContract]
        int InsertArea(Area area);
    }
}

 

类ICalculator:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace WCF.Contract
{
    [ServiceContract]
    public interface ICalculator
    {
        [OperationContract]
        double Add(double x, double y);

        [OperationContract]
        double Subtract(double x, double y);

        [OperationContract]
        double Multiply(double x, double y);

        [OperationContract]
        double Divide(double x, double y);
    }
}

 

3.WCF.Service层

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using WCF.Contract;
using Model;
using Common;

namespace WCF.Service
{
    public class AreaService : IArea
    {
        public List<Area> GetArea()
        {
            DataTable dt = null;
            string strSql = string.Format("select * from areatest");

            DBUtility.OracleHelper helper = new DBUtility.OracleHelper();
            dt = helper.GetTable(strSql);

            List<Area> list = ConvertHelper<Area>.ConvertToList(dt);

            return list;
        }

        public int InsertArea(Area area)
        {
            int nResult = -1;
            string strSql = string.Format("insert into areatest values({0},'{1}','{2}',{3})", area.Id, area.Name, area.Code, area.Sort);
           
            DBUtility.OracleHelper helper = new DBUtility.OracleHelper();
            nResult = helper.ExcuteNoQuery(strSql);

            return nResult;
        }
    }
}

 

类CalculatorService:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WCF.Contract;

namespace WCF.Service
{
    public class CalculatorService : ICalculator
    {
        public double Add(double x, double y)
        {
            return x + y;
        }

        public double Subtract(double x, double y)
        {
            return x - y;
        }

        public double Multiply(double x, double y)
        {
            return x * y;
        }

        public double Divide(double x, double y)
        {
            return x / y;
        }
    }
}

 

4.WCF.WcfProxy代理层

类AreaClient:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;
using WCF.Contract;
using Common;
using System.Data;

namespace WCF.WcfProxy
{
    public class AreaClient : IArea
    {

        public AreaClient()
        {
            InitFactory();
        }

        IArea Channel = null;
        private void InitFactory()
        {
            Binding httpBinding = new BasicHttpBinding();
            string strServiceAddress = WCFConfig.ServiceAddress;
            EndpointAddress httpAddress = new EndpointAddress(string.Format("{0}/{1}", strServiceAddress, "generalArea"));
            ChannelFactory<IArea> channelFactory = new ChannelFactory<IArea>(httpBinding, httpAddress);
            Channel = channelFactory.CreateChannel();
        }

        #region IArea 成员

        public List<Model.Area> GetArea()
        {
            return this.Channel.GetArea();
        }

        public int InsertArea(Model.Area area)
        {
            return this.Channel.InsertArea(area);
        }

        #endregion
    }
}

 

类CalculatorClient:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WCF.Contract;
using System.ServiceModel;
using System.ServiceModel.Channels;
using Common;

namespace WCF.WcfProxy
{
    public class CalculatorClient : ICalculator
    {

        public CalculatorClient()
        {
            InitFactory();
        }

        ICalculator Channel = null;
        private void InitFactory()
        {
            Binding httpBinding = new BasicHttpBinding();
            string strServiceAddress = WCFConfig.ServiceAddress;
            EndpointAddress httpAddress = new EndpointAddress(string.Format("{0}/{1}", strServiceAddress, "generalCalculator"));
            ChannelFactory<ICalculator> channelFactory = new ChannelFactory<ICalculator>(httpBinding, httpAddress);
            Channel = channelFactory.CreateChannel();
        }

        #region ICalculator 成员

        public double Add(double x, double y)
        {
            return this.Channel.Add(x, y);
        }

        public double Subtract(double x, double y)
        {
            return this.Channel.Subtract(x, y);
        }

        public double Multiply(double x, double y)
        {
            return this.Channel.Multiply(x, y);
        }

        public double Divide(double x, double y)
        {
            return this.Channel.Divide(x, y);
        }

        #endregion
    }
}

 

5.WCF.Hosting服务寄宿层

App.config:

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="ServiceAddress" value=">
    <add key="DBConnection" value="data source=.;User Id=10;Password=10;"/>
  </appSettings>
<startup>
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>

 

启动:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using WCF.Contract;
using WCF.Service;
using System.Configuration;

namespace Hosting
{
    class Program
    {
        private static string ServiceAddress = ConfigurationManager.AppSettings["ServiceAddress"].ToString();

        static void Main(string[] args)
        {
            HostCalculatorServiceViaCode("generalCalculator");
        }

        private static void HostCalculatorServiceViaCode(string endAddress)
        {
            Uri httpBaseAddress = new Uri(string.Format("{0}/{1}", ServiceAddress, endAddress));

            using (ServiceHost calculatorSerivceHost = new ServiceHost(typeof(CalculatorService), httpBaseAddress))
            {
                BasicHttpBinding httpBinding = new BasicHttpBinding();
                calculatorSerivceHost.AddServiceEndpoint(typeof(ICalculator), httpBinding, string.Empty);

                ServiceMetadataBehavior behavior = calculatorSerivceHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
                {
                    if (behavior == null)
                    {
                        behavior = new ServiceMetadataBehavior();
                        behavior.HttpGetEnabled = true;
                        calculatorSerivceHost.Description.Behaviors.Add(behavior);
                    }
                    else
                    {
                        behavior.HttpGetEnabled = true;
                    }
                }

                calculatorSerivceHost.Opened += delegate
                {
                    Console.WriteLine("Calculator Service has begin to listen ... ...");

                    HostAreaServiceViaCode("generalArea");
                };

                calculatorSerivceHost.Open();
            }
        }

        private static void HostAreaServiceViaCode(string endAddress)
        {
            Uri httpBaseAddress = new Uri(string.Format("{0}/{1}", ServiceAddress, endAddress));

            using (ServiceHost areaSerivceHost = new ServiceHost(typeof(AreaService), httpBaseAddress))
            {
                BasicHttpBinding httpBinding = new BasicHttpBinding();
                areaSerivceHost.AddServiceEndpoint(typeof(IArea), httpBinding, string.Empty);

                ServiceMetadataBehavior areaBehavior = areaSerivceHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
                {
                    if (areaBehavior == null)
                    {
                        areaBehavior = new ServiceMetadataBehavior();
                        areaBehavior.HttpGetEnabled = true;
                        areaSerivceHost.Description.Behaviors.Add(areaBehavior);
                    }
                    else
                    {
                        areaBehavior.HttpGetEnabled = true;
                    }
                }

                areaSerivceHost.Opened += delegate
                {
                    Console.WriteLine("Area Service has begin to listen ... ...");
                };

                areaSerivceHost.Open();

                Console.Read();
            }
        }
    }
}

 

6.Model层

类Area:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Model
{
    public class Area
    {
        private int id;

        public int Id
        {
            get { return id; }
            set { id = value; }
        }
        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        private string code;

        public string Code
        {
            get { return code; }
            set { code = value; }
        }
        private int sort;

        public int Sort
        {
            get { return sort; }
            set { sort = value; }
        }
    }
}

7.DBUtility层

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.OracleClient;
using System.Data;

namespace DBUtility
{
    public class OracleHelper
    {
        private string strDBConnection = ConfigurationManager.AppSettings["DBConnection"].ToString();
        private OracleConnection conn = null;

        private void Open()
        {          
            if (conn == null)
            {
                conn = new OracleConnection(strDBConnection);
            }

            if (conn.State == System.Data.ConnectionState.Closed)
            {
                conn.Open();
            }
        }

        private void Close()
        {
            if (conn != null && conn.State == System.Data.ConnectionState.Open)
            {
                conn.Close();
            }
        }

        public int ExcuteNoQuery(string strSql)
        {
            int nResult = -1;
            Open();

            OracleCommand cmd = new OracleCommand(strSql, conn);
            nResult = cmd.ExecuteNonQuery();

            Close();

            return nResult;
        }

        public DataTable GetTable(string strSql)
        {
            DataTable dt = new DataTable();
            Open();

            OracleDataAdapter adapter = new OracleDataAdapter(strSql, conn);
            adapter.Fill(dt);

            Close();

            return dt;
        }
    }
}

 

8.Common层

转换辅助类ConvertHelper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Collections;
using System.Reflection;

namespace Common
{
    public class ConvertHelper<T> where T : new()
    {
        /// <summary>       
        /// 利用反射和泛型       
        /// </summary>       
        /// <param name="dt"></param>       
        /// <returns></returns>       
        public static List<T> ConvertToList(DataTable dt)
        {
            // 定义集合          
            List<T> list = new List<T>();
            // 获得此模型的类型           
            Type type = typeof(T);
            //定义一个临时变量           
            string tempName = string.Empty;
            //遍历DataTable中所有的数据行          
            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                // 获得此模型的公共属性           
                PropertyInfo[] propertys = t.GetType().GetProperties();
                //遍历该对象的所有属性               
                foreach (PropertyInfo pi in propertys)
                {
                    tempName = pi.Name;//将属性名称赋值给临时变量          
                    //检查DataTable是否包含此列(列名==对象的属性名)            
                    if (dt.Columns.Contains(tempName))
                    {
                        // 判断此属性是否有Setter     
                        if (!pi.CanWrite) continue;//该属性不可写,直接跳出       
                        //取值                   
                        object value = dr[tempName];
                        //如果非空,则赋给对象的属性     

                        if (value != DBNull.Value)
                        {
                            switch (pi.PropertyType.Name)
                            {
                                case "Int16":
                                    pi.SetValue(t, Convert.ToInt16(value), null);
                                    break;
                                case "Int32":
                                    pi.SetValue(t, Convert.ToInt32(value), null);
                                    break;
                                case "Int64":
                                    pi.SetValue(t, Convert.ToInt64(value), null);
                                    break;
                                case "String":
                                    pi.SetValue(t, value.ToString(), null);
                                    break;
                                case "Decimal":
                                    pi.SetValue(t, Convert.ToDecimal(value), null);
                                    break;
                                case "Double":
                                    pi.SetValue(t, Convert.ToDecimal(value), null);
                                    break;
                                case "Boolean":
                                    pi.SetValue(t, Convert.ToBoolean(value), null);
                                    break;
                                case "DateTime":
                                    pi.SetValue(t, Convert.ToDateTime(value), null);
                                    break;
                                case "Char":
                                    pi.SetValue(t, Convert.ToChar(value), null);
                                    break;
                                case "Byte":
                                    pi.SetValue(t, Convert.ToByte(value), null);
                                    break;
                            }
                        }
                    }
                }
                //对象添加到泛型集合中            
                list.Add(t);
            }
            return list;
        }
    }
}

 

9.winform客户端调用:

private void button1_Click(object sender, EventArgs e)
        {
            AreaClient area = new AreaClient();
            List<Model.Area> dt = area.GetArea();
            dataGridView1.DataSource = dt;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Model.Area area = new Model.Area();
            area.Id = 5;
            area.Name = "安徽";
            area.Code = "500";
            area.Sort = 5;
            AreaClient areaClient = new AreaClient();
            areaClient.InsertArea(area);
        }

 

10.控制台客户端调用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Channels;
using System.ServiceModel;
using WCF.WcfProxy;

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            InvocateCalclatorServiceViaCode();

            Console.Read();
        }

        static void InvocateCalclatorServiceViaCode()
        {
            CalculatorClient calculator = new CalculatorClient();
            {
                try
                {
                    Console.WriteLine("x + y = {2} where x = {0} and y = {1}", 1, 2, calculator.Add(1, 2));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值