コード例 #1
0
        public async Task <byte[]> ProcessRequestAsync(byte[] rawRequest, string clientInformation)
        {
            byte[]    response;
            CommandId commandId = CommandId.Zero;

            try
            {
                if (rawRequest == null)
                {
                    throw new ArgumentNullException(nameof(rawRequest));
                }
                if (rawRequest.Length == 0)
                {
                    throw new ArgumentException(@"Length must not be zero.", nameof(rawRequest));
                }

                var tlsEnvelope = new NOTLSEnvelope(rawRequest);
                var request     = this.ratchet.DecryptRequest(tlsEnvelope);

                Command command = request.ParseCommand();
                commandId = command.CommandId;
                response  = await this.commandProcessor.ExecuteAuthenticatedRequestAsync(command);
            }
            catch (Exception e)
            {
                // Always return a properly formatted response, never null, otherwise the client will simply hang.
                var error = $"{clientInformation}: Command {commandId} threw an Exception: {e.Message}";
                this.logger.LogError(error, nameof(NoTLSRequestHandler));
                response = new RequestCommand(CommandId.ServerException, error).Serialize(CommandHeader.Yes);
            }

            byte[] reply = this.ratchet.EncryptRequest(response).Serialize();
            this.logger.LogInformation($"{clientInformation}: {commandId}, I/O {rawRequest?.Length}/{reply.Length} bytes.");
            return(reply);
        }
        protected override async Task <ResponseCommand <T2> > Execute(RequestCommand <T, T2> context, Func <RequestCommand <T, T2>, Task <ResponseCommand <T2> > > next)
        {
            Request = context.RestRequest;
            var profile = context.Profile;

            Polly.AsyncPolicy <IRestResponse <T2> > policy = Policy.NoOpAsync <IRestResponse <T2> >();

            if (context.Authenticate)
            {
                policy = context.CustomPolicy ?? Policy.NoOpAsync <IRestResponse <T2> >();

                Polly.AsyncPolicy <IRestResponse <T2> > mainPolicy = Policy
                                                                     .HandleResult <IRestResponse <T2> >(resp => resp.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                                                                     .RetryAsync(
                    retryCount: 1,
                    onRetryAsync: async(result, retryNumber, ctx) => await GetAuthorizationTokenAsync(profile, true)
                    );

                policy = mainPolicy.WrapAsync(policy);


                await GetAuthorizationTokenAsync(profile);
            }

            var response = await policy.ExecuteAsync(async() => await RestClient.ExecuteAsync <T2>(context.RestRequest));

            var responseCommand = new ResponseCommand <T2>
            {
                Response = response
            };

            return(responseCommand);
        }
コード例 #3
0
        public async Task <ResponseMessage> PushMessage(RequestCommand requestCommand)
        {
            var formattedValue = _formatter.Format(new InValue()
            {
                ProfileId        = requestCommand.ProfileId,
                Message          = requestCommand.Message,
                Hyperlink        = requestCommand.Hyperlink,
                Read             = requestCommand.Read,
                NotificationType = requestCommand.NotificationType,
                Parameters       = requestCommand.Parameters,
                User             = requestCommand.UserName,
            });

            if (requestCommand.NotificationType.ToLower().Contains("pub"))
            {
                await _notificationSender.Send("PublicNotificationPush", formattedValue.FormattedValue);
            }
            else
            {
                await _notificationSender.Send("PrivateNotificationPush", formattedValue.FormattedValue, requestCommand.UserName);
            }

            var recordBuilt = BuildRecord(requestCommand);

            await _repository.Insert(recordBuilt);

            return(BuildResponseMessage(recordBuilt));
        }
コード例 #4
0
ファイル: ChatClient.cs プロジェクト: xds-playgrounds/xds-sdk
        public async Task <Response <IReadOnlyCollection <XMessage> > > DownloadMessages(string myId)
        {
            var response = new Response <IReadOnlyCollection <XMessage> >();

            try
            {
                var requestCommand = new RequestCommand(CommandId.DownloadMessages, myId).Serialize(CommandHeader.Yes);
                var tlsResponse    = await this.networkClient.SendRequestAsync(requestCommand, Transport.TCP);

                List <XMessage> downloadedMessages = new List <XMessage>();
                foreach (var authenticableRequest in tlsResponse)
                {
                    downloadedMessages.AddRange(authenticableRequest.CommandData.DeserializeCollection(XMessageExtensions.DeserializeMessage));
                }

                this.logger.LogDebug($"Successfully downloaded and deserialized {downloadedMessages.Count} XMessage items.");
                response.Result = downloadedMessages;
                response.SetSuccess();
            }
            catch (Exception e)
            {
                this.logger.LogError(e.Message);
                response.SetError(e);
            }
            return(response);
        }
コード例 #5
0
ファイル: SynelClient.cs プロジェクト: synel/syndll2
        /// <summary>
        /// Creates the full command string that is to be sent to the terminal.
        /// </summary>
        /// <param name="command">The request command.</param>
        /// <param name="terminalId">The terminal id.</param>
        /// <param name="data">Any data that should be sent along with the command.</param>
        /// <returns>The full command string, including CRC and EOT.</returns>
        internal static string CreateCommand(RequestCommand command, int terminalId, string data = null)
        {
            // sanitize input for null data
            if (data == null)
            {
                data = string.Empty;
            }

            // make sure the input isn't too long, except for when uploading fingerprints.
            if (data.Length > MaxDataSize && command != RequestCommand.Fingerprint)
            {
                throw new ArgumentException(string.Format("Data must be {0} ASCII characters or less.", MaxDataSize));
            }

            // Begin building the command string
            var sb = new StringBuilder(MaxPacketSize);

            // The first character is the request command code.
            sb.Append((char)command);

            // The second character is the terminal ID.
            sb.Append(Util.TerminalIdToChar(terminalId));

            // The data block comes next
            sb.Append(data);

            // Then 4 characters of CRC of the string thus far
            sb.Append(SynelCRC.Calculate(sb.ToString()));

            // Finally, a termination character.
            sb.Append(ControlChars.EOT);

            return(sb.ToString());
        }
コード例 #6
0
 // 调度过来的命令
 public void ReceiveCommand(RequestCommand command)
 {
     // TraceManagerForOPC.AppendInfo("PUMP-OPC子服务当前任务条目数:"+ this.queue.Count.ToString());
     //写值操作
     if (command.sonServerType == CommandServerType.Pump_OPC && command.operType == CommandOperType.Write)
     {
         TakeOutCollectCommand();
         this.Append(PumpCommand.CreateWriteCommand(this.opcClientManager, command));
         //命令记录
         TraceManagerForCommand.AppendDebug(string.Format("命令ID:{0}开始执行JZID:{1},业务地址{2},设定值{3}操作", command.ID, command.jzID, command.fDBAddress, command.value));
         return;
     }
     // OPC_Pump--重载请求
     if (command.sonServerType == CommandServerType.Pump_OPC && command.operType == CommandOperType.ReLoadData)
     {
         TakeOutCollectCommand();
         this.Append(PumpCommand.CreateReloadCommand(this.opcClientManager, command));
         //命令记录
         TraceManagerForCommand.AppendDebug(string.Format("命令ID:{0}开始执行PUMP-OPC重载机组数据操作:", command.ID));
         return;
     }
     // 错误请求
     CommandManager.MakeFail("错误的请求类型", ref command);
     CommandManager.CompleteCommand(command);
     TraceManagerForCommand.AppendErrMsg(command.message);
     return;
 }
コード例 #7
0
ファイル: OPCDataService.cs プロジェクト: Jaasdsa/CityIoT
 // 对调度服务实现的接口
 public void ReceiveCommand(RequestCommand command)
 {
     if (opcScadaManager != null && opcScadaManager.IsRuning)
     {
         opcScadaManager.ReceiveCommand(command);
     }
 }
コード例 #8
0
 private void ExcuteCommand(RequestCommand command)
 {
     if (command.sonServerType == CommandServerType.YL_WEB && command.operType == CommandOperType.ReLoadData)
     {
         if (ExcuteDoing) // 正在采集,等这次采集结束,在采集一次
         {
             DateTime time1 = DateTime.Now;
             while (true)
             {
                 Thread.Sleep(1);
                 if (DateTime.Now - time1 > TimeSpan.FromSeconds(command.timeoutSeconds)) // 超时
                 {
                     CommandManager.MakeTimeout("Scada-WEB-压力监测点 数据更新超时", ref command);
                     CommandManager.CompleteCommand(command);
                     TraceManagerForCommand.AppendInfo(command.message);
                     return;
                 }
                 if (!ExcuteDoing)
                 {
                     break;
                 }
             }
         }
         // 调取之前先重新加载一次缓存
         Excute();
         CommandManager.MakeSuccess("Scada-WEB-压力监测点 数据已更新", ref command);
         CommandManager.CompleteCommand(command);
         TraceManagerForCommand.AppendInfo("Scada-WEB-压力监测点 数据已更新");
         return;
     }
     CommandManager.MakeFail("错误的请求服务类型", ref command);
     CommandManager.CompleteCommand(command);
     TraceManagerForCommand.AppendErrMsg(command.message);
     return;
 }
コード例 #9
0
 public void ReceiveCommand(RequestCommand command)
 {
     //if (command == null)
     //    return;
     //if (command.commandServerType == CommandServerType.OPC_Pump && command.commandOperType == CommandOperType.ReLoadJZData)
     //{
     //    if (ExcuteDoing) // 正在采集,等这次采集结束,在采集一次
     //    {
     //        DateTime time1 = DateTime.Now;
     //        while (true)
     //        {
     //            Thread.Sleep(1);
     //            if (DateTime.Now - time1 > TimeSpan.FromSeconds(command.timeoutSeconds)) // 超时
     //            {
     //                RecCommand.MakeTimeout("Pump-OPC数据更新超时", ref command);
     //                CommandManager.CompleteCommand(command);
     //                TraceManagerForOPC.AppendInfo(command.message);
     //                return;
     //            }
     //            if (!ExcuteDoing)
     //                break;
     //        }
     //    }
     //    // 刷新一次
     //    Excute();
     //    RecCommand.MakeSuccess("Pump-OPC数据已更新", ref command);
     //    CommandManager.CompleteCommand(command);
     //    TraceManagerForOPC.AppendInfo("Pump-OPC数据已更新");
     //    return;
     //}
     //RecCommand.MakeFail("错误的请求服务类型", ref command);
     //CommandManager.CompleteCommand(command);
     //TraceManagerForOPC.AppendErrMsg(command.message);
     //return;
 }
コード例 #10
0
 private void ExcuteCommand(RequestCommand command)
 {
     CommandManager.MakeFail("暂时不支持控制服务", ref command);
     CommandManager.CompleteCommand(command);
     TraceManagerForCommand.AppendErrMsg(command.message);
     return;
 }
コード例 #11
0
        public async Task <IActionResult> Send(RequestCommand requestCommand)
        {
            if (!_notifyApplication.IsValid(requestCommand))
            {
                return(BadRequest(new ResponseMessage()
                {
                    Code = 400, Errors = new Dictionary <string, object>()
                    {
                        { "X404", "Request is not valid" }
                    }
                }));
            }

            var responseMessage = await _notifyApplication.PushMessage(requestCommand);

            if (responseMessage.Errors != null && responseMessage.Errors.Any())
            {
                return(BadRequest(new ResponseMessage()
                {
                    Code = responseMessage.Code, Errors = responseMessage.Errors
                }));
            }

            return(Ok(responseMessage));
        }
コード例 #12
0
 public RequestContext(RequestCommand requestCommand, string[] args)
 {
     RequestCommand = requestCommand;
     CommandArgs    = args;
     Settings       = new RequestSettings();
     TunerState     = new TunerState();
 }
コード例 #13
0
 public RenderElementRequest(RenderElement ve, RequestCommand req,
                             object parameters)
 {
     this.renderElem = ve;
     this.req        = req;
     this.parameters = parameters;
 }
        /// <seealso cref= CustomSerializer#serializeContent(RequestCommand, InvokeContext) </seealso>
        public override bool serializeContent(RequestCommand req, InvokeContext invokeContext)
        {
            serialFlag.set(true);
            RpcRequestCommand rpcReq = (RpcRequestCommand)req;
            RequestBody       bd     = (RequestBody)rpcReq.RequestObject;
            int id = bd.Id;

            byte[] msg;
            try
            {
                msg = Encoding.UTF8.GetBytes(bd.Msg);
                IByteBuffer bb = UnpooledByteBufferAllocator.Default.Buffer(4 + msg.Length);
                bb.WriteInt(id);
                bb.WriteBytes(msg);
                rpcReq.Content = bb.Array;
            }
            catch (UnsupportedEncodingException e)
            {
                System.Console.WriteLine(e.ToString());
                System.Console.Write(e.StackTrace);
            }

            contentSerializer = rpcReq.Serializer;
            return(true);
        }
        /// <seealso cref= CustomSerializer#deserializeContent(RequestCommand) </seealso>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: @Override public <T extends com.alipay.remoting.rpc.RequestCommand> boolean deserializeContent(T req) throws com.alipay.remoting.exception.DeserializationException
        public override bool deserializeContent(RequestCommand req)
        {
            deserialFlag.set(true);
            RpcRequestCommand rpcReq = (RpcRequestCommand)req;

            byte[]      content = rpcReq.Content;
            IByteBuffer bb      = Unpooled.WrappedBuffer(content);
            int         a       = bb.ReadInt();

            byte[] dst = new byte[content.Length - 4];
            bb.ReadBytes(dst, 0, dst.Length);
            try
            {
                string      b  = Encoding.UTF8.GetString(dst);
                RequestBody bd = new RequestBody(a, b);
                rpcReq.RequestObject = bd;
            }
            catch (UnsupportedEncodingException e)
            {
                System.Console.WriteLine(e.ToString());
                System.Console.Write(e.StackTrace);
            }

            contentDeserializer = rpcReq.Serializer;
            return(true);
        }
コード例 #16
0
ファイル: ZhuMaDianRuNan.cs プロジェクト: Jaasdsa/CityIoT
 public override void ReceiveCommand(RequestCommand command)
 {
     if (command == null)
     {
         CommandManager.MakeFail(projectName + "接受调度命令的异常命令", ref command);
         CommandManager.CompleteCommand(command);
         TraceManagerForDispatch.AppendErrMsg(projectName + "接受调度命令的异常命令");
         return;
     }
     if (command.sonServerType != CommandServerType.Pump_WEB && command.sonServerType != CommandServerType.ReLoadJZData)
     {
         CommandManager.MakeFail(projectName + "错误的服务类型", ref command);
         CommandManager.CompleteCommand(command);
         TraceManagerForDispatch.AppendErrMsg(projectName + "错误的服务类型");
         return;
     }
     if (this.sonServiceManager != null && this.sonServiceManager.IsRuning &&
         this.sonServiceManager.webDataService != null && this.sonServiceManager.webDataService.IsRuning)
     {
         this.sonServiceManager.webDataService.ReceiveCommand(command);
     }
     else
     {
         CommandManager.MakeFail(projectName + "子服务管理器未运行", ref command);
         CommandManager.CompleteCommand(command);
         TraceManagerForDispatch.AppendErrMsg(projectName + "子服务管理器未运行");
         return;
     }
 }
コード例 #17
0
 public void SetGear(GearDirection g)
 {
     gearDirectionRequest   = g;
     gearDirectionRequested = true;
     Status.GearDirection   = g;
     request = RequestCommand.Command;
 }
コード例 #18
0
ファイル: OPCDataService.cs プロジェクト: Jaasdsa/CityIoT
 // 对调度服务实现的接口
 public void ReceiveCommand(RequestCommand request)
 {
     if (opcPumpManager != null && opcPumpManager.IsRuning)
     {
         opcPumpManager.ReceiveCommand(request);
     }
 }
コード例 #19
0
 // 对调度服务实现的接口
 public void ReceiveCommand(RequestCommand command)
 {
     if (webPumpManager != null && webPumpManager.IsRuning)
     {
         webPumpManager.ReceiveCommand(command);
     }
 }
コード例 #20
0
ファイル: DeviceControl.cs プロジェクト: Jaasdsa/CityIoT
        public string ReLoadStationData(int stationID, out string statusCode, out string errMsg)
        {
            statusCode = "0000";
            errMsg     = "";
            // 服务器参数检查
            if (!iotParam.Check(out errMsg))
            {
                statusCode = "401";
                return("");
            }
            CommandServerType type = getStationCommmandServerType(stationID, out errMsg);

            if (!string.IsNullOrWhiteSpace(errMsg))
            {
                statusCode = "402";
                return("");
            }
            RequestCommand request = new RequestCommand()
            {
                ID            = Guid.NewGuid().ToString(),
                sonServerType = type,
                operType      = CommandOperType.ReLoadData,
                state         = CommandState.Pending,
                beginTime     = DateTime.Now
            };

            return(SendRequest(request, out statusCode, out errMsg));
        }
コード例 #21
0
        public VirtualUserNetwork(RequestCommand command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }
            if (command.Requests == null || command.Requests.Count == 0)
            {
                throw new ArgumentOutOfRangeException("command", Arguments.VirtualUserNetwork_EmptyCommandRequests);
            }
            if (command.Users == null)
            {
                throw new ArgumentNullException("command.Users");
            }
            if (command.Users.Amount < 1)
            {
                throw new ArgumentOutOfRangeException("command.Users.Amount", Arguments.VirtualUserNetwork_AmountNotGreaterThanZero);
            }
            ExecutionId = command.ExecutionId;
            Guid        = Guid.NewGuid();
            Id          = Guid.ToString().Split('-').First().ToUpper();

            userSettings  = command.Users;
            taskScheduler = new WorkStealingTaskScheduler(userSettings.Amount);
            tokenSource   = new CancellationTokenSource();
            queue         = new ConcurrentQueue <IRestRequest>(command.Requests);

            users = new ConcurrentBag <VirtualUser>();

            RestClient = command.Client;
            SleepTime  = command.Users.SleepTime;
        }
