Esempio n. 1
0
 public static void RemoveClient(HeaderParameter para)
 {
     if (routerDic.ContainsKey(para.routerid))
     {
         lock (syncObj)
         {
             (routerDic[para.routerid] as IContextChannel).Abort();
             routerDic.Remove(para.routerid);
             headParaDic.Remove(para.routerid);
         }
     }
     if (RoundRobinCount.ContainsKey(para.routerid))
     {
         lock (syncObj)
         {
             int key = RoundRobinCount[para.routerid];
             RegistrationInfo regInfo = RegistrationList[key];
             regInfo.ClientNum -= 1;
         }
     }
     if (hostwcfRouter != null)
     {
         //界面显示
         hostwcfRouter(RegistrationList.Values.ToList());
     }
 }
Esempio n. 2
0
        private void AddMessageHeader(IContextChannel channel, string cmd, bool iscompressjson, bool isencryptionjson, SerializeType serializetype, SysLoginRight loginright, Action callback)
        {
            using (var scope = new OperationContextScope(channel as IContextChannel))
            {
                if (string.IsNullOrEmpty(cmd))
                {
                    cmd = "";
                }

                HeaderParameter para = new HeaderParameter();
                para.cmd        = cmd;
                para.routerid   = clientObj.RouterID;
                para.pluginname = clientObj.PluginName;
                //ReplyIdentify如果客户端创建连接为空,如果中间件连接上级中间件那就是本地中间件标识
                para.replyidentify    = null;
                para.beginidentify    = BeginIdentify;
                para.endidentify      = EndIdentify;
                para.token            = loginright != null ? loginright.token : null; //clientObj.Token;
                para.iscompressjson   = iscompressjson;
                para.isencryptionjson = isencryptionjson;
                para.serializetype    = serializetype;
                para.LoginRight       = loginright;
                para.NodePath         = null;
                HeaderOperater.AddMessageHeader(OperationContext.Current.OutgoingMessageHeaders, para);
                callback();
            }
        }
Esempio n. 3
0
        public void TestReadCurrentTreePersonExpecting200Response()
        {
            var expect = new HeaderParameter("X-Expect-Override", "200-ok");
            var state  = tree.ReadPersonForCurrentUser(expect);

            Assert.DoesNotThrow(() => state.IfSuccessful());
            Assert.AreEqual(HttpStatusCode.OK, state.Response.StatusCode);
        }
Esempio n. 4
0
 /// <summary>
 /// 超级回调中间件
 /// </summary>
 /// <param name="para"></param>
 /// <param name="plugin"></param>
 /// <param name="controller"></param>
 /// <param name="method"></param>
 /// <param name="jsondata"></param>
 /// <returns></returns>
 public string SuperReplyClient(HeaderParameter para, string plugin, string controller, string method, string jsondata)
 {
     if (SuperReplyClientAction != null)
     {
         return(SuperReplyClientAction(para, plugin, controller, method, jsondata));
     }
     return(null);
 }
Esempio n. 5
0
        //string ns = "http://www.efwplus.cn/";
        public string CreateClient(string clientName)
        {
            //客户端回调
            IDataReply      mCallBack = OperationContext.Current.GetCallbackChannel <IDataReply>();
            HeaderParameter para      = HeaderOperater.GetHeaderValue(OperationContext.Current.RequestContext.RequestMessage);
            string          ClientID  = ClientManage.CreateClient(clientName, DateTime.Now, mCallBack, para.pluginname, para.replyidentify);

            return(ClientID);
        }
Esempio n. 6
0
        public void it_should_set_parameter_by_name()
        {
            var parameters = new HeaderParameterCollection();

            parameters["some"] = new HeaderParameter("some", "test");

            parameters["some"].Should().NotBeNull();
            parameters["some"].Value.Should().Be("test");
        }
Esempio n. 7
0
        public void it_should_override_old_parameter_when_setting_by_name()
        {
            var parameters = new HeaderParameterCollection();

            parameters["some"] = new HeaderParameter("some", "test");
            parameters["some"] = new HeaderParameter("some", "other");

            parameters["some"].Value.Should().Be("other");
        }
Esempio n. 8
0
        public void it_should_try_and_parse_a_header_value()
        {
            HeaderParameter result;

            HeaderParameter.TryParse("q=1", out result).Should().BeTrue();

            result.Should().BeOfType <HeaderParameter>().Which.Name.Should().Be("q");
            result.Value.Should().Be(1.0);
        }
