Ejemplo n.º 1
0
        public void submitMove(string sku, string fromloc, string fromid, string toid, string qty, string actloc)
        {
            string errortxt = this.Vaildate();
            if (errortxt != string.Empty)
            {
                MessageBox.Show(errortxt);
                this.focusControl.Focus();
                return;
            }
            reqitem = req.Utility.Create( sku,  fromloc,  fromid,  toid,  qty,  actloc);
            reqitem.UtilityHeader.userid = this.loginuser.UserName;
             RequestMessage request = new RequestMessage(enumRequestType.MessageProcessor,
                  enumMessageType.Utility,
                  enumRequestMethod.functionOperation, this.loginuser,
                  enumSendSysId.EXceed,
                  reqitem);
            //RequestWorkItem workitem = new RequestWorkItem(request, 1);
            ResponseMessage response = ThreadHelper.Execute(request);
            string errormsg = response.GetErrorMessage();
            if (errormsg != string.Empty)
            {
                MessageBox.Show(response.GetErrorMessage());
            }
            else
            {
                MessageBox.Show("移动完成");
                Clean();

            }
        }
Ejemplo n.º 2
0
        public ResponseMessage ExchangeAsClient(RequestMessage request)
        {
            PrepareExchangeAsClient();

            stream.Send(request);
            return stream.Receive<ResponseMessage>();
        }
Ejemplo n.º 3
0
 protected override void HandleRequest(RequestMessage request, PeerState peer)
 {
     if (!peer.IsChoked && request.Length <= Global.Instance.BlockSize)
     {
         BlockManager.GetBlock(new byte[request.Length], request.Index, request.Offset, request.Length, BlockRead, peer);
     }
 }
 private void OnNewUpdate(
     IRequestManager<ConfigurationUpdate, ConfigurationUpdateAnswer> sender, 
     RequestMessage<ConfigurationUpdate> request)
 {
     var newConfiguration = request.request.update;
     //Not the most efficient code, but premature optimisation is root of evil.
     lock (internalLock)
     {
         var existing = allConfigurations.FirstOrDefault(o =>
             o.Instance == newConfiguration.Instance &&
             o.Key == newConfiguration.Key
         );
         if (existing != null)
         {
             existing.Value = newConfiguration.Value;
         }
         else
         {
             allConfigurations.Add(newConfiguration);
         }
     }
     this.persister.Persist(allConfigurations);
     //Todo here broadcast the update?
     sender.Send(new AnwserMessage<ConfigurationUpdateAnswer>()
     {
         id = request.id,
         answer = new ConfigurationUpdateAnswer()
         {
             result = true
         }
     });
 }
Ejemplo n.º 5
0
        public void SecureClientClearsPoolWhenAllConnectionsCorrupt()
        {
            var pool = new ConnectionPool<ServiceEndPoint, IConnection>();
            var stream = Substitute.For<IMessageExchangeStream>();
            stream.When(x => x.IdentifyAsClient()).Do(x => { throw new ConnectionInitializationFailedException(""); });
            for (int i = 0; i < SecureClient.RetryCountLimit; i++)
            {
                var connection = Substitute.For<IConnection>();
                connection.Protocol.Returns(new MessageExchangeProtocol(stream));
                pool.Return(endpoint, connection);
            }

            var request = new RequestMessage
            {
                Destination = endpoint,
                ServiceName = "IEchoService",
                MethodName = "SayHello",
                Params = new object[] { "Fred" }
            };

            var secureClient = new SecureClient(endpoint, Certificates.Octopus, log, pool);
            ResponseMessage response = null;
            secureClient.ExecuteTransaction((mep) => response = mep.ExchangeAsClient(request));

            // The pool should be cleared after the second failure
            stream.Received(2).IdentifyAsClient();
            // And a new valid connection should then be made
            Assert.AreEqual("Fred...", response.Result);
        }
Ejemplo n.º 6
0
        public void call_asnlist01(string pier)
        {
            //this.Start();
            //this.portlist.Items.Clear();
            //this.portlist.Enabled = false;
            asnlist01req = asnlist01_req.AdvancedShipNotice.Create(pier);

            RequestMessage request = new RequestMessage(enumRequestType.MessageProcessor,
                  enumMessageType.AdvancedShipNotice,
                  enumRequestMethod.listHead, this.loginuser,
                  enumSendSysId.EXceed,
                  asnlist01req);
            //RequestWorkItem workitem = new RequestWorkItem(request, 2);
            //threadhelper.AddWorkItem(workitem);
            ResponseMessage Response = ThreadHelper.Execute(request);
            string errormsg = Response.GetErrorMessage();
            if (errormsg != string.Empty)
            {
                MessageBox.Show(Response.GetErrorMessage());
            }
            else
            {
                asnlist01res = Response.Deserialize<asnlist01_res.AdvancedShipNotice>();
                foreach (asnlist01_res.AdvancedShipNoticeHeader body in asnlist01res.AdvancedShipNoticeHeaders)
                {
                    if (!string.IsNullOrEmpty(body.ReceiptKey))
                    {
                        this.addasnlist(body.ReceiptKey + " " + body.StorerKey + " " + body.Status);
                    }
                    //InvokeHelper.Invoke(this, "addasnlist", body.ReceiptKey + " " + body.StorerKey + " " + body.Status);
                }
            }
        }
Ejemplo n.º 7
0
        private void call_UserData(string username, string password)
        {
            userinforeq = fllg_req.Utility.Create(username, password);
            RequestMessage searchrequest = new RequestMessage(enumRequestType.MessageProcessor,
                enumMessageType.Utility,
                enumRequestMethod.functionOperation, this._user,
                enumSendSysId.EXceed,
                userinforeq);
            RequestWorkItem workitem = new RequestWorkItem(searchrequest, 1);
            //threadhelper.AddWorkItem(workitem);
            ResponseMessage Response = ThreadHelper.Execute(searchrequest);
            if (Response.GetErrorMessage() != string.Empty)
            {
                MessageBox.Show(Response.GetErrorMessage());
                this.usernametxt.Focus();
            }
            else
            {
                this.userinfores = Response.Deserialize<fllg_res.Utility>();
                if (this._user.UserName == string.Empty)
                {
                    MessageBox.Show("用户名不存在");
                    this.usernametxt.Focus();
                }
                else
                {
                    this.screen = this.userinfores.UtilityHeader[0].Screen.Split(new char[] { ';' });
                    //InvokeHelper.Set(this, "DialogResult", DialogResult.OK);
                    DialogResult = DialogResult.OK;

                }
            }
        }
Ejemplo n.º 8
0
        private void call_NSPRFIQ01()
        {
            this.request.UtilityHeader.userid = this.LoginUser.UserName;
            RequestMessage query = new RequestMessage(enumRequestType.MessageProcessor,
                enumMessageType.Utility,
                enumRequestMethod.functionOperation, this.LoginUser,
                enumSendSysId.EXceed,
                this.request);

            ResponseMessage response = ThreadHelper.Execute(query);
            string errormsg = response.GetErrorMessage();
            if (errormsg != string.Empty)
            {
                MessageBox.Show(response.GetErrorMessage());
            }
            else
            {
                RFDeviceAPP.Common.NSPRFIQ01.Response.Utility result = response.Deserialize<RFDeviceAPP.Common.NSPRFIQ01.Response.Utility>();
                //Console.Write(result);
                //FrmStockResult resultfrm = new FrmStockResult(result);
                FrmStockResultDetail resultfrm = new FrmStockResultDetail(result);
                resultfrm.ShowDialog();
                this.Activate();
                this.storerkey.SetFocus();
            }
        }
Ejemplo n.º 9
0
        private void loadReason()
        {
            RFDeviceAPP.Common.TaskReason.Request.TaskReason request = RFDeviceAPP.Common.TaskReason.Request.TaskReason.Craete(this.LoginUser.UserName);
            RequestMessage requestmessage = new RequestMessage(enumRequestType.MessageProcessor,
                  enumMessageType.TaskReason,
                  enumRequestMethod.list, this.LoginUser,
                  enumSendSysId.EXceed,
                  request);
            RequestWorkItem workitem = new RequestWorkItem(requestmessage, 1);
            //threadhelper.AddWorkItem(workitem);
            ResponseMessage Response = ThreadHelper.Execute(requestmessage);
            string errormsg = Response.GetErrorMessage();
            if (errormsg != string.Empty)
            {
                MessageBox.Show(errormsg);

            }
            else
            {
                RFDeviceAPP.Common.TaskReason.Response.TaskReason tasklist = Response.Deserialize<RFDeviceAPP.Common.TaskReason.Response.TaskReason>();
                foreach (RFDeviceAPP.Common.TaskReason.Response.TaskReasonHeader header in tasklist.TaskReasonHeaders)
                {
                    string line = header.TASKMANAGERREASONKEY;
                    this.listBox1.Items.Add(line);
                }
                this.listBox1.SelectedIndex = 0;

            }
        }