コード例 #22
0
 public void ReceiveCommand(RequestCommand dispatchCommand)
 {
     if (dispatchCommand != null)
     {
         Excute();
     }
 }
コード例 #23
0
 public void SetTurnSignal(TurnSignal t)
 {
     turnSignalRequest  = t;
     turnSinalRequested = true;
     Status.TurnSignal  = t;
     request            = RequestCommand.Command;
 }
コード例 #24
0
    public void MicroServiceResponseCorrelatesToRequest()
    {
        var options = new BusOptions()
        {
            QueueName = "CallbackTest02"
        };
        var serviceMock = new CallbackMock();

        using (var host = new MicroserviceHost <CallbackMock>(serviceMock, options))
            using (var proxy = new MicroserviceProxy(options))
            {
                host.Open();

                RequestCommand requestCommand = new RequestCommand {
                    Name = "Marco"
                };
                SlowRequestCommand slowCommand = new SlowRequestCommand {
                    Name = "Slow"
                };

                TestResponse slowResponse = proxy.Execute <TestResponse>(slowCommand);
                TestResponse response     = proxy.Execute <TestResponse>(requestCommand);

                Assert.Equal("Hello, Marco", response.Greeting);
                Assert.Equal("Hello, Slow", slowResponse.Greeting);
            }
    }
