WCF簡單三層框架

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="http://localhost:5555"/>
    <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);
                }
            }
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章