Ejemplo n.º 10
0
        public void call_NSPRFSH01()
        {
            string errortxt = this.Vaildate();
            if (errortxt != string.Empty)
            {
                MessageBox.Show(errortxt);
                this.focusControl.Focus();
                return;
            }
            string[] tmp = this.toid.Text.Split(new char[] { ' ' });
            string toidstr = tmp[0];

            sh01_req.Utility sh01req = sh01_req.Utility.CreateSH(toidstr);
            sh01req.UtilityHeader.userid = this.LoginUser.UserName;
            RequestMessage requestmessage = new RequestMessage(enumRequestType.MessageProcessor,
                  enumMessageType.Utility,
                  enumRequestMethod.functionOperation, this.LoginUser,
                  enumSendSysId.EXceed,
                  sh01req);
            ResponseMessage response = ThreadHelper.Execute(requestmessage);
            string errormsg = response.GetErrorMessage();
            if (errormsg != string.Empty)
            {
                MessageBox.Show(response.GetErrorMessage());

            }
            else
            {

                MessageBox.Show("发运完成");
            }
        }
Ejemplo n.º 11
0
 public RawRequestMessage(RequestMessage rm, int commandCount)
 {
     var prefix = (rm.Prefix ?? "");
     Id = prefix + (prefix.Length>0?"_":"") + commandCount;
     Type = rm.Type??"request";
     Uri = rm.Uri;
     Payload = rm.Payload;
 }
 private static RequestMessage<ConfigurationSubscription> GetRequestMessage(int requestId, string goodInstance)
 {
     var request = new RequestMessage<ConfigurationSubscription>()
     {
         id = requestId,
         request = new ConfigurationSubscription() {instance = goodInstance}
     };
     return request;
 }
Ejemplo n.º 13
0
		public override ResponseMessage Execute (RequestMessage req)
		{
			// Start the shutdown process in a separate thread
			// to avoid a deadlock: BeginShutdown() waits until
			// all worker process are finished, but this method
			// itself is part of a worker.
			ExceptionHandlingThread.Start (new ThreadStart (DoShutdown));

			return new EmptyResponse ();
		}
Ejemplo n.º 14
0
 public override void Publish(RequestMessage request)
 {
     try
     {
         Write(request);
     }
     catch (Exception e)
     {
         OnChannelError(e);
     }
 }
Ejemplo n.º 15
0
 static ResponseMessage InvokeAndWrapAnyExceptions(RequestMessage request, Func<RequestMessage, ResponseMessage> incomingRequestProcessor)
 {
     try
     {
         return incomingRequestProcessor(request);
     }
     catch (Exception ex)
     {
         return ResponseMessage.FromException(request, ex);
     }
 }
Ejemplo n.º 16
0
        void IMessageSink.Invoke(RequestMessage request)
        {
            if (request == null) throw new ArgumentNullException("request");

            DistributedMessaging messaging = DistributedMessaging.Instance;
            Action<RequestMessage> eventHandler = messaging.Handlers.Outgoing.Request(request.Event);
            if (eventHandler != null)
            {
                eventHandler.DynamicInvoke(request);
            }
        }
		public override ResponseMessage Execute (RequestMessage req)
		{
			this.info_request = (InformationalMessagesRequest) req;

			if (QueryDriver.IsIndexing)
				SendIndexingStatusResponse (IndexingStatus.Running);

			QueryDriver.ChangedEvent += OnQueryDriverChanged;

			// Don't send a response; we'll be sending them async.
			return null;
		}
Ejemplo n.º 18
0
        protected static Cybersource.RequestMessage CreateRequest()
        {
            RequestMessage request = new RequestMessage();

            request.clientLibrary = ".NET WCF";
            request.clientLibraryVersion = Environment.Version.ToString();
            request.clientEnvironment =
                Environment.OSVersion.Platform +
                Environment.OSVersion.Version.ToString();

            return request;
        }
Ejemplo n.º 19
0
        async Task Simple(EndpointConfiguration endpointConfiguration, IEndpointInstance endpoint, SendOptions sendOptions)
        {
            #region 5to6-Callbacks-InstanceId
            endpointConfiguration.ScaleOut().InstanceDiscriminator("uniqueId");
            #endregion

            #region 5to6-Callbacks

            RequestMessage message = new RequestMessage();
            ResponseMessage response = await endpoint.Request<ResponseMessage>(message, sendOptions);

            #endregion
        }
Ejemplo n.º 20
0
        private void CalculateBtn_Click(object sender, EventArgs e)
        {
            // Create the request message.
            RequestMessage aRequest = new RequestMessage();
            aRequest.Number1 = int.Parse(Number1TextBox.Text);
            aRequest.Number2 = int.Parse(Number2TextBox.Text);

            // Send request to the service to calculate 2 numbers.
            // It waits until the response is received.
            ResponseMessage aResponse = mySender.SendRequestMessage(aRequest);

            // Display the result.
            ResultTextBox.Text = aResponse.Result.ToString();
        }
Ejemplo n.º 21
0
        Callbacks(IBus bus)
        {
            #region 5to6-Callbacks

            RequestMessage requestMessage = new RequestMessage();
            bus.Send(requestMessage)
                .Register(ar =>
                {
                    CompletionResult localResult = (CompletionResult) ar.AsyncState;
                    ResponseMessage response = (ResponseMessage) localResult.Messages[0];
                }, null);

            #endregion
        }
        public void Call_NSPRFQUERYBYDROPID(string dropid)
        {
            RFDeviceAPP.Common.NSPRFQUERYBYDROPID.Request.Utility req = RFDeviceAPP.Common.NSPRFQUERYBYDROPID.Request.Utility.Create(dropid);
            RequestMessage request = new RequestMessage(enumRequestType.MessageProcessor,
              enumMessageType.Utility,
              enumRequestMethod.functionOperation, this.LoginUser,
              enumSendSysId.EXceed,
              req);

            ResponseMessage response = ThreadHelper.Execute(request);
            string xmls = response.XmlString;
            RFDeviceAPP.Common.NSPRFQUERYBYDROPID.Response.Utility result = response.Deserialize<RFDeviceAPP.Common.NSPRFQUERYBYDROPID.Response.Utility>();
            string errormsg = response.GetErrorMessage();
            if (errormsg != string.Empty)
            {
                MessageBox.Show(response.GetErrorMessage());
            }
            else
            {
                this.wavekeytxt.Text = result.UtilityHeader.WaveKey;
                this.orderkeytxt.Text = result.UtilityHeader.OrderKey;
                if (!this.orderkeytxt.Text.Equals(""))
                {
                    ShipmentOrder spod = ShipmentOrder.CreatePOD(this.orderkeytxt.Text);
                    RequestMessage searchrequest = new RequestMessage(enumRequestType.MessageProcessor,
                      enumMessageType.ShipmentOrder,
                      enumRequestMethod.list, this.LoginUser,
                      enumSendSysId.EXceed,
                      spod);

                    ResponseMessage response1 = ThreadHelper.Execute(searchrequest);
                    if (response1.GetErrorMessage() != string.Empty)
                    {
                        MessageBox.Show(response1.GetErrorMessage());
                        this.dropidtxt.Focus();
                    }
                    else
                    {
                        RFDeviceAPP.Common.Orders.ShipmentOrder result1 = response1.Deserialize<RFDeviceAPP.Common.Orders.ShipmentOrder>();
                        this.susr15.Text = result1.ShipmentOrderHeader.SUSR15;
                    }
                }

                if (result.UtilityHeader.ISFULLPICKED == "0" && result.UtilityHeader.OrderKey.Length > 0)
                {
                    MessageBox.Show("该订单拣货完成");
                    this.dropidtxt.SetFocus();
                }
            }
        }
Ejemplo n.º 23
0
        public void call_NSPRFRL021SO()
        {
            //this.Start();
            this.RL02Sreq = RL02S_req.Utility.Create(this.orderkey.Text);

            RequestMessage requestmessage = new RequestMessage(enumRequestType.MessageProcessor,
                  enumMessageType.Utility,
                  enumRequestMethod.functionOperation, this.LoginUser,
                  enumSendSysId.EXceed,
                  this.RL02Sreq);
            RequestWorkItem workitem = new RequestWorkItem(requestmessage, 1);
            //threadhelper.AddWorkItem(workitem);
            ResponseMessage Response = ThreadHelper.Execute(requestmessage);

               string errormsg = Response.GetErrorMessage();
            if (errormsg != string.Empty)
            {
                MessageBox.Show(errormsg);
                return;

            }
            this.RL02Sres = Response.Deserialize<RL02S_res.Utility>();
            if (RL02Sres != null)
            {
                this.orderlist = new List<OrderItem>();
                foreach (RL02S_res.UtilityHeader header in RL02Sres.UtilityHeaders)
                {
                    if (header.OrderKey.Length > 0)
                    {
                        OrderItem item = new OrderItem();
                        item.Dropid = header.DropID;
                        item.Orderkey = header.OrderKey;
                        item.Loc = header.Loc;
                        if (item.Orderkey.Length > 0)
                        {
                            this.orderlist.Add(item);
                        }
                    }
                    //string itemstring = string.Format("{2} {0} {1}", header.DropID, header.Loc, header.OrderKey);
                    //if (itemstring.Length > 5)
                    //{
                    //    //InvokeHelper.Invoke(this, "adddroplist", itemstring);
                    //    this.adddroplist(itemstring);
                    //}
                }
                this.countlable.Text = string.Format("总数: {0}", this.orderlist.Count);
                this.gridbinding(this.orderlist);
                this.dropid.SetFocus();
            }
        }