コード例 #25
0
ファイル: DeviceControl.cs プロジェクト: Jaasdsa/CityIoT
        // 控制请求接口
        public string WriteJZValue(int userID, int jzID, string fDBAddress, double value, out string statusCode, out string errMsg)
        {
            statusCode = "0000";
            errMsg     = "";

            // 服务器参数检查
            if (!iotParam.Check(out errMsg))
            {
                statusCode = "401";

                return("");
            }
            // 控制参数检查
            if (userID == 0)
            {
                errMsg     = "用户ID不能为空";
                statusCode = "402";
                return("");
            }
            if (!CheckControlRole(userID, out errMsg))
            {
                statusCode = "430";
                return("");
            }
            if (jzID == 0)
            {
                errMsg     = "机组ID不能为空";
                statusCode = "403";
                return("");
            }
            if (string.IsNullOrWhiteSpace(fDBAddress))
            {
                errMsg     = "数据业务地址不能为空";
                statusCode = "404";
                return("");
            }
            // 加载机组通信模式
            CommandServerType commandServerType = GetJZCommandServerType(jzID, out errMsg);

            if (!string.IsNullOrWhiteSpace(errMsg))
            {
                statusCode = "405";
                return("");
            }
            RequestCommand request = new RequestCommand()
            {
                ID            = Guid.NewGuid().ToString(),
                sonServerType = commandServerType,
                operType      = CommandOperType.Write,
                userID        = userID,
                jzID          = jzID,
                fDBAddress    = fDBAddress,
                value         = value,
                state         = CommandState.Pending,
                beginTime     = DateTime.Now
            };

            return(SendRequest(request, out statusCode, out errMsg));
        }