Esempio n. 9
0
        /// <summary>
        /// 截获从Client端发送的消息转发到目标终结点并获得返回值给Client端
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public Message ProcessMessage(Message requestMessage)
        {
            try
            {
                begintime();
                IRouterService  proxy = null;
                HeaderParameter para  = HeaderOperater.GetHeaderValue(requestMessage);

                if (RouterServerManage.routerDic.ContainsKey(para.routerid))
                {
                    proxy = RouterServerManage.routerDic[para.routerid];
                    para.replyidentify = RouterServerManage.headParaDic[para.routerid].replyidentify;
                }
                else
                {
                    //Binding binding = null;
                    EndpointAddress endpointAddress = null;
                    Uri             touri           = null;
                    para = RouterServerManage.AddClient(requestMessage, para, out endpointAddress, out touri);
                    requestMessage.Headers.To = touri;

                    IDuplexRouterCallback callback = OperationContext.Current.GetCallbackChannel <IDuplexRouterCallback>();
                    NetTcpBinding         tbinding = new NetTcpBinding("NetTcpBinding_WCFHandlerService");
                    DuplexChannelFactory <IRouterService> factory = new DuplexChannelFactory <IRouterService>(new InstanceContext(new DuplexRouterCallback(callback)), tbinding, endpointAddress);
                    proxy = factory.CreateChannel();

                    //缓存会话
                    RouterServerManage.routerDic.Add(para.routerid, proxy);
                    RouterServerManage.headParaDic.Add(para.routerid, para);
                }

                Message responseMessage = null;
                HeaderOperater.AddMessageHeader(requestMessage, para);//增加自定义消息头
                responseMessage = proxy.ProcessMessage(requestMessage);

                if (para.cmd == "Quit")
                {
                    //关闭连接释放缓存会话
                    RouterServerManage.RemoveClient(para);
                }

                double outtime = endtime();
                // 请求消息记录
                if (WcfServerManage.IsDebug)
                {
                    RouterServerManage.hostwcfMsg(Color.Black, DateTime.Now, String.Format("路由请求消息发送(耗时[" + outtime + "]):  {0}", requestMessage.Headers.Action));
                }


                return(responseMessage);
            }
            catch (Exception e)
            {
                return(Message.CreateMessage(requestMessage.Version, FaultCode.CreateReceiverFaultCode("error", RouterServerManage.ns), e.Message, requestMessage.Headers.Action));
            }
        }
Esempio n. 10
0
        public void DeleteWithoutAuthorization()
        {
            var deleteHeaders = new HeaderParameter().AddEncoding().AddLanguage().AddOrigin().AddReferer().AddXmlHttpRequest();

            _annotate
            .Given(_ => _step.TheUserIsActive())
            .When(_ => _step.DeleteBookingIsCalled(deleteHeaders, "12345"))
            .Then(_ => _assert.TheStatusCodeIs(HttpStatusCode.Forbidden, StepKey.DeleteBookingResponseMessage))
            .BDDfy();
        }
Esempio n. 11
0
        public void AddNewBooking_NegativeTest(string firstname, string surname, double?price, bool?deposit, string checkInDate, string checkOutDate)
        {
            var requestBody = new AddRequestModel(firstname, surname, price, deposit, checkInDate, checkOutDate);
            var headers     = new HeaderParameter().AddEncoding().AddLanguage().AddOrigin().AddReferer().AddXmlHttpRequest();

            _annotate
            .Given(_ => _step.TheUserWithTheFollowingDetails(requestBody))
            .When(_ => _step.AddBookingIsCalled(headers))
            .Then(_ => _assert.TheStatusCodeIs(HttpStatusCode.InternalServerError, StepKey.AddBookingResponseMessage))
            .And(_ => _assert.TheErrorMessageContains("Internal Server Error"))
            .BDDfy();
        }
Esempio n. 12
0
        public void AddNewBooking(string firstname, string surname, double price, bool deposit, string checkInDate, string checkOutDate)
        {
            var requestBody = new AddRequestModel(firstname, surname, price, deposit, checkInDate, checkOutDate);
            var headers     = new HeaderParameter().AddEncoding().AddLanguage().AddOrigin().AddReferer().AddXmlHttpRequest();

            _annotate
            .Given(_ => _step.TheUserWithTheFollowingDetails(requestBody))
            .When(_ => _step.AddBookingIsCalled(headers))
            .Then(_ => _assert.TheStatusCodeIs(HttpStatusCode.OK, StepKey.AddBookingResponseMessage))
            .And(_ => _assert.TheBookingIdIsNotNullOrEmpty())
            .And(_ => _assert.TheBookingResponseContainsTheFirstname(firstname))
            .BDDfy();
        }
