一步步实现自己的框架系列(四):页面与页面服务的创建

  上一篇已经把我们的基础通信做好了,接下来就开始创建页面与页面服务,首先来看下我们页面与页面服务的接口定义,一目清晰了然。

页面接口的定义:

   public interface IPage
    {
        string InstanceId { get; }

        bool IsPageServiceCreated { get; }

        ICoreClient CoreClient { get; }

        /// <summary>
        /// 初始化页面
        /// </summary>
        void Initialize();

        /// <summary>
        /// 关闭页面
        /// </summary>
        void Close();


        /// <summary>
        /// 调用服务方法
        /// </summary>
        /// <param name="methodName">方法名称</param>
        /// <param name="paramTypes">方法参数类型的类名列表</param>
        /// <param name="args">方法参数集合</param>
        /// <returns>返回结果</returns>
        object CallService(string methodName, string[] paramTypes, params object[] args);

        /// <summary>
        /// 单向调用服务方法(通信成功即返回,不等待方法执行)
        /// </summary>
        /// <param name="methodName">方法名称</param>
        /// <param name="paramTypes">方法参数类型的类名列表</param>
        /// <param name="args">方法参数集合</param>
        void OneWayCallService(string methodName, string[] paramTypes, params object[] args);



        /// <summary>
        /// 调用页面服务
        /// </summary>
        object CallPageService(string methodName, string[] paramTypes, params object[] args);

        /// <summary>
        /// 单向调用页面服务
        /// </summary>
        void OneWayCallPageService(string methodName, string[] paramTypes, params object[] args);

    }

页面服务接口的定义:

    public interface IPageService
    {
        /// <summary>
        /// 页面实例ID
        /// </summary>
        string InstanceId { get; }

        ISession Session { get; }

        void SetSession(ISession session);

        /// <summary>
        /// 初始化页面服务
        /// </summary>
        void Initialize();

        /// <summary>
        /// 关闭页面服务
        /// </summary>
        void Close();


        /// <summary>
        /// 回调页面客户端方法
        /// </summary>
        /// <param name="methodName">方法名称</param>
        /// <param name="paramTypes">方法参数类型的类名列表</param>
        /// <param name="args">方法参数集合</param>
        /// <returns>客户端方法返回结果</returns>
        object CallPage(string methodName, string[] paramTypes, params object[] args);

        /// <summary>
        /// 单向回调页面客户端方法(通信成功即返回,不等待方法执行)
        /// </summary>
        /// <param name="methodName">方法名称</param>
        /// <param name="paramTypes">方法参数类型的类名列表</param>
        /// <param name="args">方法参数集合</param>
        void OneWayCallPage(string methodName, string[] paramTypes, params object[] args);

        /// <summary>
        /// 销毁页面服务
        /// </summary>
        void Dispose();
    }

接下来就是页面基类的实现:

 public abstract class PageBase : ContentControl, IPage
    {
        static PageBase()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(PageBase), new FrameworkPropertyMetadata(typeof(PageBase)));
        }

        public PageBase()
        {
            if (DesignerProperties.GetIsInDesignMode(this))
                return;
            //焦点设置
            FocusManager.SetIsFocusScope(this, true);
            KeyboardNavigation.SetDirectionalNavigation(this, KeyboardNavigationMode.Contained);
            this.Focusable = false;
            //事件设置
            this.Loaded += new RoutedEventHandler(PageBase_Loaded);
            this.Unloaded += new RoutedEventHandler(PageBase_Unloaded);
        }

        void PageBase_Loaded(object sender, RoutedEventArgs e)
        {
            this.Loaded -= PageBase_Loaded;
            Initialize();
        }

        void PageBase_Unloaded(object sender, RoutedEventArgs e)
        {
            this.Unloaded -= PageBase_Unloaded;
        }

        #region IPage

        public string InstanceId { get; private set; }

        public bool IsPageServiceCreated { get; private set; }

        public ICoreClient CoreClient { get; private set; }

        /// <summary>
        /// 页面服务的名称
        /// </summary>
        protected virtual string PageServiceName
        {
            get
            {
                return this.GetType().FullName;
            }
        }

        public void Initialize()
        {
            CoreClient = GL.Core.PartPlatform.Instance.GetSinglePart<ICoreClient>();
            if (!IsPageServiceCreated)
            {
                this.InstanceId = this.CoreClient.CreatePageService("GL.Service.Page1.ServicePage1");
                this.IsPageServiceCreated = true;
            }
        }

        public void Close()
        {
            this.CallService("Close", null);
        }

        public object CallService(string methodName, string[] paramTypes, params object[] args)
        {
            var request = new Request();
            request.InstanceId = this.InstanceId;
            request.MethodName = methodName;
            request.ParamTypes = paramTypes;
            request.Parameters = args.SerializeToByteArray();
            var result = this.CoreClient.CallService(request);
            return result.Value.DeserializeToObject();
        }

        public void OneWayCallService(string methodName, string[] paramTypes, params object[] args)
        {
            var request = new Request();
            request.InstanceId = this.InstanceId;
            request.MethodName = methodName;
            request.ParamTypes = paramTypes;
            request.Parameters = args.SerializeToByteArray();
            this.CoreClient.OneWayCallService(request);
        }

        public object CallPageService(string methodName, string[] paramTypes, params object[] args)
        {
            var request = new Request();
            request.InstanceId = this.InstanceId;
            request.MethodName = methodName;
            request.ParamTypes = paramTypes;
            request.Parameters = args.SerializeToByteArray();
            var result = this.CoreClient.CallPageService(request);
            return result.Value.DeserializeToObject();
        }

        public void OneWayCallPageService(string methodName, string[] paramTypes, params object[] args)
        {
            var request = new Request();
            request.InstanceId = this.InstanceId;
            request.MethodName = methodName;
            request.ParamTypes = paramTypes;
            request.Parameters = args.SerializeToByteArray();
            this.CoreClient.OneWayCallPageService(request);
        }

        #endregion
    }