コード例 #26
0
        protected override async Task <ResponseCommand <T2> > Execute(RequestCommand <T, T2> context, Func <RequestCommand <T, T2>, Task <ResponseCommand <T2> > > next)
        {
            var failures = Validator.Validate <T>(context.Model);

            return(failures.Any()
                ? throw new Exception(string.Join(",", failures))
                : await next(context));
        }
コード例 #27
0
ファイル: RequestParser.cs プロジェクト: wade1990/SyncWinRT
        private List <IOfflineEntity> GetEntityListFromRequest(RequestCommand requestCommand)
        {
            if (requestCommand != RequestCommand.UploadChanges)
            {
                return(null);
            }

            return(_entityList);
        }
コード例 #28
0
ファイル: PumpCommand.cs プロジェクト: Jaasdsa/CityIoT
 /// <summary>
 /// 创建重载机组数据任务
 /// </summary>
 /// <param name="opcClientManager"></param>
 /// <param name="pointsSaveInterVal"></param>
 /// <returns></returns>
 public static PumpCommand CreateReloadCommand(OpcClient opcClientManager, RequestCommand requestCommand)
 {
     return(new PumpCommand()
     {
         type = PumpCommandType.Reload,
         opcClientManager = opcClientManager,
         requestCommand = requestCommand,
         opcCommandType = OPCCommandType.Pending,
     });
 }