Esempio n. 13
0
        /// <summary>
        /// 从注册表容器中根据Message的Action找到匹配的 binding和 endpointaddress
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <param name="binding"></param>
        /// <param name="endpointAddress"></param>
        public static HeaderParameter AddClient(Message requestMessage, HeaderParameter para, out EndpointAddress endpointAddress, out Uri touri)
        {
            string contractNamespace = requestMessage.Headers.Action.Substring(0, requestMessage.Headers.Action.LastIndexOf("/"));

            RegistrationInfo regInfo = null;


            List <KeyValuePair <int, RegistrationInfo> > krlist = RegistrationList.OrderBy(x => x.Value.ClientNum).ToList().FindAll(x => x.Value.ContractNamespace.Contains(contractNamespace));

            if (krlist.Count > 0)
            {
                foreach (var r in krlist)
                {
                    if (r.Value.pluginList.FindIndex(x => x.name == para.pluginname) > -1)
                    {
                        lock (syncObj)
                        {
                            RoundRobinCount[para.routerid] = r.Key;
                            r.Value.ClientNum += 1;
                            regInfo            = r.Value;
                            break;
                        }
                    }
                }
            }
            if (regInfo == null)
            {
                throw new Exception("找不到对应的路由地址");
            }

            Uri addressUri = new Uri(regInfo.Address);

            //binding = CustomBindConfig.GetRouterBinding(addressUri.Scheme);
            endpointAddress = new EndpointAddress(regInfo.Address);
            //重设Message的目标终结点
            touri = new Uri(regInfo.Address);

            PluginInfo pinfo = regInfo.pluginList.Find(x => x.name == para.pluginname);

            if (pinfo != null && !string.IsNullOrEmpty(pinfo.replyidentify))
            {
                para.replyidentify = pinfo.replyidentify;
            }

            if (hostwcfRouter != null)
            {
                //界面显示
                hostwcfRouter(RegistrationList.Values.ToList());
            }
            return(para);
        }
Esempio n. 14
0
        public void DeleteExistingBooking(string firstname, string surname, double price, bool deposit, string checkInDate, string checkOutDate)
        {
            var requestBody = new AddRequestModel(firstname, surname, price, deposit, checkInDate, checkOutDate);
            var getHeaders  = new HeaderParameter();
            var addHeaders  = getHeaders.AddEncoding().AddLanguage().AddOrigin().AddReferer().AddXmlHttpRequest();

            _annotate
            .Given(_ => _step.TheUserWithTheFollowingDetails(requestBody))
            .And(_ => _step.AddBookingIsCalled(addHeaders))
            .And(_ => _assert.TheStatusCodeIs(HttpStatusCode.OK, StepKey.AddBookingResponseMessage))
            .When(_ => _step.GetBookingsIsCalled(getHeaders))
            .Then(_ => _assert.TheStatusCodeIs(HttpStatusCode.OK, StepKey.GetBookingResponseMessage))
            .And(_ => _assert.TheGetResponseCountIsGreaterThan(1))
            .BDDfy();
        }
Esempio n. 15
0
        public void DeleteBookingIsCalled(HeaderParameter headers, string bookingId)
        {
            var environmentSettings = _gContext.EnvironmentContext;
            var requestParameter    = new RequestParameter(environmentSettings.BaseAddress, environmentSettings.Path + "/" + bookingId, headers, HttpMethod.Delete, null);

            var response = _apiController.Execute(requestParameter);

            _context.Set(StepKey.DeleteBookingResponseMessage, response);

            if (response.IsSuccessStatusCode)
            {
                var resultAsString = _apiController.ReadContentAsString(response);
                _context.Set(StepKey.DeleteBookingSuccess, resultAsString);
            }
        }
        //异步请求
        public IAsyncResult BeginProcessRequest(string clientId, string controller, string method, string jsondata, AsyncCallback callback, object asyncState)
        {
            string pluginname = null;
            string cname      = null;

            string[] names = controller.Split(new char[] { '@' });
            if (names.Length == 2)
            {
                pluginname = names[0];
                cname      = names[1];
            }
            HeaderParameter para = HeaderOperater.GetHeaderValue(OperationContext.Current.RequestContext.RequestMessage);

            return(new CompletedAsyncResult <string>(WcfServerManage.ProcessRequest(clientId, pluginname, cname, method, jsondata, para)));
        }
        //服务请求
        public string ProcessRequest(string clientId, string controller, string method, string jsondata)
        {
            string pluginname = null;
            string cname      = null;

            string[] names = controller.Split(new char[] { '@' });
            if (names.Length == 2)
            {
                pluginname = names[0];
                cname      = names[1];
            }
            HeaderParameter para = HeaderOperater.GetHeaderValue(OperationContext.Current.RequestContext.RequestMessage);

            return(WcfServerManage.ProcessRequest(clientId, pluginname, cname, method, jsondata, para));
        }
