private void Button_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            ProcessRequest CMDTable = new ProcessRequest();
            DataTable      dt       = ((MainWindow)Application.Current.MainWindow)._1337;
            var            IPs      = (from row in dt.AsEnumerable()
                                       where row.Field <string>("Building").Contains(cbBuilding.SelectedItem.ToString())
                                       where row.Field <string>("Room") == cbRoom.SelectedItem.ToString()
                                       select row["IP"].ToString()).ToList();

            string controllerIP = IPs.ElementAt(0);

            ControllerGuc.Connect(controllerIP, 8888);

            // check if the controller is UDP
            var isUDP = (from row in dt.AsEnumerable()
                         where row.Field <string>("Building").Contains(cbBuilding.SelectedItem.ToString())
                         where row.Field <string>("Room") == cbRoom.SelectedItem.ToString()
                         select row["UDP"]).ToList();

            if ((bool)isUDP.ElementAt(0))
            {
                if (((Button)sender).Content.ToString() == "Zoom In" || ((Button)sender).Content.ToString() == "Zoom Out")
                {
                    ControllerGuc.SendCommand("!REQUEST", CMDTable.ProcessRequests["CameraZoomStop"].ToString());
                }
                else
                {
                    ControllerGuc.SendCommand("!REQUEST", CMDTable.ProcessRequests["CameraPanTiltStop"].ToString());
                }
            }
            else
            {
                ControllerGuc.SendHTTPCommand(controllerIP, 8888, CMDTable.ProcessRequests["CameraPanTiltStop"].ToString());
            }
        }
        public async Task <IActionResult> ProcessRequest(ProcessRequest processRequest)
        {
            ProcessRequest  pRequest  = new ProcessRequest();
            ProcessResponse pResponse = new ProcessResponse();

            pRequest.IsPriorityRequest = "No";
            using (var httpClient = new HttpClient())
            {
                try
                {
                    //int id = verify.VerificationId;
                    StringContent content = new StringContent(JsonConvert.SerializeObject(processRequest), Encoding.UTF8, "application/json");
                    using (var response = await httpClient.PostAsync("http://localhost:34213/api/Process/ProcessRequest", content))
                    {
                        string apiResponse = await response.Content.ReadAsStringAsync();

                        //ViewBag.Result = "Success";
                        pResponse = JsonConvert.DeserializeObject <ProcessResponse>(apiResponse);
                        //ViewBag.Result = "Successfully Registered, Please Login.....THANKYOU";
                        TempData["pResponse"] = JsonConvert.SerializeObject(pResponse);
                    }
                    TempData["RequestId"] = pResponse.RequestId;
                    TempData["PandD"]     = JsonConvert.SerializeObject(pResponse.PackagingAndDeliveryCharge);
                    //TempData["PandD"] = pResponse.PackagingAndDeliveryCharge;
                    TempData["Processing"] = JsonConvert.SerializeObject(pResponse.ProcessingCharge);
                }
                catch (Exception)
                {
                    ViewBag.Message = "Component API not Loaded. Please Try Later.";
                    return(View());
                }
            }
            return(RedirectToAction("ProcessResponse"));
        }
Beispiel #3
0
        /// <inheritdoc/>
        public async Task <ProcessResponse> Execute(ProcessRequest <TState> request, ProcessMiddlewareDelegate next, CancellationToken token)
        {
            var response = await next();

            foreach (var message in response.ProcessMessages
                     .Where(s => !s.IsPublished)
                     .Select(s => s.Message))
            {
                var executionResult = await PublishMessageAsync(message);

                if (executionResult.Success)
                {
                    await store.MarkMessageAsPublishedAsync(request.Id, message);
                }
            }

            return(response);

            Task <IExecutionResult> PublishMessageAsync(IMessage msg) =>
            msg switch
            {
                ICommand cmd => commandBus.PublishAsync(cmd),
                Notification notification => notificationBus.PublishAsync(notification),
                _ => throw new ArgumentException($"Invalid message type '{msg.GetType()}'."),
            };
        }
Beispiel #4
0
 /// <summary>
 /// Processes a request through a callback delegate within a try/catch block. Distinguished Entity Framework exceptions from general exceptions.
 /// </summary>
 /// <param name="callback">A delegate method to call within the try block</param>
 /// <param name="title">Title for the panel</param>
 /// <param name="successMessage">Text to display as the message if the callback processes without an exception</param>
 public void TryRun(ProcessRequest callback, string title, string successMessage)
 {
     if (TryCatch(callback))
     {
         ShowInfo(successMessage, title, STR_TITLE_ICON_success, STR_PANEL_success);
     }
 }