コード例 #29
0
ファイル: ApiController.cs プロジェクト: sshaddicts/A2v10
        async Task ExecuteCommand(RequestCommand cmd, ExpandoObject dataToInvoke, Guid apiGuid)
        {
            switch (cmd.type)
            {
            case CommandType.clr:
                await ExecuteClrCommand(cmd, dataToInvoke, apiGuid);

                break;
            }
        }
コード例 #30
0
        /// <summary>
        /// Create a new command object
        /// </summary>
        /// <param name="command"></param>
        /// <param name="data"></param>
        public TpiCommand(RequestCommand command, String data = null)
        {
            Command = command;
            CommandData = data;

            if (data != null)
                TPIData = CheckSumHelper.AppendCheckSumAndEndOfRequest(command.GetStringValue() + data);
            else
                TPIData = CheckSumHelper.AppendCheckSumAndEndOfRequest(command.GetStringValue());
        }
コード例 #31
0
 /// <summary>
 /// 创建站点写值任务
 /// </summary>
 /// <param name="opcClientManager"></param>
 /// <param name="pointsSaveInterVal"></param>
 /// <returns></returns>
 public static StationCommand CreateWriteCommand(OpcClient opcClientManager, RequestCommand requestCommand)
 {
     return(new StationCommand()
     {
         type = StationCommandType.Write,
         opcClientManager = opcClientManager,
         requestCommand = requestCommand,
         opcCommandType = OPCCommandType.Pending,
     });
 }
コード例 #32
0
 internal static IRequestProcessor GetRequestProcessorInstance(RequestCommand requestCommand, SyncServiceConfiguration configuration,
     HttpContextServiceHost serviceHost)
 {
     switch (requestCommand)
     {
         case RequestCommand.UploadChanges:
             return new UploadChangesRequestProcessor(configuration, serviceHost);
         case RequestCommand.DownloadChanges:
             return new DownloadChangesRequestProcessor(configuration, serviceHost);
         case RequestCommand.SyncScopes:
             return new SyncScopesRequestProcessor(configuration);
         case RequestCommand.ScopeMetadata:
             return new ScopeSchemaRequestProcessor(configuration);
         default:
             throw new NotSupportedException();
     }
 }