Esempio n. 18
0
        public void GetBookingsIsCalled(HeaderParameter headers)
        {
            var environmentSettings = _gContext.EnvironmentContext;
            var requestParameter    = new RequestParameter(environmentSettings.BaseAddress, environmentSettings.Path, headers, HttpMethod.Get, null);

            var response = _apiController.Execute(requestParameter);

            _context.Set(StepKey.GetBookingResponseMessage, response);

            if (response.IsSuccessStatusCode)
            {
                var resultAsString = _apiController.ReadContentAsString(response);
                var result         = JsonConvert.DeserializeObject <List <GetResponseModel> >(resultAsString);
                _context.Set(StepKey.GetBookingSuccess, result);
            }
        }
Esempio n. 19
0
        /// <summary>Initializes a new instance of the <see cref="AsMediaTypeAttribute" /> class.</summary>
        /// <param name="mediaType">Target media type.</param>
        /// <param name="parameters">Optional parameters of the media type.</param>
        public AsMediaTypeAttribute(string mediaType, params string[] parameters)
        {
            if (mediaType == null)
            {
                throw new ArgumentNullException("mediaType");
            }

            if (mediaType.Length == 0)
            {
                throw new ArgumentOutOfRangeException("mediaType");
            }

            MediaType = mediaType;
            var headerParameters = new HeaderParameterCollection();

            parameters.ForEach(parameter => headerParameters.Add(HeaderParameter.Parse(parameter)));
            Parameters = headerParameters;
        }
        public string CreateDomain(string ipAddress)
        {
            //客户端回调
            IClientService  mCallBack = OperationContext.Current.GetCallbackChannel <IClientService>();
            HeaderParameter para      = HeaderOperater.GetHeaderValue(OperationContext.Current.RequestContext.RequestMessage);
            string          ClientID  = WcfServerManage.CreateClient(OperationContext.Current.SessionId, ipAddress, DateTime.Now, mCallBack, para.pluginname, para.replyidentify);

            //异步执行同步缓存
            new Action(delegate()
            {
                if (para.pluginname == "SuperPlugin")
                {
                    //创建连接时候会将上级中间件的缓存同步到下级中间件
                    DistributedCacheManage.SyncAllCache(mCallBack);
                }
            }).BeginInvoke(null, null);

            return(ClientID);
        }
Esempio n. 21
0
        public void GetAddDeleteGetJourney(string firstname, string surname, double price, bool deposit, string checkInDate, string checkOutDate)
        {
            var requestBody   = new AddRequestModel(firstname, surname, price, deposit, checkInDate, checkOutDate);
            var getHeaders    = new HeaderParameter();
            var addHeaders    = getHeaders.AddEncoding().AddLanguage().AddOrigin().AddReferer().AddXmlHttpRequest();
            var deleteHeaders = addHeaders.AddAuthorization();

            _annotate
            .Given(_ => _step.GetBookingsIsCalled(getHeaders))
            .And(_ => _assert.TheStatusCodeIs(HttpStatusCode.OK, StepKey.GetBookingResponseMessage))
            .And(_ => _step.GetCurrentBookingCount())
            .And(_ => _step.TheUserWithTheFollowingDetails(requestBody))
            .And(_ => _step.AddBookingIsCalled(addHeaders))
            .And(_ => _assert.TheStatusCodeIs(HttpStatusCode.OK, StepKey.AddBookingResponseMessage))
            .When(_ => _step.DeleteBookingIsCalled(deleteHeaders))
            .Then(_ => _assert.TheStatusCodeIs(HttpStatusCode.Created, StepKey.DeleteBookingResponseMessage))
            .And(_ => _assert.TheDeleteResponseContains("Created"))
            .And(_ => _assert.CompareCurrentCountToPreviousCountIsTheSame())
            .BDDfy();
        }