Beispiel #5
0
    protected void BtnQuery_Click(object sender, EventArgs e)
    {
        if (TextXiaoqu.Text != "")
        {
            ProcessRequest process = new ProcessRequest();
            if (process.ProcessSqlStr(this.TextXiaoqu.Text) == false)
            {
                Page.ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('" + GetTran("000873", "编号有误") + "!');</script>");
                return;
            }
            if (QueryInfo.IsNumberExist(this.TextXiaoqu.Text, DropDownQiShu.ExpectNum) == false)
            {
                Page.ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('" + GetTran("000710", "编号不存在") + "!');</script>");
                return;
            }
        }
        //根据用户的选择组合字符串
        string sql = GetSqlString();

        if (sql.Trim() != "")
        {
            //保存标准汇率的ID
            Session["currency"] = DropCurrency.SelectedValue;
            Session["gaojiSql"] = sql;

            Response.Redirect("AdvanceQueryView.aspx?CurGrass=" + DropDownQiShu.ExpectNum);
        }
    }
        /// <inheritdoc />
        public async Task <ProcessResponse> Execute(ProcessRequest <TState> request, ProcessMiddlewareDelegate next, CancellationToken token)
        {
            var response = await next();

            var correlationId = request.State is IIntegrationEvent @event
                ? @event.CorrelationId
                : Unified.NewCode();

            var processMessages = response.ProcessMessages
                                  .Select(m =>
            {
                m.Message.CorrelationId = correlationId;
                EnrichWithUserId(m.Message, options.ActorId);
                EnrichWithRoles(m.Message, "[]");

                var principal = new Principal
                {
                    IdentityId       = options.ActorId,
                    UserId           = options.ActorId,
                    IsProcessManager = true,
                };

                m.Message.Actor = principal.AsActor();
                if (m.Message is Command cmd)
                {
                    cmd.Principal = principal;
                }

                return(new ProcessMessage(m.Message, m.IsPublished));
            })
                                  .ToArray();

            return(new ProcessResponse(response.Id, processMessages, response.IsPersisted));
        }
Beispiel #7
0
 public CommandContext(ProcessRequest request, StringBuilder text, CommandMatch match, Dictionary <string, string> vars)
 {
     FromRequest = request;
     Text        = text;
     Match       = match;
     Vars        = vars;
 }
Beispiel #8
0
        public string GetRequest(string json)
        {
            _log4net.Info("GetRequest() called with json input");
            RequestObject = JsonConvert.DeserializeObject <ProcessRequest>(json);

            RequestObject = new ProcessRequest
            {
                Name              = RequestObject.Name,
                ContactNumber     = RequestObject.ContactNumber,
                CreditCardNumber  = RequestObject.CreditCardNumber,
                ComponentType     = RequestObject.ComponentType,
                ComponentName     = RequestObject.ComponentName,
                Quantity          = RequestObject.Quantity,
                IsPriorityRequest = RequestObject.IsPriorityRequest
            };
            int Processing = ProcessId();



            ResponseObject = new ProcessResponse
            {
                RequestId                  = Processing,
                ProcessingCharge           = ProcessingCharge(RequestObject.ComponentType),
                PackagingAndDeliveryCharge = PackagingDelivery(RequestObject.ComponentType, RequestObject.Quantity),
                DateOfDelivery             = DeliveryDate()
            };

            var ResponseString = JsonConvert.SerializeObject(ResponseObject);

            return(ResponseString);
        }