Ejemplo n.º 24
0
        static object[] GetArguments(RequestMessage requestMessage, MethodInfo methodInfo)
        {
            var methodParams = methodInfo.GetParameters();
            var args = new object[methodParams.Length];
            for (var i = 0; i < methodParams.Length; i++)
            {
                if (i >= requestMessage.Params.Length) continue;

                var jsonArg = requestMessage.Params[i];
                args[i] = jsonArg;
            }

            return args;
        }
Ejemplo n.º 25
0
        public void Test_Serialize_MessageContainingDefaultValues()
        {
            var serializer = new ProtobufSerializer(null);

            var msg = new IDefault_PayloadTable.CallWithDefault_Invoke { a = 2, b = 2, c = "Test" };
            var obj = new RequestMessage { InvokePayload = msg };

            var bytes = serializer.ToBinary(obj);
            var obj2 = (RequestMessage)serializer.FromBinary(bytes, null);
            var msg2 = (IDefault_PayloadTable.CallWithDefault_Invoke)obj2.InvokePayload;

            Assert.Equal(msg.a, msg2.a);
            Assert.Equal(msg.b, msg2.b);
            Assert.Equal(msg.c, msg2.c);
        }
Ejemplo n.º 26
0
        public void NSPRFTM01(string area, string taskcode)
        {
            //this.Start();
            this.task_req1 = task_req.Utility.CreateInstance(area, taskcode);
            this.task_req1.UtilityHeader.userid = this.loginuser.UserName;
            //UserInfo admin = new UserInfo();
            //admin.UserName = "******";
            //admin.Password = "******";
            RequestMessage requestmessage = new RequestMessage(enumRequestType.MessageProcessor,
                  enumMessageType.Utility,
                  enumRequestMethod.functionOperation, this.loginuser,
                  enumSendSysId.EXceed,
                  this.task_req1);
            //RequestWorkItem workitem = new RequestWorkItem(requestmessage, 1);
            //threadhelper.AddWorkItem(workitem);
            ResponseMessage Response = ThreadHelper.Execute(requestmessage);
               string errormsg = Response.GetErrorMessage();
               if (errormsg != string.Empty)
               {
               this.submitbtn.SetEnabled(true);

               MessageBox.Show(errormsg);
               this.area01txt.SetFocus();
               this.task_req1 = null;

               }
               else
               {

                   this.task_res1 = Response.Deserialize<task_res.Utility>();
                   //Console.WriteLine(task_res1);
                   //6上架4拣货
                   if (task_res1.UtilityHeader.rectype == "6")
                   {

                       this.OpenRFTPA00Frm(this.loginuser, this.task_res1);
                   }
                   else if (task_res1.UtilityHeader.rectype == "4")
                   {
                        this.OpenRFTPK01C( this.loginuser, this.task_res1);
                   }
                   else
                   {

                   }

               }
        }
Ejemplo n.º 27
0
 public void call_NSPRFTM01(string area, string taskcode)
 {
     this.Start();
     this.task_req1 = task_req.Utility.CreateInstance(area, taskcode);
     this.task_req1.UtilityHeader.userid =   this.loginuser.UserName;
     //UserInfo admin = new UserInfo();
     //admin.UserName = "******";
     //admin.Password = "******";
     RequestMessage requestmessage = new RequestMessage(enumRequestType.MessageProcessor,
           enumMessageType.Utility,
           enumRequestMethod.functionOperation, this.loginuser,
           enumSendSysId.EXceed,
           this.task_req1);
     RequestWorkItem workitem = new RequestWorkItem(requestmessage, 1);
     threadhelper.AddWorkItem(workitem);
 }
Ejemplo n.º 28
0
        public ResponseMessage Invoke(RequestMessage requestMessage)
        {
            using (var lease = factory.CreateService(requestMessage.ServiceName))
            {
                var methods = lease.Service.GetType().GetMethods().Where(m => string.Equals(m.Name, requestMessage.MethodName, StringComparison.OrdinalIgnoreCase)).ToList();
                if (methods.Count == 0)
                {
                    return ResponseMessage.FromError(requestMessage, string.Format("Service {0}::{1} not found", lease.Service.GetType().FullName, requestMessage.MethodName));
                }

                var method = SelectMethod(methods, requestMessage);
                var args = GetArguments(requestMessage, method);
                var result = method.Invoke(lease.Service, args);
                return ResponseMessage.FromResult(requestMessage, result);
            }
        }
Ejemplo n.º 29
0
        public void TestSeriDeseri_RequestMessage()
        {
            var serializer = new ProtobufSerializer(null);

            var obj = new RequestMessage
            {
                RequestId = 12345678,
                InvokePayload = new TestInvokableMessage { a = "Hello", b = "World" }
            };

            var bytes = serializer.ToBinary(obj);

            var obj2 = (RequestMessage)serializer.FromBinary(bytes, null);
            Assert.Equal(obj.RequestId, obj2.RequestId);
            Assert.Equal(((TestInvokableMessage)obj.InvokePayload).a, ((TestInvokableMessage)obj2.InvokePayload).a);
            Assert.Equal(((TestInvokableMessage)obj.InvokePayload).b, ((TestInvokableMessage)obj2.InvokePayload).b);
        }
Ejemplo n.º 30
0
        void IMessageSink.Invoke(RequestMessage request)
        {
            if (request == null) throw new ArgumentNullException("request");

            MessageEvent incomingRequest = DAO.For<MessageEvent>().Single(match => match.CorrelationId == request.CorrelationId
                && match.Kind == MessageEventKind.Request && match.Direction == MessageEventDirection.Incoming
                && match.Thumbprint == request.Thumbprint());
            if (incomingRequest != null)
            {
                throw new DuplicateRequestException(String.Format("Incoming Request '{0}' for Event '{1}' was already processed. Request will be Ignored!"
                    , request.CorrelationId
                    , request.Event)
                    , request);
            }

            DAO.For<MessageEvent>().Upsert(request);
        }
        public void RequestEncoding()
        {
            int length = new RequestMessage(5, 1024, 16384).Encode(buffer, offset);

            Assert.AreEqual("00-00-00-0D-06-00-00-00-05-00-00-04-00-00-00-40-00", BitConverter.ToString(buffer, offset, length));
        }
Ejemplo n.º 32
0
        public OperationReturn EncryptRecord(string fileName, string strPassword)
        {
            OperationReturn optReturn = new OperationReturn();

            optReturn.Result = true;
            optReturn.Code   = 0;
            try
            {
                optReturn.Data = fileName;
                if (Session == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = RET_NO_SESSION;
                    optReturn.Message = string.Format("SessionInfo is null");
                    return(optReturn);
                }
                if (mRecordInfo == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = RET_NO_RECORDINFO;
                    optReturn.Message = string.Format("RecordInfo is null");
                    return(optReturn);
                }
                if (mRecordInfo.MediaType != 1)
                {
                    //只能对录音文件进行加密
                    return(optReturn);
                }
                if (Service03Helper == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("Service03Helper is null");
                    return(optReturn);
                }
                RequestMessage request;
                ReturnMessage  retMessage;
                request         = new RequestMessage();
                request.Command = (int)Service03Command.EncryptRecordFile;
                request.ListData.Add(fileName);
                request.ListData.Add(strPassword);
                optReturn = Service03Helper.DoRequest(request);
                if (!optReturn.Result)
                {
                    return(optReturn);
                }
                retMessage = optReturn.Data as ReturnMessage;
                if (retMessage == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("RetMessage is null");
                    return(optReturn);
                }
                if (!retMessage.Result)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = retMessage.Code;
                    optReturn.Message = retMessage.Message;
                    return(optReturn);
                }
                fileName       = retMessage.Data;
                optReturn.Data = fileName;
                OnDebug("EncryptRecord", string.Format("EncryptRecord end.\t{0}", fileName));
            }
            catch (Exception ex)
            {
                optReturn.Result    = false;
                optReturn.Code      = Defines.RET_FAIL;
                optReturn.Message   = ex.Message;
                optReturn.Exception = ex;
            }
            return(optReturn);
        }
Ejemplo n.º 33
0
 public ChangeFeedStartFromRequestOptionPopulator(RequestMessage requestMessage)
 {
     this.requestMessage = requestMessage ?? throw new ArgumentNullException(nameof(requestMessage));
 }