Esempio n. 22
0
        private void AddMessageHeader(IContextChannel channel, string cmd, bool iscompressjson, bool isencryptionjson, SerializeType serializetype, Action callback)
        {
            using (var scope = new OperationContextScope(channel as IContextChannel))
            {
                if (string.IsNullOrEmpty(cmd))
                {
                    cmd = "";
                }

                HeaderParameter para = new HeaderParameter();
                para.cmd        = cmd;
                para.routerid   = mConn.RouterID;
                para.pluginname = mConn.PluginName;
                //ReplyIdentify如果客户端创建连接为空,如果中间件连接上级中间件那就是本地中间件标识
                para.replyidentify    = WcfServerManage.Identify;
                para.token            = mConn.Token;
                para.iscompressjson   = iscompressjson;
                para.isencryptionjson = isencryptionjson;
                para.serializetype    = serializetype;
                HeaderOperater.AddMessageHeader(OperationContext.Current.OutgoingMessageHeaders, para);
                callback();
            }
        }
Esempio n. 23
0
            /// <summary>
            /// Add header parameter
            /// </summary>
            /// <param name="headerParameter">Header Parameter</param>
		    public void AddHeaderParameter(HeaderParameter headerParameter) 
            {
			    this.headerParameters.Add(headerParameter.GetName(), headerParameter);
		    }
Esempio n. 24
0
 public string ReplyProcessRequest(HeaderParameter para, string plugin, string controller, string method, string jsondata)
 {
     return(DataManage.ReplyProcessRequest(plugin, controller, method, jsondata, para));
 }
 /// <summary>
 /// Performs conversion between a <see cref="HeaderParameter"/> instance and an <see cref="AdditionalHeaderEnvelope"/> instance.
 /// </summary>
 /// <param name="source">The header parameter instance to convert from.</param>
 /// <returns>A converted instance of <see cref="AdditionalHeaderEnvelope"/>.</returns>
 public static AdditionalHeaderEnvelope ToEnvelope(this HeaderParameter source) =>