View Code

  页面基类实现了页面与服务通信与函数调用的基本功能。

页面服务基类的实现:

    public abstract class PageServiceBase : IPageService, IDisposable
    {
        public string InstanceId { get; private set; }

        public ISession Session { get; private set; }


        public PageServiceBase()
        {
            this.InstanceId = Guid.NewGuid().ToString();
        }

        /// <summary>
        /// 设置当前页面Session
        /// </summary>
        /// <param name="session"></param>
        public void SetSession(ISession session)
        {
            if (Session != null)
            {
                throw new InvalidOperationException("page session has already setting!");
            }
            this.Session = session;
        }

        public void Initialize() 
        {
            this.OnInitializing();
            //TODO:初始化服务

            this.OnInitialized();
        }

        protected virtual void OnInitialized()
        {

        }

        protected virtual void OnInitializing()
        {

        }

        public virtual void Close() 
        {
            throw new NotImplementedException();
        }


        public object CallPage(string methodName, string[] paramTypes, params object[] args)
        {
            var request = new Request();
            request.InstanceId = this.InstanceId;
            request.MethodName = methodName;
            request.ParamTypes = paramTypes;
            request.Parameters = args == null ? null : args.SerializeToByteArray();

            return this.Session.CallbackService.PageCallback(request).Value.DeserializeToObject();
        }


        public T CallPage<T>(string methodName, string[] paramTypes, params object[] args)
        {
            return (T)this.CallPage(methodName, paramTypes, args);
        }

        public void OneWayCallPage(string methodName, string[] paramTypes, params object[] args)
        {
            var request = new Request();
            request.InstanceId = this.InstanceId;
            request.MethodName = methodName;
            request.ParamTypes = paramTypes;
            request.Parameters = args == null ? null : args.SerializeToByteArray();

            this.Session.CallbackService.OneWayPageCallback(request);
        }

        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }
View Code

下面就做个单元测试,测试下我们的成果吧。

测试页面定义:

    public class Page1 : PageBase
    {
        public void WriteLine(string msg)
        {
            Console.WriteLine(msg);
        }
    }

测试页面服务定义:

    public class ServicePage1 : PageServiceBase
    {

        public void InvokeClientConsole()
        {
            this.OneWayCallPage("WriteLine", null, "Hello World!");
        }
    }


启动服务端:

    class Program
    {
        static void Main(string[] args)
        {
            XmlConfigurator.Configure();

            Program p = new Program();

            string path = Path.Combine(Environment.CurrentDirectory, "GL.Service.Test.config");

            var partPath = @"C:\GL\GL.DynamicDLLLoadTest\GL.Release\ServiceTest";
            //启动插件平台
            PartPlatform.Instance.Start(path, new string[] { partPath });

            Console.WriteLine("PartPlatform Started");
            //启动核心服务
            Program.StartService("GL WCF Service", typeof(CoreService));

            Console.WriteLine("CoreServiceHost Started");

            Console.ReadKey();
        }

        private static IList<ServiceHost> _startedServices = new List<ServiceHost>();

        private static void StartService(string serviceName, Type serviceType)
        {
            var service = new ServiceHost(serviceType);
            service.Open();
            _startedServices.Add(service);

        }
    }

 

启动客户端:

 class Program 
    {
        [STAThreadAttribute]
        static void Main(string[] args)
        {
            XmlConfigurator.Configure();

            Program p = new Program();
            string path = Path.Combine(Environment.CurrentDirectory, "GL.Service.Test.config");

            var partPath = @"C:\GL\GL.DynamicDLLLoadTest\GL.Release\ClientTest";
            //启动插件平台
            PartPlatform.Instance.Start(path, new string[] { partPath });

            //连接到服务端
            var coreClient = PartPlatform.Instance.GetSinglePart<ICoreClient>();

            var sessionID = coreClient.Connect(new GL.Contracts.ClientConnectionInfo() { UserName="GL", UserPassword = "GL" });

            Console.WriteLine("sessionID:{0}", sessionID);

            while (Console.ReadKey().KeyChar == (char)Keys.Enter)
            {
                //创建页面
                var pg = PageFactory.CreatePage("GL.Client.Page1.Page1");

                Console.WriteLine("OneWayCallService" + pg.InstanceId);

                //调用页面服务
                var request = new Request();
                request.InstanceId = pg.InstanceId;
                request.MethodName = "InvokeClientConsole";
                request.ParamTypes = null;
                request.Parameters = null;

                coreClient.OneWayCallPageService(request);
            }
            Console.ReadLine();
        }
    }

最激动人心的时刻,永远是屏幕出现那令人期待的Hello World!享受我们的成果吧!

 

posted @ 2013-06-18 09:44  广林  阅读(1682)  评论(2编辑  收藏  举报