Ejemplo n.º 34
0
        public OperationReturn ConvertWaveFormat(string fileName)
        {
            OperationReturn optReturn = new OperationReturn();

            optReturn.Result = true;
            optReturn.Code   = 0;
            try
            {
                optReturn.Data = fileName;
                if (Session == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = RET_NO_SESSION;
                    optReturn.Message = string.Format("SessionInfo is null");
                    return(optReturn);
                }
                if (mRecordInfo == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = RET_NO_RECORDINFO;
                    optReturn.Message = string.Format("RecordInfo is null");
                    return(optReturn);
                }
                var            format = mRecordInfo.WaveFormat;
                RequestMessage request;
                ReturnMessage  retMessage;
                switch (format)
                {
                case VOICEFORMAT_G729_A:
                    request         = new RequestMessage();
                    request.Command = (int)Service03Command.ConvertWaveFormat;
                    request.ListData.Add(fileName);
                    request.ListData.Add("1");
                    optReturn = Service03Helper.DoRequest(request);
                    if (!optReturn.Result)
                    {
                        return(optReturn);
                    }
                    retMessage = optReturn.Data as ReturnMessage;
                    if (retMessage == null)
                    {
                        optReturn.Result  = false;
                        optReturn.Code    = Defines.RET_OBJECT_NULL;
                        optReturn.Message = string.Format("RetMessage is null");
                        return(optReturn);
                    }
                    if (!retMessage.Result)
                    {
                        optReturn.Result  = false;
                        optReturn.Code    = retMessage.Code;
                        optReturn.Message = retMessage.Message;
                        return(optReturn);
                    }
                    fileName       = retMessage.Data;
                    optReturn.Data = fileName;
                    OnDebug("ConvertFormat", string.Format("ConvertWaveFormat end.\t{0}", fileName));
                    break;
                }
            }
            catch (Exception ex)
            {
                optReturn.Result    = false;
                optReturn.Code      = Defines.RET_FAIL;
                optReturn.Message   = ex.Message;
                optReturn.Exception = ex;
            }
            return(optReturn);
        }
 /// <inheritdoc />
 /// <summary>
 /// Invalid Message Type Exception
 /// </summary>
 /// <param name="requestMessage">Request Message Object</param>
 /// <param name="expectedType">Expected Message Type</param>
 /// <param name="actualType">Actual Message Type</param>
 public InvalidMessageTypeException(RequestMessage requestMessage, Type expectedType, Type actualType) : base("Invalid Request Message Type Exception")
 {
     Data.Add(nameof(requestMessage), requestMessage?.TrySerializeToJson());
     Data.Add(nameof(expectedType), expectedType.SerializeToJson());
     Data.Add(nameof(actualType), actualType.SerializeToJson());
 }
Ejemplo n.º 36
0
 private T DeserializeObject <T>(RequestMessage requestMessage)
 {
     return(requestMessage.Body != null?
            JsonConvert.DeserializeObject <T>(requestMessage.Body) :
                ((JObject)requestMessage.BodyAsJson).ToObject <T>());
 }
Ejemplo n.º 37
0
        private double IsMatch(RequestMessage requestMessage)
        {
            // Check if the matcher is a IObjectMatcher
            if (Matcher is IObjectMatcher objectMatcher)
            {
                // If the body is a JSON object, try to match.
                if (requestMessage.BodyAsJson != null)
                {
                    return(objectMatcher.IsMatch(requestMessage.BodyAsJson));
                }

                // If the body is a byte array, try to match.
                if (requestMessage.BodyAsBytes != null)
                {
                    return(objectMatcher.IsMatch(requestMessage.BodyAsBytes));
                }
            }

            // Check if the matcher is a IStringMatcher
            if (Matcher is IStringMatcher stringMatcher)
            {
                // If the  body is a JSON object, try to use Body (string) to match.
                if (requestMessage.BodyAsJson != null && requestMessage.Body != null)
                {
                    return(stringMatcher.IsMatch(requestMessage.Body));
                }

                // If the string body is defined, try to match.
                if (requestMessage.Body != null)
                {
                    return(stringMatcher.IsMatch(requestMessage.Body));
                }

                // If the body is a byte array, attempt to convert it and match on that
                if (requestMessage.BodyAsBytes != null)
                {
                    try // to convert from the byte[] to a string
                    {
                        var input = Encoding.UTF8.GetString(requestMessage.BodyAsBytes);
                        return(stringMatcher.IsMatch(input));
                    }
                    catch
                    {
                        // just ignore the exception
                    }
                }
            }

            if (Func != null)
            {
                return(MatchScores.ToScore(requestMessage.Body != null && Func(requestMessage.Body)));
            }

            if (DataFunc != null)
            {
                return(MatchScores.ToScore(requestMessage.BodyAsBytes != null && DataFunc(requestMessage.BodyAsBytes)));
            }

            if (JsonFunc != null)
            {
                return(MatchScores.ToScore(requestMessage.BodyAsJson != null && JsonFunc(requestMessage.BodyAsJson)));
            }

            return(MatchScores.Mismatch);
        }
Ejemplo n.º 38
0
        public static ResponseMessage List()
        {
            RequestMessage request = MessagePrepareAgent.GetRequest(action, tranCode, null, null);

            return(new MessageBroker().Execute(request));
        }
Ejemplo n.º 39
0
 public override void ProcessRequest(RequestMessage requestMessage)
 {
 }
Ejemplo n.º 40
0
    protected void CyberSource_Customer_Profile_Fetch()
    {
        try
        {
            /// Include the following fields in the request:
            /// merchantID
            /// merchantReferenceCode
            /// recurringSubscriptionInfo_frequency —set to on-demand.
            /// paySubscriptionCreateService_paymentRequestID —include the requestID value returned from the original transaction request.
            ///
            /// See Appendix A, "API Fields," on page 34 for detailed descriptions of the request and
            /// reply fields. See Appendix B, "Examples," on page 62 for a request and reply example.

            RequestMessage request = new RequestMessage();

            request.paySubscriptionRetrieveService     = new PaySubscriptionRetrieveService();
            request.paySubscriptionRetrieveService.run = "true"; // Tokenization?

            request.merchantReferenceCode = merchantReferenceCode.Text;

            RecurringSubscriptionInfo SubscriptionInfo = new RecurringSubscriptionInfo();
            SubscriptionInfo.subscriptionID   = "4738680334246909704009";
            request.recurringSubscriptionInfo = SubscriptionInfo;


            ReplyMessage reply    = SoapClient.RunTransaction(request);
            string       template = ghCyberSource.GetTemplate(reply.decision.ToUpper());
            string       content  = "";
            try { content = ghCyberSource.GetContent(reply); }
            catch { content = "error"; }
            txtTemplate.Text = template.ToString();
            txtContent.Text  = content.ToString();
            txtReply.Text    = reply.ToString();
            lblCatch.Text   += String.Format("<br />decision: {0}", reply.decision.ToUpper());
            try { lblCatch.Text += String.Format("<br />reasonCode: {0}", reply.reasonCode); } catch { }
            try { lblCatch.Text += String.Format("<br />reasonCode: {0}", reply.paySubscriptionCreateReply.reasonCode); } catch { }
            try { lblCatch.Text += String.Format("<br />subscriptionID: {0}", reply.paySubscriptionCreateReply.subscriptionID); } catch { }
            try { lblCatch.Text += String.Format("<br />missingField: {0}", reply.missingField.Length); } catch { String.Format("<br />missingField: {0}", "x"); }
            lblCatch.Text += "<hr />";
            try { lblCatch.Text += String.Format("<br />missingField: {0}", reply.missingField.Length); } catch { String.Format("<br />missingField: {0}", "x"); }
        }
        catch (Exception ex)
        {
            lblCatch.Text += String.Format("<table class='table_error'>"
                                           + "<tr><td>Error<td/><td>{0}</td></tr>"
                                           + "<tr><td>Message<td/><td>{1}</td></tr>"
                                           + "<tr><td>StackTrace<td/><td>{2}</td></tr>"
                                           + "<tr><td>Source<td/><td>{3}</td></tr>"
                                           + "<tr><td>InnerException<td/><td>{4}</td></tr>"
                                           + "<tr><td>Data<td/><td>{5}</td></tr>"
                                           + "</table>"
                                           , "Tokenization"    //0
                                           , ex.Message        //1
                                           , ex.StackTrace     //2
                                           , ex.Source         //3
                                           , ex.InnerException //4
                                           , ex.Data           //5
                                           , ex.HelpLink
                                           , ex.TargetSite
                                           );
        }
    }