Esempio n. 26
0
        public static string ReplyProcessRequest(string plugin, string controller, string method, string jsondata, HeaderParameter para)
        {
            string retJson = null;

            try
            {
                //显示调试信息
                if (WcfGlobal.IsDebug == true)
                {
                    ShowHostMsg(Color.Black, DateTime.Now, "客户端[本地回调]正在执行:" + controller + "." + method + "(" + jsondata + ")");
                }

                begintime();

                #region 执行插件控制器的核心算法
                object[]            paramValue  = null;//jsondata?
                ServiceResponseData retObj      = null;
                LocalPlugin         localPlugin = RemotePluginManage.GetLocalPlugin();
                if (string.IsNullOrEmpty(para.replyidentify) || localPlugin.ServerIdentify == para.replyidentify)
                {
                    if (localPlugin.PluginDic.ContainsKey(plugin) == true)
                    {
                        //先解密再解压
                        string _jsondata = jsondata;
                        //解密参数
                        if (para.isencryptionjson)
                        {
                            DESEncryptor des = new DESEncryptor();
                            des.InputString = _jsondata;
                            des.DesDecrypt();
                            _jsondata = des.OutString;
                        }
                        //解压参数
                        if (para.iscompressjson)
                        {
                            _jsondata = ZipComporessor.Decompress(_jsondata);
                        }

                        ClientRequestData requestData = new ClientRequestData(para.iscompressjson, para.isencryptionjson, para.serializetype);
                        requestData.SetJsonData(_jsondata);
                        requestData.LoginRight = para.LoginRight;

                        EFWCoreLib.CoreFrame.Plugin.ModulePlugin moduleplugin = localPlugin.PluginDic[plugin];
                        retObj = (ServiceResponseData)moduleplugin.WcfServerExecuteMethod(controller, method, paramValue, requestData);

                        if (retObj != null)
                        {
                            retJson = retObj.GetJsonData();
                        }
                        else
                        {
                            retObj = new ServiceResponseData();
                            retObj.Iscompressjson   = para.iscompressjson;
                            retObj.Isencryptionjson = para.isencryptionjson;
                            retObj.Serializetype    = para.serializetype;

                            retJson = retObj.GetJsonData();
                        }

                        retJson = "{\"flag\":0,\"msg\":" + "\"\"" + ",\"data\":" + retJson + "}";
                        //先压缩再加密
                        //压缩结果
                        if (para.iscompressjson)
                        {
                            retJson = ZipComporessor.Compress(retJson);
                        }
                        //加密结果
                        if (para.isencryptionjson)
                        {
                            DESEncryptor des = new DESEncryptor();
                            des.InputString = retJson;
                            des.DesEncrypt();
                            retJson = des.OutString;
                        }
                    }
                    else
                    {
                        throw new Exception("本地插件找不到指定的插件");
                    }
                }
                else//本地插件找不到,就执行远程插件
                {
                    if (RemotePluginManage.GetRemotePlugin().FindIndex(x => x.ServerIdentify == para.replyidentify) > -1)
                    {
                        RemotePlugin rp = RemotePluginManage.GetRemotePlugin().Find(x => x.ServerIdentify == para.replyidentify);
                        string[]     ps = rp.plugin;

                        if (ps.ToList().FindIndex(x => x == plugin) > -1)
                        {
                            retJson = rp.callback.ReplyProcessRequest(para, plugin, controller, method, jsondata);
                        }
                        else
                        {
                            throw new Exception("远程插件找不到指定的插件");
                        }
                    }
                    else
                    {
                        throw new Exception("远程插件找不到指定的回调中间件");
                    }
                }
                #endregion

                //System.Threading.Thread.Sleep(20000);//测试并发问题,此处也没有问题
                double outtime = endtime();
                //记录超时的方法
                if (ClientManage.IsOverTime == true)
                {
                    if (outtime > Convert.ToDouble(ClientManage.OverTime * 1000))
                    {
                        WriterOverTimeLog(outtime, controller + "." + method + "(" + jsondata + ")");
                    }
                }
                //显示调试信息
                if (WcfGlobal.IsDebug == true)
                {
                    ShowHostMsg(Color.Green, DateTime.Now, "客户端[本地回调]收到结果(耗时[" + outtime + "]):" + retJson);
                }

                if (retJson == null)
                {
                    throw new Exception("请求的插件未获取到有效数据");
                }

                return(retJson);
            }
            catch (Exception err)
            {
                //记录错误日志
                //EFWCoreLib.CoreFrame.EntLib.ZhyContainer.CreateException().HandleException(err, "HISPolicy");

                if (err.InnerException == null)
                {
                    retJson = "{\"flag\":1,\"msg\":" + "\"" + err.Message + "\"" + "}";
                    if (para.iscompressjson)
                    {
                        retJson = ZipComporessor.Compress(retJson);
                    }
                    ShowHostMsg(Color.Red, DateTime.Now, "客户端[本地回调]执行失败:" + err.Message);
                    return(retJson);
                }
                else
                {
                    retJson = "{\"flag\":1,\"msg\":" + "\"" + err.InnerException.Message + "\"" + "}";
                    if (para.iscompressjson)
                    {
                        retJson = ZipComporessor.Compress(retJson);
                    }
                    ShowHostMsg(Color.Red, DateTime.Now, "客户端[本地回调]执行失败:" + err.InnerException.Message);
                    return(retJson);
                }
            }
        }
Esempio n. 27
0
 public void it_should_throw_when_setting_parameter_with_incorrect_name()
 {
     new HeaderParameterCollection().Invoking(parameters => parameters["test"] = new HeaderParameter("some")).ShouldThrow <InvalidOperationException>();
 }