コード例 #33
0
ファイル: Request.cs プロジェクト: Fedorm/core-master
        internal Request(RequestCommand requestCommand, 
                        HttpContextServiceHost serviceHost, 
                        Dictionary<CommandParamType, object> commandParams, 
                        byte[] blob,
                        List<IOfflineEntity> entities, 
                        SyncSerializationFormat responseSerializationFormat)
        {
            IdToTempIdMapping = new Dictionary<string, string>();

            RequestCommand = requestCommand;
            ServiceHost = serviceHost;
            CommandParams = commandParams;
            SyncBlob = blob;
            ResponseSerializationFormat = responseSerializationFormat;

            if (null != entities && requestCommand != RequestCommand.UploadChanges)
            {
                throw SyncServiceException.CreateBadRequestError(Strings.EntitiesOnlyAllowedForUploadChangesRequest);
            }

            EntityList = entities;
        }
コード例 #34
0
ファイル: SynelClient.cs プロジェクト: synel/syndll2
 /// <summary>
 /// Communicates with the terminal by sending a request and receiving a response.
 /// </summary>
 /// <param name="requestCommand">The request command to send.</param>
 /// <param name="dataToSend">Any data that should be sent along with the command.</param>
 /// <param name="validResponses">If specified, the response must start with one of the valid responses (omit the terminal id).</param>
 /// <returns>A validated <see cref="Response"/> object.</returns>
 internal Response SendAndReceive(RequestCommand requestCommand, string dataToSend = null, params string[] validResponses)
 {
     return SendAndReceive(requestCommand, dataToSend, 1, validResponses);
 }
コード例 #35
0
ファイル: SynelClient.cs プロジェクト: synel/syndll2
 /// <summary>
 /// Communicates with the terminal by sending a request and receiving a response.
 /// </summary>
 /// <param name="requestCommand">The request command to send.</param>
 /// <param name="dataToSend">Any data that should be sent along with the command.</param>
 /// <param name="attempts">Number of times to attempt the command until receiving a response.</param>
 /// <param name="validResponses">If specified, the response must start with one of the valid responses (omit the terminal id).</param>
 /// <returns>A validated <see cref="Response"/> object.</returns>
 internal Response SendAndReceive(RequestCommand requestCommand, string dataToSend = null, int attempts = 1, params string[] validResponses)
 {
     return SendAndReceive(requestCommand, dataToSend, attempts, 5000, validResponses);
 }
コード例 #36
0
 public RenderElementRequest(RenderElement ve, RequestCommand req)
 {
     this.ve = ve;
     this.req = req;
     this.parameters = null;
 }
コード例 #37
0
 public BindableViewModel(IRequestListener requestListener)
 {
     if (requestListener != null)
         Request = new RequestCommand(this, requestListener);
 }
コード例 #38
0
ファイル: SynelClient.cs プロジェクト: synel/syndll2
        /// <summary>
        /// Returns an awaitable task that communicates with the terminal by sending a request and receiving a response.
        /// </summary>
        /// <param name="requestCommand">The request command to send.</param>
        /// <param name="dataToSend">Any data that should be sent along with the command.</param>
        /// <param name="attempts">Number of times to attempt the command until receiving a response.</param>
        /// <param name="timeoutms">The timeout, in milliseconds, to wait for a response.</param>
        /// <param name="validResponses">If specified, the response must start with one of the valid responses (omit the terminal id).</param>
        /// <returns>A task that yields a validated <see cref="Response"/> object.</returns>
        internal async Task<Response> SendAndReceiveAsync(RequestCommand requestCommand, string dataToSend = null, int attempts = 1, int timeoutms = 5000, params string[] validResponses)
        {
            if (!Connected)
                throw new InvalidOperationException("Not connected!");

            // augment valid responses with the terminal id
            if (validResponses.Length > 0)
            {
                var tid = Util.TerminalIdToChar(_terminalId).ToString(CultureInfo.InvariantCulture);
                validResponses = validResponses.Select(x => x.Insert(1, tid)).ToArray();
            }

            var receiver = new Receiver(_connection.Stream);

            // retry loop
            for (int i = 1; i <= MaxRetries; i++)
            {
                try
                {
                    var cts = new CancellationTokenSource();
                    using (var timer = new Timer(state => cts.Cancel(), null, timeoutms, Timeout.Infinite))
                    {
                        // Send the request
                        var rawRequest = CreateCommand(requestCommand, dataToSend);
                        await SendAsync(rawRequest);

                        // Wait for the response or timeout
                        var message = await receiver.ReceiveMessageAsync(cts.Token);
                        if (message == null)
                            continue;

                        // Stop the idle timeout timer, since we have data
                        timer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);

                        // Don't ever handle host query responses here.
                        if (message.RawResponse[0] == 'q')
                            continue;

                        // If the valid list is populated, don't handle responses that aren't in it.
                        if (validResponses.Length > 0 && !validResponses.Any(x => message.RawResponse.StartsWith(x)))
                            continue;

                        // Ignore responses intended for other terminals
                        if (message.Response != null && message.Response.TerminalId != _terminalId)
                            continue;

                        if (message.RawResponse != null)
                            Util.Log("Received: " + message.RawResponse, RemoteAddress);

                        if (message.Exception != null)
                            throw message.Exception;

                        if (message.Response == null)
                        {
                            if (i < attempts && i < MaxRetries)
                            {
                                Util.Log("No response.  Retrying...", RemoteAddress);
                                continue;
                            }

                            throw new TimeoutException("No response received from the terminal.");
                        }

                        return message.Response;
                    }
                }
                catch (InvalidCrcException)
                {
                    // swallow these until the retry limit is reached
                    if (i < MaxRetries)
                        Util.Log("Bad CRC.  Retrying...", RemoteAddress);
                }
            }

            // We've hit the retry limit, throw a CRC exception.
            throw new InvalidCrcException(string.Format("Retried the operation {0} times, but still got CRC errors.", MaxRetries));
        }