Ejemplo n.º 41
0
    protected void CyberSource_Customer_Profile_Create()
    {
        try
        {
            #region CyberSource Tokenization
            /// Here we create the Credit Card Tokenization - in CyberSource this is actually a Subscription ID
            /// We only do this for approved transactions
            /// Include the following fields in the request:
            /// merchantID
            /// merchantReferenceCode
            /// recurringSubscriptionInfo_frequency —set to on-demand.
            /// paySubscriptionCreateService_paymentRequestID —include the requestID value returned from the original transaction request.
            ///
            /// See Appendix A, "API Fields," on page 34 for detailed descriptions of the request and
            /// reply fields. See Appendix B, "Examples," on page 62 for a request and reply example.

            RequestMessage request = new RequestMessage();
            request.paySubscriptionCreateService     = new PaySubscriptionCreateService();
            request.paySubscriptionCreateService.run = "true"; // Tokenization?

            // request.merchantID = merchantID.Text; // This is not needed since it should automatically pull it from the confg [capture in DB anyways...]

            RecurringSubscriptionInfo SubscriptionInfo = new RecurringSubscriptionInfo();
            SubscriptionInfo.frequency        = "on-demand";
            request.recurringSubscriptionInfo = SubscriptionInfo;

            request.merchantReferenceCode = merchantReferenceCode.Text;
            int cbAge = 0;
            Int32.TryParse(age.Text, out cbAge);
            if (cbAge > 60)
            {
                request.paySubscriptionCreateService.paymentRequestID = paymentRequestID2.Text;
            }
            else
            {
                request.paySubscriptionCreateService.paymentRequestID = paymentRequestID.Text;
            }

            ReplyMessage reply    = SoapClient.RunTransaction(request);
            string       template = ghCyberSource.GetTemplate(reply.decision.ToUpper());
            string       content  = "";
            try { content = ghCyberSource.GetContent(reply); }
            catch { content = "error"; }
            txtTemplate.Text = template.ToString();
            txtContent.Text  = content.ToString();
            if (content.ToString() == "Approved")
            {
                txtContent.BackColor = System.Drawing.Color.Aqua;
            }
            else
            {
                txtContent.BackColor = System.Drawing.Color.Orange;
            }
            txtReply.Text  = reply.ToString();
            lblCatch.Text += String.Format("<br />decision: {0}", reply.decision.ToUpper());
            try { lblCatch.Text += String.Format("<br />reasonCode: {0}", reply.reasonCode); } catch { }
            try { lblCatch.Text += String.Format("<br />reasonCode: {0}", reply.paySubscriptionCreateReply.reasonCode); } catch { }
            try { lblCatch.Text += String.Format("<br />subscriptionID: {0}", reply.paySubscriptionCreateReply.subscriptionID); } catch { }
            try { lblCatch.Text += String.Format("<br />missingField: {0}", reply.missingField.Length); } catch { String.Format("<br />missingField: {0}", "x"); }

            String sp_subscriptionid = reply.paySubscriptionCreateReply.subscriptionID;
            String sp_decision       = reply.decision.ToUpper();
            Int32  sp_callid         = -1;
            Int32  sp_donationid     = -1;
            Int32  sp_authid         = -1;
            Int32  sp_authorid       = -1;
            Int32  sp_reasoncode     = -1;
            Int32  sp_status         = -1;
            Int32  sp_actionid       = -1;

            Int32.TryParse(callid.Text, out sp_callid);
            Int32.TryParse(donationid.Text, out sp_donationid);
            Int32.TryParse(authid.Text, out sp_authid);
            Int32.TryParse(authorid.Text, out sp_authorid);
            Int32.TryParse(reply.paySubscriptionCreateReply.reasonCode, out sp_reasoncode);

            sp_actionid = 10330001; // Tokenization - Actions | Create New Token
            if (sp_decision == "ACCEPT")
            {
                sp_status = 10340001; // Tokenization - Status | Success
            }
            else if (sp_decision == "REJECT")
            {
                sp_status = 10340002; // Tokenization - Status | Failure
            }
            else
            {
                sp_status = 10340003; // Tokenization - Status | Error
            }

            #endregion CyberSource Tokenization

            #region CyberSource Tokenization - Log

            lblTokenization.Text = "Testing...";
            Int32 sp_tokenid = CyberSource_Customer_Profile_Insert(sp_subscriptionid, sp_callid, sp_donationid, sp_authid, sp_status);
            // Need to log it regardless
            // Log has the decision and reasoncode
            if (sp_tokenid != -1)
            {
                lblTokenization.Text = "Testing...";
                CyberSource_Customer_Profile_Insert_Log(sp_tokenid, sp_authorid, sp_actionid, sp_status, sp_decision, sp_reasoncode);
            }

            #endregion CyberSource Tokenization - Log
        }
        catch (Exception ex)
        {
            lblCatch.Text += String.Format("<table class='table_error'>"
                                           + "<tr><td>Error<td/><td>{0}</td></tr>"
                                           + "<tr><td>Message<td/><td>{1}</td></tr>"
                                           + "<tr><td>StackTrace<td/><td>{2}</td></tr>"
                                           + "<tr><td>Source<td/><td>{3}</td></tr>"
                                           + "<tr><td>InnerException<td/><td>{4}</td></tr>"
                                           + "<tr><td>Data<td/><td>{5}</td></tr>"
                                           + "</table>"
                                           , "Tokenization"    //0
                                           , ex.Message        //1
                                           , ex.StackTrace     //2
                                           , ex.Source         //3
                                           , ex.InnerException //4
                                           , ex.Data           //5
                                           , ex.HelpLink
                                           , ex.TargetSite
                                           );
        }
    }