Esempio n. 28
0
        public static string ProcessRequest(string clientId, string plugin, string controller, string method, string jsondata, HeaderParameter para)
        {
            string retJson = null;

            try
            {
                if (plugin == null || controller == null)
                {
                    throw new Exception("插件名称或控制器名称不能为空!");
                }

                if (ClientManage.ClientDic.ContainsKey(clientId) == false)
                {
                    throw new Exception("客户端不存在,正在创建新的连接!");
                }

                if (ClientManage.IsToken == true)//非调试模式下才验证
                {
                    //验证身份,创建连接的时候验证,请求不验证
                    IsAuth(plugin, controller, method, para.token);
                }

                //显示调试信息
                if (WcfGlobal.IsDebug == true)
                {
                    ShowHostMsg(Color.Black, DateTime.Now, "客户端[" + clientId + "]正在执行:" + controller + "." + method + "(" + jsondata + ")");
                }


                begintime();

                #region 执行插件控制器的核心算法
                object[]            paramValue  = null;//jsondata?
                ServiceResponseData retObj      = null;
                LocalPlugin         localPlugin = RemotePluginManage.GetLocalPlugin();
                if (string.IsNullOrEmpty(para.replyidentify) || localPlugin.ServerIdentify == para.replyidentify)
                {
                    if (localPlugin.PluginDic.ContainsKey(plugin) == true)
                    {
                        //先解密再解压
                        string _jsondata = jsondata;
                        //解密参数
                        if (para.isencryptionjson)
                        {
                            DESEncryptor des = new DESEncryptor();
                            des.InputString = _jsondata;
                            des.DesDecrypt();
                            _jsondata = des.OutString;
                        }
                        //解压参数
                        if (para.iscompressjson)
                        {
                            _jsondata = ZipComporessor.Decompress(_jsondata);
                        }

                        ClientRequestData requestData = new ClientRequestData(para.iscompressjson, para.isencryptionjson, para.serializetype);
                        requestData.SetJsonData(_jsondata);
                        requestData.LoginRight = para.LoginRight;

                        EFWCoreLib.CoreFrame.Plugin.ModulePlugin moduleplugin = localPlugin.PluginDic[plugin];
                        retObj = (ServiceResponseData)moduleplugin.WcfServerExecuteMethod(controller, method, paramValue, requestData);

                        if (retObj != null)
                        {
                            retJson = retObj.GetJsonData();
                        }
                        else
                        {
                            retObj = new ServiceResponseData();
                            retObj.Iscompressjson   = para.iscompressjson;
                            retObj.Isencryptionjson = para.isencryptionjson;
                            retObj.Serializetype    = para.serializetype;

                            retJson = retObj.GetJsonData();
                        }

                        retJson = "{\"flag\":0,\"msg\":" + "\"\"" + ",\"data\":" + retJson + "}";
                        //先压缩再加密
                        //压缩结果
                        if (para.iscompressjson)
                        {
                            retJson = ZipComporessor.Compress(retJson);
                        }
                        //加密结果
                        if (para.isencryptionjson)
                        {
                            DESEncryptor des = new DESEncryptor();
                            des.InputString = retJson;
                            des.DesEncrypt();
                            retJson = des.OutString;
                        }
                    }
                    else
                    {
                        throw new Exception("本地插件找不到指定的插件");
                    }
                }
                else//本地插件找不到,就执行远程插件
                {
                    if (RemotePluginManage.GetRemotePlugin().FindIndex(x => x.ServerIdentify == para.replyidentify) > -1)
                    {
                        RemotePlugin rp = RemotePluginManage.GetRemotePlugin().Find(x => x.ServerIdentify == para.replyidentify);
                        string[]     ps = rp.plugin;

                        if (ps.ToList().FindIndex(x => x == plugin) > -1)
                        {
                            retJson = rp.callback.ReplyProcessRequest(para, plugin, controller, method, jsondata);
                        }
                        else
                        {
                            throw new Exception("远程插件找不到指定的插件");
                        }
                    }
                    else
                    {
                        throw new Exception("远程插件找不到指定的回调中间件");
                    }
                }
                #endregion

                double outtime = endtime();
                //记录超时的方法
                if (ClientManage.IsOverTime == true)
                {
                    if (outtime > Convert.ToDouble(ClientManage.OverTime * 1000))
                    {
                        WriterOverTimeLog(outtime, controller + "." + method + "(" + jsondata + ")");
                    }
                }
                //显示调试信息
                if (WcfGlobal.IsDebug == true)
                {
                    ShowHostMsg(Color.Green, DateTime.Now, "客户端[" + clientId + "]收到结果(耗时[" + outtime + "]):" + retJson);
                }

                //更新客户端信息
                ClientManage.UpdateRequestClient(clientId, jsondata == null ? 0 : jsondata.Length, retJson == null ? 0 : retJson.Length);


                if (retJson == null)
                {
                    throw new Exception("插件执行未返回有效数据");
                }

                return(retJson);
            }
            catch (Exception err)
            {
                //记录错误日志
                if (err.InnerException == null)
                {
                    retJson = "{\"flag\":1,\"msg\":" + "\"" + err.Message + "\"" + "}";
                    if (para.iscompressjson)
                    {
                        retJson = ZipComporessor.Compress(retJson);
                    }
                    ShowHostMsg(Color.Red, DateTime.Now, "客户端[" + clientId + "]执行失败:" + err.Message);
                    return(retJson);
                }
                else
                {
                    retJson = "{\"flag\":1,\"msg\":" + "\"" + err.InnerException.Message + "\"" + "}";
                    if (para.iscompressjson)
                    {
                        retJson = ZipComporessor.Compress(retJson);
                    }
                    ShowHostMsg(Color.Red, DateTime.Now, "客户端[" + clientId + "]执行失败:" + err.InnerException.Message);
                    return(retJson);
                }
            }
        }