コード例 #39
0
 public InvalidStatusException(RequestCommand command, ResponseStatus status)
     : base(string.Format("Response '{0}' is illegal for command '{1}'", status, command)) {
     Command = command;
     Status = status;
 }
コード例 #40
0
ファイル: SynelClient.cs プロジェクト: synel/syndll2
 /// <summary>
 /// Communicates with the terminal by sending a request without waiting for a response.
 /// </summary>
 /// <param name="requestCommand">The request command to send.</param>
 /// <param name="dataToSend">Any data that should be sent along with the command.</param>
 internal void SendOnly(RequestCommand requestCommand, string dataToSend = null)
 {
     SendOnlyAsync(requestCommand, dataToSend).Wait();
 }
コード例 #41
0
ファイル: SynelClient.cs プロジェクト: synel/syndll2
        /// <summary>
        /// Returns an awaitable task that communicates with the terminal by sending a request without waiting for a response.
        /// </summary>
        /// <param name="requestCommand">The request command to send.</param>
        /// <param name="dataToSend">Any data that should be sent along with the command.</param>
        internal async Task SendOnlyAsync(RequestCommand requestCommand, string dataToSend = null)
        {
            if (!Connected)
                throw new InvalidOperationException("Not connected!");

            var rawRequest = CreateCommand(requestCommand, dataToSend);
            await SendAsync(rawRequest);
        }
コード例 #42
0
 public string GenerateOutputMessage(RequestCommand requestCommand)
 {
     return string.Format("{0} has requested: {1}", requestCommand.Requester, requestCommand.RequestMessage);
 }
コード例 #43
0
ファイル: AccumulateData.cs プロジェクト: huamanhtuyen/VNACCS
 private string CreateRequestData(RequestCommand command, string outcode)
 {
     string str2;
     this.mSendCount = 0;
     string str = this.JobCode();
     IData data = new NaccsData {
         Header = { Control = DataControl.GetControl(), JobCode = str, UserId = this.mUser, Password = this.mPass, Path = this.mTermLogicalName, DataInfo = string.Format("{0}{1}{2:D6}", str, this.DateTimeString(), this.mSendCount) }
     };
     if (command == RequestCommand.GET)
     {
         str2 = outcode;
     }
     else
     {
         str2 = command.ToString();
     }
     string str3 = string.Format("{0}{1}", str2.PadRight(7, ' '), "\r\n");
     data.JobData = str3;
     this.mFirstRequest = data;
     return data.GetDataString();
 }
コード例 #44
0
ファイル: SynelClient.cs プロジェクト: synel/syndll2
        /// <summary>
        /// Creates the full command string that is to be sent to the terminal.
        /// </summary>
        /// <param name="command">The request command.</param>
        /// <param name="terminalId">The terminal id.</param>
        /// <param name="data">Any data that should be sent along with the command.</param>
        /// <returns>The full command string, including CRC and EOT.</returns>
        internal static string CreateCommand(RequestCommand command, int terminalId, string data = null)
        {
            // sanitize input for null data
            if (data == null)
                data = string.Empty;

            // make sure the input isn't too long, except for when uploading fingerprints.
            if (data.Length > MaxDataSize && command != RequestCommand.Fingerprint)
                throw new ArgumentException(string.Format("Data must be {0} ASCII characters or less.", MaxDataSize));

            // Begin building the command string
            var sb = new StringBuilder(MaxPacketSize);

            // The first character is the request command code.
            sb.Append((char)command);

            // The second character is the terminal ID.
            sb.Append(Util.TerminalIdToChar(terminalId));

            // The data block comes next
            sb.Append(data);

            // Then 4 characters of CRC of the string thus far
            sb.Append(SynelCRC.Calculate(sb.ToString()));

            // Finally, a termination character.
            sb.Append(ControlChars.EOT);

            return sb.ToString();
        }