Ejemplo n.º 42
0
        private Message HandleMessage(Peer peer, Message msg)
        {
            if (msg.IsSigned && !msg.Address.IsNull)
            {
                if (msg.Address.IsUser)
                {
                    peer.SetAddress(msg.Address);
                }
                else
                {
                    return(new ErrorMessage(Address, this.PublicEndpoint, P2PError.InvalidAddress));
                }
            }
            else
            {
                return(new ErrorMessage(Address, this.PublicEndpoint, P2PError.MessageShouldBeSigned));
            }

            Endpoint endpoint;

            try
            {
                endpoint = Endpoint.FromString(msg.Host);
            }
            catch (ChainException e)
            {
                return(new ErrorMessage(Address, this.PublicEndpoint, P2PError.InvalidEndpoint));
            }

            var peerKey = endpoint.ToString();

            lock (_peers)
            {
                if (!_peers.ContainsKey(peerKey))
                {
                    Logger.Message("Added peer: " + peerKey);
                    peer.UpdateEndpoint(endpoint);
                    _peers[peerKey] = peer;
                }
            }

            Logger.Debug($"Got {msg.Opcode} message from {peerKey}");

            switch (msg.Opcode)
            {
            case Opcode.EVENT:
            {
                var evtMessage = (EventMessage)msg;
                var evt        = evtMessage.Event;
                Logger.Message("New event: " + evt.ToString());
                return(null);
            }

            case Opcode.REQUEST:
            {
                var request = (RequestMessage)msg;

                if (request.NexusName != Nexus.Name)
                {
                    return(new ErrorMessage(Address, this.PublicEndpoint, P2PError.InvalidNexus));
                }

                if (request.Kind == RequestKind.None)
                {
                    return(null);
                }

                var answer = new ListMessage(this.Address, this.PublicEndpoint, request.Kind);

                if (request.Kind.HasFlag(RequestKind.Peers))
                {
                    answer.SetPeers(this.Peers.Where(x => x != peer).Select(x => x.Endpoint.ToString()));
                }

                if (request.Kind.HasFlag(RequestKind.Chains))
                {
                    var chainList = Nexus.GetChains(Nexus.RootStorage);
                    var chains    = chainList.Select(x => Nexus.GetChainByName(x)).Select(x => new ChainInfo(x.Name, Nexus.GetParentChainByName(x.Name), x.Height)).ToArray();
                    answer.SetChains(chains);
                }

                if (request.Kind.HasFlag(RequestKind.Mempool) && Capabilities.HasFlag(PeerCaps.Mempool))
                {
                    var txs = _mempool.GetTransactions().Select(x => Base16.Encode(x.ToByteArray(true)));
                    answer.SetMempool(txs);
                }

                if (request.Kind.HasFlag(RequestKind.Blocks))
                {
                    foreach (var entry in request.Blocks)
                    {
                        var chain = this.Nexus.GetChainByName(entry.Key);
                        if (chain == null)
                        {
                            continue;
                        }

                        answer.AddBlockRange(chain, entry.Value);
                    }
                }

                return(answer);
            }

            case Opcode.LIST:
            {
                var listMsg = (ListMessage)msg;

                var outKind = RequestKind.None;

                if (listMsg.Kind.HasFlag(RequestKind.Peers))
                {
                    IEnumerable <string> newPeers;

                    lock (_peers)
                    {
                        newPeers = listMsg.Peers.Where(x => !_peers.ContainsKey(x));
                    }

                    foreach (var entry in newPeers)
                    {
                        Logger.Message("New peer: " + entry);
                    }
                    QueueEndpoints(newPeers);
                }

                var blockFetches = new Dictionary <string, RequestRange>();
                if (listMsg.Kind.HasFlag(RequestKind.Chains))
                {
                    foreach (var entry in listMsg.Chains)
                    {
                        var chain = Nexus.GetChainByName(entry.name);
                        // NOTE if we dont find this chain then it is too soon for ask for blocks from that chain
                        if (chain != null)
                        {
                            if (chain.Height < entry.height)
                            {
                                var start = chain.Height + 1;
                                var end   = entry.height;
                                var limit = start + ListMessage.MaxBlocks - 1;

                                if (end > limit)
                                {
                                    end = limit;
                                }

                                blockFetches[entry.name] = new RequestRange(start, end);

                                lock (_knownHeights)
                                {
                                    BigInteger lastKnowHeight = _knownHeights.ContainsKey(chain.Name) ? _knownHeights[chain.Name] : 0;
                                    if (entry.height > lastKnowHeight)
                                    {
                                        _knownHeights[chain.Name] = entry.height;
                                        IsFullySynced             = false;
                                    }
                                }
                            }

                            if (chain.Height == entry.height)
                            {
                                IsFullySynced = true;
                            }
                        }
                    }
                }

                if (listMsg.Kind.HasFlag(RequestKind.Mempool) && Capabilities.HasFlag(PeerCaps.Mempool))
                {
                    int submittedCount = 0;
                    foreach (var txStr in listMsg.Mempool)
                    {
                        var bytes = Base16.Decode(txStr);
                        var tx    = Transaction.Unserialize(bytes);
                        try
                        {
                            _mempool.Submit(tx);
                            submittedCount++;
                        }
                        catch
                        {
                        }

                        Logger.Message(submittedCount + " new transactions");
                    }
                }

                if (listMsg.Kind.HasFlag(RequestKind.Blocks))
                {
                    Chain chain = null;
                    foreach (var entry in listMsg.Blocks)
                    {
                        chain = Nexus.GetChainByName(entry.Key);
                        if (chain == null)
                        {
                            continue;
                        }

                        var blockRange = entry.Value;
                        foreach (var block in blockRange.blocks)
                        {
                            var transactions = new List <Transaction>();
                            foreach (var txHash in block.TransactionHashes)
                            {
                                var tx = entry.Value.transactions[txHash];
                                transactions.Add(tx);
                            }

                            var maxPendingHeightExpected = chain.Height + ListMessage.MaxBlocks;

                            if (block.Height > chain.Height && block.Height <= maxPendingHeightExpected)
                            {
                                var key = $"{chain.Name}.{block.Height}";
                                lock (_pendingBlocks)
                                {
                                    _pendingBlocks[key] = new PendingBlock(chain.Name, block, transactions);
                                }
                            }
                        }

                        _lastRequestTime = DateTime.UtcNow;
                        //Thread.Sleep(10000);
                    }
                }

                if (blockFetches.Count > 0)
                {
                    outKind |= RequestKind.Blocks;
                }

                if (outKind != RequestKind.None)
                {
                    var answer = new RequestMessage(this.Address, this.PublicEndpoint, outKind, Nexus.Name);

                    if (blockFetches.Count > 0)
                    {
                        answer.SetBlocks(blockFetches);
                    }

                    return(answer);
                }

                return(null);
            }

            case Opcode.MEMPOOL_Add:
            {
                if (Capabilities.HasFlag(PeerCaps.Mempool))
                {
                    var memtx           = (MempoolAddMessage)msg;
                    int submissionCount = 0;
                    foreach (var tx in memtx.Transactions)
                    {
                        try
                        {
                            if (_mempool.Submit(tx))
                            {
                                submissionCount++;
                            }
                        }
                        catch
                        {
                            // ignore
                        }
                    }

                    Logger.Message($"Added {submissionCount} txs to the mempool");
                }

                return(null);
            }

            case Opcode.BLOCKS_List:
            {
                break;
            }

            case Opcode.ERROR:
            {
                var errorMsg = (ErrorMessage)msg;
                if (string.IsNullOrEmpty(errorMsg.Text))
                {
                    Logger.Error($"ERROR: {errorMsg.Code}");
                }
                else
                {
                    Logger.Error($"ERROR: {errorMsg.Code} ({errorMsg.Text})");
                }

                return(null);
            }
            }

            throw new NodeException("No answer sent to request " + msg.Opcode);
        }
Ejemplo n.º 43
0
        void Process(IChannelHandlerContext ctx, IFullHttpRequest request)
        {
            string uri = request.Uri;
            int    i   = 0;

            byte[] destination = new byte[request.Content.Capacity];
            while (i < request.Content.Capacity)
            {
                destination[i] = request.Content.ReadByte();
                i++;
            }
            var requestMessage = new RequestMessage();

            requestMessage.Method = request.Method.ToString();
            requestMessage.Uri    = uri;
            foreach (var header in request.Headers)
            {
                string key = header.Key.ToString().ToLower();
                if (!requestMessage.Headers.TryGetValue(key, out List <string> values))
                {
                    values = new List <string>();
                }
                values.Add(header.Value.ToString());
                requestMessage.Headers[key] = values;
            }
            string mytraceid = Guid.NewGuid().ToString("N").ToLower();

            requestMessage.Headers["mytraceid"] = new List <string>()
            {
                mytraceid
            };
            requestMessage.Content = destination;
            ProxyServerHandler.group.WriteAndFlushAsync(JsonConvert.SerializeObject(requestMessage) + "\r\n");
            ProxyServerHandler.group.Flush();
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            ResponseMessage responseMessage = null;

            while (!ProxyServerHandler.dictResponse.TryRemove(mytraceid, out responseMessage) && stopwatch.ElapsedMilliseconds < 100 * 1000)
            {
                System.Threading.Thread.Sleep(5);
            }
            if (stopwatch.ElapsedMilliseconds < 100 * 1000)
            {
                IByteBuffer buf      = Unpooled.WrappedBuffer(responseMessage.Content);
                var         statue   = new HttpResponseStatus(responseMessage.StatusCode, new AsciiString(responseMessage.ReasonPhrase));
                var         response = new DefaultFullHttpResponse(HttpVersion.Http11
                                                                   , statue, buf, false);
                HttpHeaders headers = response.Headers;
                foreach (var header in responseMessage.Headers)
                {
                    headers.Set(new AsciiString(header.Key), header.Value.ToArray());
                }
                ctx.WriteAndFlushAsync(response);
                ctx.CloseAsync();
            }
            else
            {
                var response = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.NotFound, Unpooled.Empty, false);
                ctx.WriteAndFlushAsync(response);
                ctx.CloseAsync();
            }
        }
Ejemplo n.º 44
0
        public OperationReturn DecryptRecord(string fileName, string password)
        {
            OperationReturn optReturn = new OperationReturn();

            optReturn.Result = true;
            optReturn.Code   = 0;
            try
            {
                optReturn.Data = fileName;
                if (Session == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = RET_NO_SESSION;
                    optReturn.Message = string.Format("SessionInfo is null");
                    return(optReturn);
                }
                if (mRecordInfo == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = RET_NO_RECORDINFO;
                    optReturn.Message = string.Format("RecordInfo is null");
                    return(optReturn);
                }
                var encryptFlag = mRecordInfo.EncryptFlag;
                if (encryptFlag == "0")
                {
                    return(optReturn);
                }                                                 //未加密的无需解密操作
                if (encryptFlag != "2")
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("EncryptFlag invalid.\t{0}", encryptFlag);
                    return(optReturn);
                }
                if (Service03Helper == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("Service03Helper is null");
                    return(optReturn);
                }
                if (string.IsNullOrEmpty(password))
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_STRING_EMPTY;
                    optReturn.Message = string.Format("RealPassword is empty");
                    return(optReturn);
                }
                RequestMessage request;
                ReturnMessage  retMessage;
                request         = new RequestMessage();
                request.Command = (int)Service03Command.DecryptRecordFile;
                request.ListData.Add(fileName);
                request.ListData.Add(password);
                optReturn = Service03Helper.DoRequest(request);
                if (!optReturn.Result)
                {
                    return(optReturn);
                }
                retMessage = optReturn.Data as ReturnMessage;
                if (retMessage == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("RetMessage is null");
                    return(optReturn);
                }
                if (!retMessage.Result)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = retMessage.Code;
                    optReturn.Message = retMessage.Message;
                    return(optReturn);
                }
                fileName       = retMessage.Data;
                optReturn.Data = fileName;
                OnDebug("DecryptRecord", string.Format("DecryptRecord end.\t{0}", fileName));
            }
            catch (Exception ex)
            {
                optReturn.Result    = false;
                optReturn.Code      = Defines.RET_FAIL;
                optReturn.Message   = ex.Message;
                optReturn.Exception = ex;
            }
            return(optReturn);
        }