Esempio n. 29
0
        public Message ProcessMessage(Message requestMessage)
        {
            try
            {
                //计时器
                Stopwatch sw = new Stopwatch();
                sw.Start();

                IRouterBaseHandler proxy = null;
                HeaderParameter    para  = HeaderOperater.GetHeaderValue(requestMessage);

                if (RouterManage.routerDic.ContainsKey(para.routerid))
                {
                    proxy = RouterManage.routerDic[para.routerid];
                    para.replyidentify = RouterManage.headParaDic[para.routerid].replyidentify;
                }
                else
                {
                    //Binding binding = null;
                    EndpointAddress endpointAddress = null;
                    Uri             touri           = null;
                    para = RouterManage.AddClient(requestMessage, para, out endpointAddress, out touri);
                    requestMessage.Headers.To = touri;

                    IRouterBaseReply callback = OperationContext.Current.GetCallbackChannel <IRouterBaseReply>();
                    NetTcpBinding    tbinding = new NetTcpBinding("NetTcpBinding_BaseService");
                    DuplexChannelFactory <IRouterBaseHandler> factory = new DuplexChannelFactory <IRouterBaseHandler>(new InstanceContext(new ReplyRouterBaseCallback(callback)), tbinding, endpointAddress);
                    proxy = factory.CreateChannel();

                    //缓存会话
                    RouterManage.routerDic.Add(para.routerid, proxy);
                    RouterManage.headParaDic.Add(para.routerid, para);
                }

                Message responseMessage = null;
                try
                {
                    HeaderOperater.AddMessageHeader(requestMessage, para);//增加自定义消息头
                    responseMessage = proxy.ProcessMessage(requestMessage);
                }
                catch (CommunicationException e)
                {
                    RouterManage.RemoveClient(para);
                    throw e;
                }
                if (para.cmd == "Quit")
                {
                    //关闭连接释放缓存会话
                    RouterManage.RemoveClient(para);
                }

                //double outtime = endtime();
                // 请求消息记录
                if (WcfGlobal.IsDebug)
                {
                    MiddlewareLogHelper.WriterLog(LogType.MidLog, true, Color.Black, String.Format("路由请求消息发送(耗时[" + sw.Elapsed.TotalMilliseconds + "]):  {0}", requestMessage.Headers.Action));
                }


                return(responseMessage);
            }
            catch (Exception e)
            {
                return(Message.CreateMessage(requestMessage.Version, FaultCode.CreateReceiverFaultCode("error", RouterManage.ns), e.Message, requestMessage.Headers.Action));
            }
        }
Esempio n. 30
0
            /// <summary>
            /// Remove header parameter
            /// </summary>
            /// <param name="headerParameter">Header Parameter</param>
		    public void RemoveHeaderParameter(HeaderParameter headerParameter) 
            {
			    this.queryParameters.Remove(headerParameter.GetName());
		    }
Esempio n. 31
0
        public string ProcessRequest(string clientId, string plugin, string controller, string method, string jsondata)
        {
            HeaderParameter para = HeaderOperater.GetHeaderValue(OperationContext.Current.RequestContext.RequestMessage);

            return(DataManage.ProcessRequest(clientId, plugin, controller, method, jsondata, para));
        }
Esempio n. 32
0
        public IAsyncResult BeginProcessRequest(string clientId, string plugin, string controller, string method, string jsondata, AsyncCallback callback, object asyncState)
        {
            HeaderParameter para = HeaderOperater.GetHeaderValue(OperationContext.Current.RequestContext.RequestMessage);

            return(new CompletedAsyncResult <string>(DataManage.ProcessRequest(clientId, plugin, controller, method, jsondata, para)));
        }