コード例 #45
0
ファイル: SynelClient.cs プロジェクト: synel/syndll2
 /// <summary>
 /// Returns an awaitable task that communicates with the terminal by sending a request and receiving a response.
 /// </summary>
 /// <param name="requestCommand">The request command to send.</param>
 /// <param name="dataToSend">Any data that should be sent along with the command.</param>
 /// <param name="attempts">Number of times to attempt the command until receiving a response.</param>
 /// <param name="timeoutms">The timeout, in milliseconds, to wait for a response.</param>
 /// <param name="validResponses">If specified, the response must start with one of the valid responses (omit the terminal id).</param>
 /// <returns>A task that yields a validated <see cref="Response"/> object.</returns>
 internal async Task<Response> SendAndReceiveAsync(RequestCommand requestCommand, string dataToSend = null, int attempts = 1, params string[] validResponses)
 {
     return await SendAndReceiveAsync(requestCommand, dataToSend, attempts, 5000, validResponses);
 }
コード例 #46
0
 public RenderElementRequest(RenderElement ve, RequestCommand req, object parameters)
 {
     this.ve = ve;
     this.req = req;
     this.parameters = parameters;
 }
コード例 #47
0
ファイル: RequestParser.cs プロジェクト: jmichas/SyncWinRT
        private List<IOfflineEntity> GetEntityListFromRequest(RequestCommand requestCommand)
        {
            if (requestCommand != RequestCommand.UploadChanges)
            {
                return null;
            }

            return _entityList;
        }
コード例 #48
0
ファイル: SynelClient.cs プロジェクト: synel/syndll2
 /// <summary>
 /// Creates the full command string that is to be sent to the terminal.
 /// </summary>
 /// <param name="command">The request command.</param>
 /// <param name="data">Any data that should be sent along with the command.</param>
 /// <returns>The full command string, including CRC and EOT.</returns>
 private string CreateCommand(RequestCommand command, string data = null)
 {
     return CreateCommand(command, _terminalId, data);
 }
コード例 #49
0
ファイル: SynelClient.cs プロジェクト: synel/syndll2
 /// <summary>
 /// Communicates with the terminal by sending a request and receiving a response.
 /// </summary>
 /// <param name="requestCommand">The request command to send.</param>
 /// <param name="dataToSend">Any data that should be sent along with the command.</param>
 /// <param name="attempts">Number of times to attempt the command until receiving a response.</param>
 /// <param name="timeoutms">The timeout, in milliseconds, to wait for a response.</param>
 /// <param name="validResponses">If specified, the response must start with one of the valid responses (omit the terminal id).</param>
 /// <returns>A validated <see cref="Response"/> object.</returns>
 internal Response SendAndReceive(RequestCommand requestCommand, string dataToSend = null, int attempts = 1, int timeoutms = 5000, params string[] validResponses)
 {
     return SendAndReceiveAsync(requestCommand, dataToSend, attempts, timeoutms, validResponses).Result;
 }
コード例 #50
0
ファイル: BatchDoc.cs プロジェクト: huamanhtuyen/VNACCS
 private string CreateRequestData(RequestCommand command, string body)
 {
     IData data = new NaccsData {
         Header = { JobCode = "?" + command.ToString(), UserId = this.mUser, Password = this.mPass },
         JobData = body
     };
     return data.GetDataString();
 }
コード例 #51
0
ファイル: AccumulateData.cs プロジェクト: huamanhtuyen/VNACCS
 private void RequestSend(RequestCommand command, string outcode)
 {
     try
     {
         int num;
         if (command == RequestCommand.GET)
         {
             this.mIsExcute = true;
         }
         ComParameter senddata = new ComParameter {
             DataString = this.CreateRequestData(command, outcode)
         };
         ULogClass.LogWrite(string.Format("{0}_SEND Command({1})", this.JobCode(), command.ToString()), senddata.DataString.Substring(0, 400), true);
         if (command == RequestCommand.GET)
         {
             num = this.mGetClient.Send(this.mOwnerControl, command.ToString() + this.mSendCount.ToString(), senddata);
         }
         else
         {
             num = this.mCmdClient.Send(this.mOwnerControl, command.ToString() + this.mSendCount.ToString(), senddata);
         }
         if (num > 0)
         {
             ULogClass.LogWrite(string.Format("{0}_SEND Error code({1})", this.JobCode(), num));
             this.OnNetworkError(num, null);
             this.mIsExcute = false;
             this.ButtonLock(false);
         }
     }
     catch (Exception exception)
     {
         ULogClass.LogWrite(string.Format("{0}_SEND Error code({1})", this.JobCode(), "Exception"));
         HttpExceptionEx ex = new HttpExceptionEx(HttpStatus.Idle, HttpCause.ProgramError, exception);
         this.OnNetworkError(9, ex);
         this.mIsExcute = false;
         this.ButtonLock(false);
     }
 }