Ejemplo n.º 45
0
        public OperationReturn OriginalDecryptRecord(string fileName)
        {
            OperationReturn optReturn = new OperationReturn();

            optReturn.Result = true;
            optReturn.Code   = 0;
            try
            {
                optReturn.Data = fileName;
                if (Session == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = RET_NO_SESSION;
                    optReturn.Message = string.Format("SessionInfo is null");
                    return(optReturn);
                }
                if (mRecordInfo == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = RET_NO_RECORDINFO;
                    optReturn.Message = string.Format("RecordInfo is null");
                    return(optReturn);
                }
                var encryptFlag = mRecordInfo.EncryptFlag;
                if (encryptFlag != "0")
                {
                    //加密标识不为“0” 的无需做原始解密
                    return(optReturn);
                }
                var mediaType = mRecordInfo.MediaType;
                if (mediaType == 2)
                {
                    //录屏文件无需做原始解密
                    return(optReturn);
                }
                if (Service03Helper == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("Service03Helper is null");
                    return(optReturn);
                }
                RequestMessage request;
                ReturnMessage  retMessage;
                request         = new RequestMessage();
                request.Command = (int)Service03Command.OriginalDecryptFile;
                request.ListData.Add(fileName);
                optReturn = Service03Helper.DoRequest(request);
                if (!optReturn.Result)
                {
                    return(optReturn);
                }
                retMessage = optReturn.Data as ReturnMessage;
                if (retMessage == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("RetMessage is null");
                    return(optReturn);
                }
                if (!retMessage.Result)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = retMessage.Code;
                    optReturn.Message = retMessage.Message;
                    return(optReturn);
                }
                fileName       = retMessage.Data;
                optReturn.Data = fileName;
                OnDebug("OrignalDecrypt", string.Format("OrignalDecrypt end.\t{0}", fileName));
            }
            catch (Exception ex)
            {
                optReturn.Result    = false;
                optReturn.Code      = Defines.RET_FAIL;
                optReturn.Message   = ex.Message;
                optReturn.Exception = ex;
            }
            return(optReturn);
        }
Ejemplo n.º 46
0
 private double IsMatch(RequestMessage requestMessage)
 {
     return(MatchScores.ToScore(Methods.Contains(requestMessage.Method, StringComparer.OrdinalIgnoreCase)));
 }
Ejemplo n.º 47
0
        /// <see cref="IRequestMatcher.GetMatchingScore"/>
        public double GetMatchingScore(RequestMessage requestMessage, RequestMatchResult requestMatchResult)
        {
            double score = IsMatch(requestMessage);

            return(requestMatchResult.AddScore(GetType(), score));
        }
        public async Task <RequestMessage> Register(string mail, string passwod)
        {
            var requestMessage = new RequestMessage()
            {
                IsSuccess = true
            };
            var user = await _collectionDBCotext.Users
                       .Where(t => t.Mail == mail)
                       .Select(t => new { t.Id, t.Passwod })
                       .FirstOrDefaultAsync();

            if (user == null || user.Passwod != passwod)//注册 或 修改密码
            {
                requestMessage.IsSuccess = false;

                RedisHelper reids  = new RedisHelper(3);
                var         key    = mail;
                var         number = await reids.GetStringIncrAsync(key);

                if (number >= 3)
                {
                    requestMessage.Message = "请勿频繁注册,请查看垃圾邮件或换一个邮箱注册!";
                    return(requestMessage);
                }
                //30分钟内有效(标记邮件激活30分钟内有效)
                await reids.SetStringIncrAsync(key, TimeSpan.FromMinutes(30));

                if (user == null)
                {
                    requestMessage.Message = "第一次登录,验证链接已发邮箱。";
                }
                else
                {
                    requestMessage.Message = "您的密码有变更,验证链接已发邮箱。";
                }

                var data = JsonConvert.SerializeObject(new User()
                {
                    Mail = mail, Passwod = passwod
                });
                var         DESString = HttpUtility.UrlEncode(EncryptDecryptExtension.DES3Encrypt(data, DESKey));
                EmailHelper email     = new EmailHelper();
                email.MailToArray = new string[] { mail };
                var checkUrl = Request.Scheme + "://" + Request.Host.Value + "/Home/CheckLogin?desstring=" + DESString;
                email.MailSubject = "欢迎您注册 爱收藏";
                email.MailBody    = EmailHelper.TempBody(mail, "请复制打开链接(或者右键'在新标签页中打开'),完成验证。", "<a style='word-wrap: break-word;word-break: break-all;' href='" + checkUrl + "'>" + checkUrl + "</a>");
                email.Send(t =>
                {
                    //string aa = "成功";
                }, t =>
                {
                    //string aa = "失败";
                });
            }
            else
            {
                SaveCookie(new Core.Entities.User()
                {
                    Id = user.Id, Mail = mail
                });
            }
            return(requestMessage);
        }
Ejemplo n.º 49
0
 /// <summary>
 /// Initializes a new instance of the <see cref="KeyboardInteractiveAuthenticationMethod"/> class.
 /// </summary>
 /// <param name="username">The username.</param>
 /// <exception cref="ArgumentException"><paramref name="username"/> is whitespace or <c>null</c>.</exception>
 public KeyboardInteractiveAuthenticationMethod(string username)
     : base(username)
 {
     _requestMessage = new RequestMessageKeyboardInteractive(ServiceName.Connection, username);
 }
Ejemplo n.º 50
0
 ResponseMessage HandleIncomingRequest(RequestMessage request)
 {
     return(invoker.Invoke(request));
 }
Ejemplo n.º 51
0
        /// <inheritdoc cref="IRequestMatcher.GetMatchingScore"/>
        public double GetMatchingScore(RequestMessage requestMessage, RequestMatchResult requestMatchResult)
        {
            double score = MatchBehaviourHelper.Convert(_matchBehaviour, IsMatch(requestMessage));

            return(requestMatchResult.AddScore(GetType(), score));
        }
        internal static ResponseMessage AggregateExceptionConverter(AggregateException aggregateException, RequestMessage request)
        {
            AggregateException innerExceptions = aggregateException.Flatten();
            DocumentClientException docClientException = (DocumentClientException)innerExceptions.InnerExceptions.FirstOrDefault(innerEx => innerEx is DocumentClientException);
            if (docClientException != null)
            {
                return docClientException.ToCosmosResponseMessage(request);
            }

            Exception exception = innerExceptions.InnerExceptions.FirstOrDefault(innerEx => innerEx is CosmosException);
            if (exception is CosmosException cosmosException)
            {
                return cosmosException.ToCosmosResponseMessage(request);
            }

            return null;
        }
        private ResponseMessage ScenariosReset(RequestMessage requestMessage)
        {
            ResetScenarios();

            return(ResponseMessageBuilder.Create("Scenarios reset"));
        }
        private ResponseMessage RequestsDelete(RequestMessage requestMessage)
        {
            ResetLogEntries();

            return(ResponseMessageBuilder.Create("Requests deleted"));
        }
Ejemplo n.º 55
0
        /// <inheritdoc />
        public virtual byte[] SerializeMessage(RequestMessage requestMessage)
        {
            var graphSONMessage = _graphSONWriter.WriteObject(requestMessage);

            return(Encoding.UTF8.GetBytes(MessageWithHeader(graphSONMessage)));
        }