Beispiel #9
0
        public void Consume(ProcessRequest processor)
        {
            try
            {
                while (true)
                {
                    var data = m_client.Read();
                    if (data == null)
                    {
                        Console.WriteLine("Read empty data");
                        CleanupClosedConnection();
                        break;
                    }

                    var envelope = Envelope.Parser.ParseFrom(data);
                    if (envelope.PayloadCase == Envelope.PayloadOneofCase.Heartbeat)
                    {
                        Console.WriteLine("Heartbeat");
                        Send(envelope);
                    }
                    else
                    {
                        processor(this, envelope);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Read error " + e.Message);
                CleanupClosedConnection();
            }
        }
        public void ProcessDocumentResourceNames()
        {
            moq::Mock <DocumentProcessorService.DocumentProcessorServiceClient> mockGrpcClient = new moq::Mock <DocumentProcessorService.DocumentProcessorServiceClient>(moq::MockBehavior.Strict);

            mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock <lro::Operations.OperationsClient>().Object);
            ProcessRequest request = new ProcessRequest
            {
                ProcessorName = ProcessorName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"),
            };
            ProcessResponse expectedResponse = new ProcessResponse
            {
                Document = new Document(),
#pragma warning disable CS0612
                HumanReviewOperation = "human_review_operationb1fb7921",
#pragma warning restore CS0612
                HumanReviewStatus = new HumanReviewStatus(),
            };

            mockGrpcClient.Setup(x => x.ProcessDocument(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(expectedResponse);
            DocumentProcessorServiceClient client = new DocumentProcessorServiceClientImpl(mockGrpcClient.Object, null);
            ProcessResponse response = client.ProcessDocument(request.ProcessorName);

            xunit::Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
Beispiel #11
0
        /// <summary>
        /// List Active Process Requests
        /// </summary>
        /// <param name="processRequestResults"></param>
        /// <returns></returns>
        public static List <ProcessRequest> ListUnfinishedRequests()
        {
            var statusIn = ProcessRequest.StatusValue.STARTED;
            List <ProcessRequest> response = ProcessRequest.List(statusIn);

            return(response);
        }
Beispiel #12
0
        private IResponse ExecuteRequest(ClientRequest clientRequest, Executor clientExecutor)
        {
            if (clientRequest.ViewNumber < this.replicaState.ViewNumber)
            {
                // Old view
                Log.Debug("ExecuteRequest: DROP - old view");
                return(null);
            }

            if (clientRequest.ViewNumber > this.replicaState.ViewNumber)
            {
                // There's a higher view that I'm not in
                this.replicaState.ChangeToInitializationState();
                return(null);
            }
            ProcessRequest runProcessRequestProtocol = this.RunProcessRequestProtocol(clientRequest, clientExecutor);

            if (runProcessRequestProtocol == ProcessRequest.DROP)
            {
                return(null);
            }

            if (runProcessRequestProtocol == ProcessRequest.LAST_EXECUTION)
            {
                return(this.replicaState.ClientTable[clientRequest.ClientId].Item2);
            }

            return(null);
        }
Beispiel #13
0
        public string GetRequest(string json)
        {
            string ComponentType = ""; int ComponentQuantity = 0;

            int Processing    = 0;
            var RequestObject = JsonConvert.DeserializeObject <ProcessRequest>(json);

            RequestObject = new ProcessRequest
            {
                Name              = RequestObject.Name,
                ContactNumber     = RequestObject.ContactNumber,
                CreditCardNumber  = RequestObject.CreditCardNumber,
                ComponentType     = RequestObject.ComponentType,
                ComponentName     = RequestObject.ComponentName,
                Quantity          = RequestObject.Quantity,
                IsPriorityRequest = RequestObject.IsPriorityRequest
            };
            ComponentType     = RequestObject.ComponentType;
            ComponentQuantity = RequestObject.Quantity;
            Processing        = ProcessId();
            DateTime date = DateTime.Now;

            ResponseObject = new ProcessResponse
            {
                RequestId                  = Processing,
                ProcessingCharge           = ProcessingCharge(RequestObject.ComponentType),
                PackagingAndDeliveryCharge = PackagingDelivery(ComponentType, ComponentQuantity),
                DateOfDelivery             = date
            };

            string ResponseString = JsonConvert.SerializeObject(ResponseObject);

            return(ResponseString);
        }
        public ActionResult NewRequest(SourceRequestViewModel model)
        {
            var    principal = (ClaimsIdentity)User.Identity;
            string EmpNum    = principal.FindFirst(ClaimTypes.SerialNumber).Value;
            string FullName  = principal.FindFirst(ClaimTypes.GivenName).Value;
            string Email     = principal.FindFirst(ClaimTypes.Email).Value;

            if (ModelState.IsValid)
            {
                model.INITIATOR_NAME   = FullName;
                model.INITIATOR_NUMBER = EmpNum;
                model.INITIATOR_EMAIL  = Email;
                ProcessRequest.ProcessNewRequest(model, EmpNum);
                return(RedirectToAction("RequestHistory"));
            }
            else
            {
                SourceRequestViewModel item = new SourceRequestViewModel();
                string _dept       = principal.FindFirst(ClaimTypes.UserData).Value;
                string _deptCode   = principal.FindFirst(ClaimTypes.Actor).Value;
                string _branch     = principal.FindFirst(ClaimTypes.StateOrProvince).Value;
                string _branchCode = principal.FindFirst(ClaimTypes.PostalCode).Value;

                item.INITIATING_DEPT       = _dept;
                item.INITIATING_DEPTCODE   = _deptCode;
                item.INITIATING_BRANCH     = _branch;
                item.INITIATING_BRANCHCODE = _branchCode;
                ViewBag.ItemCategories     = Common.GetMainCategory();
                ViewBag.Vendors            = GetVendors.GetAllVendors();
                ViewBag.Error = "An Error Occurred";
                return(View(item));
            }
        }
        public JsonResult PendingSourceReqApproval(SourceRequestViewModel model)
        {
            //check for request id on the request on the request table
            var outcome = ProcessRequest.UpdateSourceRequestApproval(model);

            return(Json(outcome, JsonRequestBehavior.AllowGet));
        }
Beispiel #16
0
        private void Worker()
        {
            WaitHandle[] wait = { _ready, _stop };
            while (0 == WaitHandle.WaitAny(wait))
            {
                if (CrashImmediately)
                {
                    CrashImmediately = false;
                    throw new AggregateException();
                }

                HttpListenerContext context;
                lock (_queue) {
                    if (_queue.Count > 0)
                    {
                        context = _queue.Dequeue();
                    }
                    else
                    {
                        _ready.Reset();
                        continue;
                    }
                }

                try {
                    Logger.Log($"Request received; {context.Request.RemoteEndPoint}", 0);
                    ProcessRequest?.Invoke(context);
                }
                catch (Exception e) {
                    Logger.LogWarning($"Server could not process a request; {e.Message}", 0);
                }
            }
        }
Beispiel #17
0
        public async Task OnMessageRequest(ProcessRequest processRequest)
        {
            var msgType = typeof(Message).Assembly.GetType(processRequest.MessageType);
            var msg     = Convert.ChangeType(processRequest.Message, msgType);
            var message = msg as Message;

            var settings = new JsonSerializerSettings();

            settings.ContractResolver = new CamelCasePropertyNamesContractResolver {
            };

            string msgAsJson = JsonConvert.SerializeObject(msg, Formatting.Indented, settings);

            var mpSender = _marktpartnerRepository.GetMarktpartnerById(processRequest.SenderId);
            var mpSystem = _marktpartnerRepository.GetSystemMarktpartner();

            using (var handler = new HttpClientHandler {
                Credentials = new NetworkCredential(mpSystem.UserName, mpSystem.Password)
            })
            {
                using (HttpClient client = new HttpClient(handler))
                {
                    var result = await client.PostAsync(mpSender.ServiceUrl, new StringContent(msgAsJson)).ConfigureAwait(false);

                    Console.WriteLine(string.Format("Message {0} to {1}: {2}", message.Id, mpSender.ServiceUrl, result));
                }
            }
        }
    private static void BackgroundProcessStarter(object sender)
    {
        DateTime wkCurrPerth = DateTime.UtcNow.AddHours(8);

        try
        {
            // Process any manually submitted jobs (submitted via MSM or other means)
            List <JobRequest> jobs = AnyManualJobsRequired();
            if (jobs != null && jobs.Count > 0)
            {
                foreach (JobRequest job in jobs)
                {
                    ProcessRequest manualProcess = new ProcessRequest();
                    if (CheckRunManualJob(job))
                    {
                        manualProcess.RunManualStep(job.Name, job.RequestData);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Logger.Info("Manually submitted jobs terminated abnormally " + ex.Message + ex.StackTrace);
        }
    }
Beispiel #19
0
        public StringBuilder Run(CommandContext ctx)
        {
            var filePath = ctx.SiteConfig.GetSourcePathToFile(ctx.Match.Args.ElementAt(0));
            var filetext = Processor.Process(ProcessRequest.FromExistingRequest(ctx,
                                                                                filePath));

            var matches = CommandProcessor.GetRegexMatches(filetext.Text.ToString());

            ctx.Text = ctx.Text.Replace(ctx.Match.Match.Value, "");

            Func <StringBuilder> final = null;

            foreach (var m in matches)
            {
                var info = CommandProcessor.ParseCommandMatches(m);
                if (info.CommandName == "placeholder")
                {
                    final = () =>
                    {
                        return(filetext.Text.Replace(m.Value, ctx.Text.ToString()));
                    };
                }
            }

            return(final());
        }
Beispiel #20
0
        private async Task OnMessage(ProcessRequest processRequest)
        {
            var rawMessage = processRequest.Message as RawMessage;

            if (rawMessage == null)
            {
                Console.WriteLine("NULL");
            }
            var msg = JsonConvert.DeserializeObject <Message>(rawMessage.Value);

            if (msg.Type == "Invoic")
            {
                InvoicMessage inovicMsg = null;
                if (JsonHelper.IsValid <Bill>(rawMessage.Value))
                {
                    inovicMsg = JsonConvert.DeserializeObject <Bill>(rawMessage.Value);
                }
                else if (JsonHelper.IsValid <Reversal>(rawMessage.Value))
                {
                    inovicMsg = JsonConvert.DeserializeObject <Reversal>(rawMessage.Value);
                }
                await StartProcess("InvoicRouter", inovicMsg, processRequest.SenderId);
            }
            else if (msg.Type == "Customer")
            {
                var customerMsg = JsonConvert.DeserializeObject <Registration>(rawMessage.Value);
                await StartProcess("CustomerRouter", customerMsg, processRequest.SenderId);
            }
            else
            {
                throw new NotSupportedException(string.Format("Message type {0} is not supported", msg.Type));
            }
        }
Beispiel #21
0
        public async Task <ProcessResponse> ProcessPaymentAsync(ProcessRequest processRequest)
        {
            var paymentId   = Guid.NewGuid().ToString();
            var bankRequest = new BankRequest(GetBank(processRequest.CardNo), processRequest.CardNo, processRequest.Amount);

            var bankResponse = await _bankIntegration.SendtoAcquirerAsync(bankRequest);

            var dbResponse = await _operations.AddPaymentAsync(processRequest, bankResponse, paymentId);

            if (!dbResponse.Success)
            {
                _logger.LogError("Failed to log payment to databse for Payment Id {PaymentId}", paymentId);
            }

            if (bankResponse.Success)
            {
                return(new ProcessResponse
                {
                    Success = true,
                    PaymentId = paymentId
                });
            }

            _logger.LogWarning("Acquirer returned error for Payment Id {PaymentId}", paymentId);
            return(new ProcessResponse
            {
                Success = false,
                ErrorMessage = bankResponse.Reason,
                Message = "Something went wrong with transaction, please contact card issuer.",
                PaymentId = paymentId
            });
        }
Beispiel #22
0
        /// <summary>
        /// List Active Process Requests
        /// </summary>
        /// <param name="processRequestResults"></param>
        /// <returns></returns>
        public static List <ProcessRequest> ListActiveRequests()
        {
            var statusIn = ProcessRequest.StatusValue.OPEN;
            List <ProcessRequest> response = ProcessRequest.List(statusIn);

            return(response);
        }
Beispiel #23
0
        public async stt::Task ProcessDocumentRequestObjectAsync()
        {
            moq::Mock <DocumentProcessorService.DocumentProcessorServiceClient> mockGrpcClient = new moq::Mock <DocumentProcessorService.DocumentProcessorServiceClient>(moq::MockBehavior.Strict);

            mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock <lro::Operations.OperationsClient>().Object);
            ProcessRequest request = new ProcessRequest
            {
                ProcessorName   = ProcessorName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"),
                SkipHumanReview = true,
                InlineDocument  = new Document(),
                RawDocument     = new RawDocument(),
            };
            ProcessResponse expectedResponse = new ProcessResponse
            {
                Document          = new Document(),
                HumanReviewStatus = new HumanReviewStatus(),
            };

            mockGrpcClient.Setup(x => x.ProcessDocumentAsync(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall <ProcessResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
            DocumentProcessorServiceClient client = new DocumentProcessorServiceClientImpl(mockGrpcClient.Object, null);
            ProcessResponse responseCallSettings  = await client.ProcessDocumentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));

            xunit::Assert.Same(expectedResponse, responseCallSettings);
            ProcessResponse responseCancellationToken = await client.ProcessDocumentAsync(request, st::CancellationToken.None);

            xunit::Assert.Same(expectedResponse, responseCancellationToken);
            mockGrpcClient.VerifyAll();
        }
Beispiel #24
0
 /// <summary>
 /// Processes a request through a delegate within a try/catch block
 /// </summary>
 /// <param name="Mydelegate">A delegate method called within try/catch block</param>
 /// <param name="message"> Message to be displayed if MyDelegate executed without raising an exception</param>
 public void TryRun(ProcessRequest Mydelegate, string message)
 {
     if (TryCatch(Mydelegate))
     {
         ShowInfo(message, STR_ICON_SUCCESS, STR_ALERT_SUCCESS);
     }
 }
Beispiel #25
0
        public ApiResponseStatus ProcessRequest(RequestParam requestParam, string token)
        {
            var processRequest = new ProcessRequest();

            return(processRequest.ProcessWebRequest(requestParam.Url, requestParam.RequestType,
                                                    requestParam.RequestBody, requestParam.Parameters, token));
        }
Beispiel #26
0
        public void ProcessDocumentRequestObject()
        {
            moq::Mock <DocumentProcessorService.DocumentProcessorServiceClient> mockGrpcClient = new moq::Mock <DocumentProcessorService.DocumentProcessorServiceClient>(moq::MockBehavior.Strict);

            mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock <lro::Operations.OperationsClient>().Object);
            ProcessRequest request = new ProcessRequest
            {
                ProcessorName   = ProcessorName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"),
                SkipHumanReview = true,
                InlineDocument  = new Document(),
                RawDocument     = new RawDocument(),
            };
            ProcessResponse expectedResponse = new ProcessResponse
            {
                Document          = new Document(),
                HumanReviewStatus = new HumanReviewStatus(),
            };

            mockGrpcClient.Setup(x => x.ProcessDocument(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(expectedResponse);
            DocumentProcessorServiceClient client = new DocumentProcessorServiceClientImpl(mockGrpcClient.Object, null);
            ProcessResponse response = client.ProcessDocument(request);

            xunit::Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
Beispiel #27
0
        public void Multiple_units_can_move_east_in_parallel()
        {
            const int repetitions = 1;

            var movementProcessor = new MovementProcessor();

            INewLocationCalculator newLocationCalculator = NewLocationCalculatorFactory.GetNewLocationCalculator(CompassDirection.East);

            var requests = new ProcessRequest[repetitions];

            for (int i = 0; i < repetitions; i++)
            {
                requests[i] = new ProcessRequest(Point2.Empty, 2.0f + i);
            }

            Stopwatch sw = Stopwatch.StartNew();

            ProcessResponse[] response = movementProcessor.Process(requests, newLocationCalculator);
            sw.Stop();
            Console.WriteLine($"Time taken: {sw.ElapsedMilliseconds} ms");

            int cnt = 0;

            foreach (ProcessResponse item in response)
            {
                Assert.AreEqual(1.0f + cnt, item.NewMovementPoints, "NewMovementPoints incorrect.");
                cnt++;
            }
        }
Beispiel #28
0
        public StringBuilder Run(CommandContext ctx)
        {
            if (ctx.Vars == null)
            {
                Console.WriteLine("can't process var for {0}", ctx.Match.Match.Value);
                return(ctx.Text);
            }

            var args = ctx.Match.Args.GetArgs().AsDictionary();

            //if we need to pull in vars from another file
            if (args.ContainsKey("from"))
            {
                var    newVars       = new Dictionary <string, string>();
                string fileName      = ctx.SiteConfig.GetSourcePathToFile(args["from"]);
                var    processResult = Processor.Process(ProcessRequest.FromExistingRequest(ctx, fileName));
                CommandProcessor.GetCommandMatchesFromText(processResult.Text.ToString())
                .Where(i => i.CommandName == "var" || i.CommandName == "val")
                .Select(i => i.Args.GetArgs().AsDictionary())
                .ForEach(d => d.Keys.ForEach(i => newVars[i] = d[i]));

                //add in the cached items vars -- if it was cached
                // then they would not be in there
                newVars.MixIn(processResult.Vars);

                return(GetVal(ctx.Match.Args.ElementAt(0), newVars, ctx.Text, ctx.Match.Match.Value));
            }

            return(GetVal(ctx.Match.Args.ElementAt(0), ctx.Vars, ctx.Text, ctx.Match.Match.Value));
        }
        public string PackageDeliver(string ComponentType, int count)
        {
            string         deliveryCharge = "";
            ProcessRequest processRequest = new ProcessRequest();

            processRequest.ComponentType = ComponentType;
            processRequest.Quantity      = count;

            if (ComponentType == "Integral")
            {
                int amount = 100;
                count = Convert.ToInt32(count);
                int delcharge = 200;
                deliveryCharge = Convert.ToString((amount * count) + delcharge);
            }
            if (ComponentType == "Accessory")
            {
                int amount = 50;
                count = Convert.ToInt32(count);
                int delcharge = 100;
                deliveryCharge = Convert.ToString((amount * count) + delcharge);
            }
            _context.SaveChanges();
            return(deliveryCharge);
        }
        public static BusinessServiceModel FromRequest(ProcessRequest request, bool shouldUpdate = false)
        {
            var newComDispatch = new BusinessServiceModel
            {
                TerminalId    = request.ProcessKey.TerminalId,
                DataAreaId    = request.ProcessKey.DataAreaId,
                StoreId       = request.ProcessKey.StoreId,
                OperationId   = Guid.Parse(request.ProcessKey.OperationId),
                StaffId       = request.StaffId,
                OperationType = request.OperationType,
                EntityId      = request.EntityId,
                ElementId     = request.ElementId,
                TransactionId = request.TransactionId,
                Barcode       = request.Barcode,
            };


            if (request.BeginTime != 0)
            {
                newComDispatch.BeginDateTime = DateTime.FromBinary(request.BeginTime);
            }
            if (request.EndTime != 0)
            {
                newComDispatch.EndDateTime = DateTime.FromBinary(request.EndTime);
            }

            return(newComDispatch);
        }
 private bool TryCatch(ProcessRequest callback)
 {
     try
     {
         callback();
         return true;
     }
     catch (DbEntityValidationException ex)
     {
         HandleException(ex);
     }
     catch (Exception ex)
     {
         HandleException(ex);
     }
     return false;
 }
 public void TryRun(ProcessRequest callback, bool suppressFeedback)
 {
     TryCatch(callback);
     MessagePanel.Visible = !suppressFeedback;
 }
Beispiel #33
0
 /// <summary>
 /// Adds a route - a specific delegate, a HTTP method and a regular 
 /// expression to which AbsolutePath have to match to run this delegate
 /// </summary>
 /// <param name="method">A HTTP method - GET, POST, PUT or DELETE (case sensitive)</param>
 /// <param name="pathRegExp">Absolute URI path regular expression to be matched for run</param>
 /// <param name="processor">A delegate which will be run if path and method matches</param>
 public void AddRoute(string method, string pathRegExp, ProcessRequest processor)
 {
     switch (method)
     {
         case "GET":
             {
                 routesGet.Add(pathRegExp, processor);
                 break;
             }
         case "POST":
             {
                 routesPost.Add(pathRegExp, processor);
                 break;
             }
         case "PUT":
             {
                 routesPut.Add(pathRegExp, processor);
                 break;
             }
         case "DELETE":
             {
                 routesDelete.Add(pathRegExp, processor);
                 break;
             }
         default:
             {
                 break;
             }
     }
 }
 /// <summary>
 /// Processes a request through a callback delegate within a try/catch block. Distinguished Entity Framework exceptions from general exceptions.
 /// </summary>
 /// <param name="callback">A delegate method to call within the try block</param>
 /// <param name="title">Title for the panel</param>
 /// <param name="successMessage">Text to display as the message if the callback processes without an exception</param>
 public void TryRun(ProcessRequest callback, string title, string successMessage)
 {
     if (TryCatch(callback))
         ShowInfo(successMessage, title, STR_TITLE_ICON_success, STR_PANEL_success);
 }
 /// <summary>
 /// Processes a request through a callback delegate within a try/catch block. Distinguished Entity Framework exceptions from general exceptions.
 /// </summary>
 /// <param name="callback">A delegate method to call within the try block</param>
 public void TryRun(ProcessRequest callback)
 {
     TryCatch(callback);
 }
        /// <summary>
        /// Processes the callback in terms of the HttpRequest and extracts either hidden form fields, or querystring parameters
        /// that is returned from the payment provider.
        /// Determines the payment status and saves that indication for later, could be in session, in db, or other storage.
        /// This information is important and used in the GetPaymentStatus().
        /// </summary>
        /// <param name="paymentSystem">The payment system.</param>
        /// <param name="paymentArgs">The payment args.</param>
        public override void ProcessCallback([NotNull] PaymentSystem paymentSystem, [NotNull] PaymentArgs paymentArgs)
        {
            Assert.ArgumentNotNull(paymentSystem, "paymentSystem");
              Assert.ArgumentNotNull(paymentArgs, "paymentArgs");
              Assert.IsNotNull(paymentArgs.ShoppingCart, "Shopping cart is null");

              this.PaymentStatus = PaymentStatus.Failure;

              HttpRequest request = HttpContext.Current.Request;
              PaymentSettingsReader configuration = new PaymentSettingsReader(paymentSystem);
              ITransactionData transactionDataProvider = Context.Entity.Resolve<ITransactionData>();
              string operation = configuration.GetSetting("operation");

              string transactionId = request.QueryString["transactionId"];
              string responseCode = request.QueryString["responseCode"];

              if (string.Compare(responseCode, "OK", StringComparison.OrdinalIgnoreCase) == 0)
              {
            string merchantId = paymentSystem.Username;
            string token = paymentSystem.Password;
            string orderNumber = paymentArgs.ShoppingCart.OrderNumber;
            decimal amount = paymentArgs.ShoppingCart.Totals.TotalPriceIncVat;
            string currency = this.Currency(paymentArgs.ShoppingCart.Currency.Code);

            Netaxept client = new Netaxept();
            ProcessRequest processRequest = new ProcessRequest
            {
              Operation = operation,
              TransactionId = transactionId
            };
            try
            {
              ProcessResponse processResponse = client.Process(merchantId, token, processRequest);
              if (string.Compare(processResponse.ResponseCode, "OK", StringComparison.OrdinalIgnoreCase) == 0)
              {
            this.PaymentStatus = PaymentStatus.Succeeded;
            transactionDataProvider.SaveCallBackValues(paymentArgs.ShoppingCart.OrderNumber, this.PaymentStatus.ToString(), transactionId, amount.ToString(), currency, string.Empty, string.Empty, string.Empty, string.Empty);

            if (string.Compare(operation, this.ReservableTransactionType, StringComparison.OrdinalIgnoreCase) == 0)
            {
              ReservationTicket reservationTicket = new ReservationTicket
              {
                Amount = amount,
                AuthorizationCode = processResponse.AuthorizationId,
                InvoiceNumber = orderNumber,
                TransactionNumber = transactionId
              };
              transactionDataProvider.SavePersistentValue(reservationTicket.InvoiceNumber, PaymentConstants.ReservationTicket, reservationTicket);
            }
              }
            }
            catch (Exception exception)
            {
              Log.Error(exception.Message, exception, this);
            }
              }
              else if (string.Compare(responseCode, "CANCEL", StringComparison.OrdinalIgnoreCase) == 0)
              {
            this.PaymentStatus = PaymentStatus.Canceled;
              }

              if (this.PaymentStatus != PaymentStatus.Succeeded)
              {
            transactionDataProvider.SavePersistentValue(paymentArgs.ShoppingCart.OrderNumber, TransactionConstants.PaymentStatus, this.PaymentStatus.ToString());
              }
        }
Beispiel #37
0
 public void AddRoute(string method, string pathRegExp, ProcessRequest processor)
 {
     routes.Add(new Route() { Method = method, Uri = pathRegExp, Handler = processor });
 }
        protected ProcessResponse Process([NotNull] PaymentSystem paymentSystem, [NotNull] ReservationTicket reservationTicket, decimal amount, [NotNull] string operation)
        {
            Assert.ArgumentNotNull(paymentSystem, "paymentSystem");
              Assert.ArgumentNotNull(reservationTicket, "reservationTicket");
              Assert.ArgumentNotNull(operation, "operation");

              string merchantId = paymentSystem.Username;
              string token = paymentSystem.Password;
              string transactionId = reservationTicket.TransactionNumber;
              string transactionAmount = amount.ToCents();

              Netaxept client = new Netaxept();
              ProcessRequest processRequest = new ProcessRequest
              {
            Operation = operation,
            TransactionId = transactionId,
            TransactionAmount = transactionAmount
              };

              return client.Process(merchantId, token, processRequest);
        }