Ejemplo n.º 56
0
        public OperationReturn DownloadFileToAppServer()
        {
            OperationReturn optReturn = new OperationReturn();

            optReturn.Result = true;
            optReturn.Code   = 0;
            try
            {
                if (Session == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = RET_NO_SESSION;
                    optReturn.Message = string.Format("SessionInfo is null");
                    return(optReturn);
                }
                if (mRecordInfo == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = RET_NO_RECORDINFO;
                    optReturn.Message = string.Format("RecordInfo is null");
                    return(optReturn);
                }
                string strServerAddress = mRecordInfo.VoiceIP;


                #region 获取下载服务器列表

                List <DownloadServerItem> listServerItems = new List <DownloadServerItem>();
                if (ListDownloadParams != null)
                {
                    var downloadParams = ListDownloadParams.Where(d => d.VoiceAddress == strServerAddress || d.VoiceAddress == string.Empty).OrderBy(d => d.ID).ToList();
                    for (int i = 0; i < downloadParams.Count; i++)
                    {
                        var downloadParam = downloadParams[i];
                        if (!downloadParam.IsEnabled)
                        {
                            continue;
                        }
                        var item = new DownloadServerItem();
                        item.Type = 1;
                        item.Info = downloadParam;
                        listServerItems.Add(item);
                    }
                }
                if (ListSftpServers != null)
                {
                    var sftps =
                        ListSftpServers.Where(s => s.HostAddress == strServerAddress).OrderBy(s => s.ObjID).ToList();
                    for (int i = 0; i < sftps.Count; i++)
                    {
                        var sftp = sftps[i];
                        var item = new DownloadServerItem();
                        item.Type = 0;
                        item.Info = sftp;
                        listServerItems.Add(item);
                    }
                }
                if (listServerItems.Count <= 0)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = RET_DOWNLOADSERVER_NOT_EXIST;
                    optReturn.Message = string.Format("Download server not exist.\t{0}", strServerAddress);
                    return(optReturn);
                }
                if (Service03Helper == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("Service03Helper is null");
                    return(optReturn);
                }

                #endregion


                #region  载文件

                RequestMessage request;
                ReturnMessage  retMessage;
                bool           isDownloaded = false;

                //遍历可用的下载服务器尝试下载文件
                for (int i = 0; i < listServerItems.Count; i++)
                {
                    var item = listServerItems[i];
                    var type = item.Type;
                    request = new RequestMessage();
                    if (type == 0)
                    {
                        //Sftp方式
                        var sftpServer = item.Info as SftpServerInfo;
                        if (sftpServer == null)
                        {
                            continue;
                        }
                        string             strPartInfo = string.Empty;
                        PartitionTableInfo partInfo    =
                            Session.ListPartitionTables.FirstOrDefault(
                                p =>
                                p.TableName == ConstValue.TABLE_NAME_RECORD && p.PartType == TablePartType.DatetimeRange);
                        if (partInfo != null)
                        {
                            DateTime startTime = mRecordInfo.StartRecordTime;
                            strPartInfo = string.Format("{0}{1}", startTime.ToString("yy"), startTime.ToString("MM"));
                        }
                        OnDebug("DownloadAppServer",
                                string.Format("Downloading by sftp.\t{0}:{1}\t{2}", sftpServer.HostAddress,
                                              sftpServer.HostPort, mRecordInfo.SerialID));
                        request.Command = (int)Service03Command.DownloadRecordFile;
                        request.ListData.Add(sftpServer.HostAddress);
                        request.ListData.Add(sftpServer.HostPort.ToString());
                        request.ListData.Add(string.Format("{0}|{1}", Session.UserID, Session.RentInfo.Token));
                        request.ListData.Add(Session.UserInfo.Password);
                        request.ListData.Add(mRecordInfo.RowID.ToString());
                        request.ListData.Add(mRecordInfo.SerialID.ToString());
                        request.ListData.Add(strPartInfo);
                        //MediaType为0,认为是.wav文件
                        int mediaType = mRecordInfo.MediaType;
                        if (mediaType == 0)
                        {
                            mediaType = 1;
                        }
                        request.ListData.Add(mediaType.ToString());
                    }
                    else if (type == 1)
                    {
                        //NAS方式
                        var downloadParam = item.Info as DownloadParamInfo;
                        if (downloadParam == null)
                        {
                            continue;
                        }
                        optReturn = GetRecordPath(downloadParam);
                        if (!optReturn.Result)
                        {
                            return(optReturn);
                        }
                        string path = optReturn.Data.ToString();
                        if (string.IsNullOrEmpty(path))
                        {
                            OnDebug("DownloadAppServer", string.Format("Record path is empty"));
                            continue;
                        }
                        if (!string.IsNullOrEmpty(downloadParam.RootDir))
                        {
                            path = string.Format("/{0}{1}", downloadParam.RootDir, path);
                        }
                        path = string.Format("{0}{1}.{2}", path, mRecordInfo.RecordReference,
                                             mRecordInfo.MediaType == 2 ? "vls" : "wav");
                        OnDebug("DownloadAppServer",
                                string.Format("Downloading by nas.\t{0}:{1}\t{2}\t{3}", downloadParam.Address,
                                              downloadParam.Port, path, mRecordInfo.SerialID));
                        string serialID = mRecordInfo.SerialID.ToString();
                        request.Command = (int)Service03Command.DownloadRecordFileNas;
                        request.ListData.Add(downloadParam.Address);
                        request.ListData.Add(downloadParam.Port.ToString());
                        request.ListData.Add(downloadParam.UserName);
                        request.ListData.Add(downloadParam.Password);
                        request.ListData.Add(path);
                        request.ListData.Add(serialID);
                        int mediaType = mRecordInfo.MediaType;
                        if (mediaType == 2)
                        {
                            mediaType = 2;
                        }
                        else
                        {
                            mediaType = 1;
                        }
                        request.ListData.Add(mediaType.ToString());
                    }
                    else
                    {
                        OnDebug("DownloadAppServer",
                                string.Format("Method invalid.\t{0}", type));
                        continue;
                    }
                    optReturn = Service03Helper.DoRequest(request);
                    if (!optReturn.Result)
                    {
                        OnDebug("DownloadAppServer",
                                string.Format("Download by {0} fail.\t{1}\t{2}", type, optReturn.Code,
                                              optReturn.Message));
                        continue;
                    }
                    retMessage = optReturn.Data as ReturnMessage;
                    if (retMessage == null)
                    {
                        OnDebug("DownloadAppServer", string.Format("RetMessage is null"));
                        continue;
                    }
                    if (!retMessage.Result)
                    {
                        OnDebug("DownloadAppServer",
                                string.Format("Fail.\t{0}\t{1}", retMessage.Code, retMessage.Message));
                        continue;
                    }
                    OnDebug("DownloadAppServer", string.Format("Download by {0} end.\t{1}", type, mRecordInfo.SerialID));
                    isDownloaded   = true;
                    optReturn.Data = retMessage.Data;
                    break;
                }
                if (!isDownloaded)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = RET_DOWNLOAD_APPSERVER_FAIL;
                    optReturn.Message =
                        string.Format("Download file to AppServer fail. Reference log for detail information");
                    return(optReturn);
                }

                #endregion
            }
            catch (Exception ex)
            {
                optReturn.Result    = false;
                optReturn.Code      = Defines.RET_FAIL;
                optReturn.Message   = ex.Message;
                optReturn.Exception = ex;
            }
            return(optReturn);
        }
Ejemplo n.º 57
0
 /// <summary>Sends a request message synchronously and returns a response message as a string.</summary>
 /// <remarks>Sends a request message synchronously and returns a response message as a string.</remarks>
 /// <param name="credentialsProvider">object to obtain Credentials from</param>
 /// <param name="requestMessage">the message to be sent</param>
 /// <returns>the response message as a string</returns>
 public virtual string SendRequestAndGetResponse(CredentialsProvider credentialsProvider, RequestMessage requestMessage)
 {
     try
     {
         return(PostMessage(credentialsProvider, requestMessage));
     }
     catch (IOException e)
     {
         throw new TransportLayerException(e);
     }
 }
Ejemplo n.º 58
0
        ResponseMessage SendOutgoingPollingRequest(RequestMessage request)
        {
            var queue = GetQueue(request.Destination.BaseUri);

            return(queue.QueueAndWait(request));
        }
        private void ProcessInsertMessage(RequestMessage message, Queue <RequestMessage> messageQueue, ConnectionId connectionId, InsertMessageBinaryEncoder <RawBsonDocument> encoder, Stopwatch stopwatch)
        {
            var          commandName          = "insert";
            var          operationId          = EventContext.OperationId;
            var          requestId            = message.RequestId;
            var          expectedResponseType = ExpectedResponseType.None;
            int          numberOfDocuments    = 0;
            int          gleRequestId;
            WriteConcern writeConcern;

            if (TryGetWriteConcernFromGLE(messageQueue, out gleRequestId, out writeConcern))
            {
                requestId            = gleRequestId;
                expectedResponseType = ExpectedResponseType.GLE;
            }

            if (_startedEvent != null)
            {
                // InsertMessage is generic, and we don't know the generic type...
                // Plus, for this we really want BsonDocuments, not whatever the generic type is.
                var decodedMessage = encoder.ReadMessage();

                var documents = decodedMessage.DocumentSource.GetRemainingItems().ToList();
                numberOfDocuments = documents.Count;
                try
                {
                    var command = new BsonDocument
                    {
                        { commandName, decodedMessage.CollectionNamespace.CollectionName },
                        { "documents", new BsonArray(documents) },
                        { "ordered", !decodedMessage.ContinueOnError }
                    };

                    if (writeConcern == null)
                    {
                        command["writeConcern"] = WriteConcern.Unacknowledged.ToBsonDocument();
                    }
                    else if (!writeConcern.IsServerDefault)
                    {
                        command["writeConcern"] = writeConcern.ToBsonDocument();
                    }

                    var @event = new CommandStartedEvent(
                        commandName,
                        command,
                        decodedMessage.CollectionNamespace.DatabaseNamespace,
                        operationId,
                        requestId,
                        connectionId);

                    _startedEvent(@event);
                }
                finally
                {
                    documents.ForEach(d => d.Dispose());
                }
            }

            if (_shouldTrackState)
            {
                _state.TryAdd(requestId, new CommandState
                {
                    CommandName               = commandName,
                    OperationId               = operationId,
                    Stopwatch                 = stopwatch,
                    ExpectedResponseType      = expectedResponseType,
                    NumberOfInsertedDocuments = numberOfDocuments
                });
            }
        }
        private ResponseMessage MappingsSave(RequestMessage requestMessage)
        {
            SaveStaticMappings();

            return(ResponseMessageBuilder.Create("Mappings saved to disk"));
        }