Exemple #1
1
        private string GenerateRequestXml(RequestInput input)
        {
            var sw = new StringWriter();

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.NewLineOnAttributes = false;
            settings.OmitXmlDeclaration = true;

            using (XmlWriter writer = XmlWriter.Create(sw, settings))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("GenerateRequest");
                writer.WriteElementString("pxPayUserId", pxPayUserId);
                writer.WriteElementString("pxPayKey", pxPayKey);

                PropertyInfo[] properties = input.GetType().GetProperties();

                foreach (PropertyInfo prop in properties)
                {
                    if (prop.CanWrite)
                    {
                        string val = (string)prop.GetValue(input, null);
                        if (val != null || val != string.Empty)
                        {
                            writer.WriteElementString(prop.Name, val);
                        }
                    }
                }
                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Flush();
            }
            return sw.ToString();
        }
Exemple #2
0
        protected void submit_Click(object sender, EventArgs e)
        {
            PxPay        ws    = new PxPay("Magnetism_Dev", "c21aa727d509e3828e79a21ab4f7a4b609b758817d83e87b7f3c722d7a88cd3a");
            RequestInput input = new RequestInput();

            decimal amount = 0;

            if (decimal.TryParse(this.amount.Text, out amount) && amount > 0)
            {
                bool     isRegularGift = this.isregulargift.Checked;
                DateTime startDate     = ParseDateTime(this.startdate.Text);

                input.AmountInput       = string.Format("{0:0.00}", amount);
                input.CurrencyInput     = "NZD";
                input.EmailAddress      = this.emailaddress.Text;
                input.MerchantReference = Guid.NewGuid().ToString();
                input.TxnType           = isRegularGift ? "Auth" : "Purchase"; // for all regular gifts, authorize (hold) the card. for one-off donations, send a purchase message
                input.EnableAddBillCard = this.isregulargift.Checked ? "1" : "0";
                input.TxnData1          = this.startdate.Text;
                input.TxnData2          = this.enddate.Text;
                input.UrlFail           = string.Format("http://{0}/_test/fail.aspx", Request.Url.Authority);
                input.UrlSuccess        = string.Format("http://{0}/_test/success.aspx", Request.Url.Authority);

                RequestOutput output = ws.GenerateRequest(input);
                if (output.valid == "1")
                {
                    Response.Redirect(output.Url);
                }
            }
        }
        public string Button1_Click()
        {
            string PxPayUserId = _configuration.GetSection("WindCave:PxPayUserId").Value;//.AppSettings["PxPayUserId"];
            string PxPayKey    = _configuration.GetSection("WindCave:PxPayKey").Value;
            //string PxPayKey = ConfigurationManager.AppSettings["PxPayKey"];

            PxPay WS = new PxPay(PxPayUserId, PxPayKey);

            RequestInput input = new RequestInput();

            input.AmountInput       = "123";
            input.CurrencyInput     = "NZD";
            input.MerchantReference = "My Reference";
            input.TxnType           = "Purchase";
            input.UrlFail           = "https://demo.windcave.com/SandboxSuccess.aspx";
            input.UrlSuccess        = "https://demo.windcave.com/SandboxSuccess.aspx";
            //input.UrlFail = Request.Url.GetLeftPart(UriPartial.Path);
            //input.UrlSuccess = Request.Url.GetLeftPart(UriPartial.Path);

            // TODO: GUID representing unique identifier for the transaction within the shopping cart (normally would be an order ID or similar)
            Guid orderId = Guid.NewGuid();

            input.TxnId = orderId.ToString().Substring(0, 16);
            //input.TxnId = "123456123123123";

            RequestOutput output = WS.GenerateRequest(input);

            if (output.valid == "1")
            {
                // Redirect user to payment page

                //Response.Redirect(output.Url);
                return(output.Url);
            }

            return(output.Url);
            //PxPay WS = new PxPay(PxPayUserId, PxPayKey);

            //RequestInput input = new RequestInput();

            //input.AmountInput = "123";
            //input.CurrencyInput = "123";
            //input.MerchantReference = "123";
            //input.TxnType = "123";
            //input.UrlFail = Request.Url.GetLeftPart(UriPartial.Path);
            //input.UrlSuccess = Request.Url.GetLeftPart(UriPartial.Path);

            //// TODO: GUID representing unique identifier for the transaction within the shopping cart (normally would be an order ID or similar)
            //Guid orderId = Guid.NewGuid();
            //input.TxnId = orderId.ToString().Substring(0, 16);

            //RequestOutput output = WS.GenerateRequest(input);

            //if (output.valid == "1")
            //{
            //    // Redirect user to payment page

            //    Response.Redirect(output.Url);
            //}
        }
Exemple #4
0
        private static string GeneratePxPayRequestURL(decimal amount, string reference, string transactionID,
                                                      string txnData, string urlFail, string urlSuccess, bool enableAddBillCard = true, string dpsBillingId = null)
        {
            RequestInput reqInput = new RequestInput();

            //if (!string.IsNullOrEmpty(dpsBillingId))
            //{
            //    reqInput.DpsBillingId = dpsBillingId;
            //}
            //else if (enableAddBillCard)
            //{
            //    reqInput.EnableAddBillCard = "1";
            //}

            reqInput.AmountInput       = amount.ToString("F2");
            reqInput.CurrencyInput     = CurrencyType.NZD;
            reqInput.MerchantReference = reference;
            reqInput.TxnId             = transactionID;
            reqInput.TxnData1          = txnData;
            reqInput.TxnType           = "Purchase";
            reqInput.UrlFail           = urlFail;
            reqInput.UrlSuccess        = urlSuccess;

            RequestOutput output = _pxPay.GenerateRequest(reqInput);

            if (output.valid == "1" && output.Url != null)
            {
                // Redirect user to payment page
                return(output.Url);
            }
            else
            {
                return(null);
            }
        }
Exemple #5
0
        public IActionResult SendAuthenticationRequest([FromBody] UserAttributeTransferDto userAttributeTransfer)
        {
            bool  res       = false;
            ulong accountId = ulong.Parse(User.Identity.Name, CultureInfo.InvariantCulture);

            UtxoPersistency utxoPersistency = _executionContextManager.ResolveUtxoExecutionServices(accountId);

            byte[] target  = userAttributeTransfer.Target.HexStringToByteArray();
            byte[] issuer  = userAttributeTransfer.Source.HexStringToByteArray();
            byte[] payload = userAttributeTransfer.Payload.HexStringToByteArray();
            byte[] assetId = userAttributeTransfer.AssetId.HexStringToByteArray();
            byte[] originalBlindingFactor = userAttributeTransfer.OriginalBlindingFactor.HexStringToByteArray();
            byte[] originalCommitment     = userAttributeTransfer.OriginalCommitment.HexStringToByteArray();
            byte[] lastTransactionKey     = userAttributeTransfer.LastTransactionKey.HexStringToByteArray();
            byte[] lastBlindingFactor     = userAttributeTransfer.LastBlindingFactor.HexStringToByteArray();
            byte[] lastCommitment         = userAttributeTransfer.LastCommitment.HexStringToByteArray();
            byte[] lastDestinationKey     = userAttributeTransfer.LastDestinationKey.HexStringToByteArray();


            RequestInput requestInput = new RequestInput {
                AssetId = assetId, EligibilityBlindingFactor = originalBlindingFactor, EligibilityCommitment = originalCommitment, Issuer = issuer, PrevAssetCommitment = lastCommitment, PrevBlindingFactor = lastBlindingFactor, PrevDestinationKey = lastDestinationKey, PrevTransactionKey = lastTransactionKey, Target = target, Payload = payload
            };

            OutputModel[] outputModels        = _gatewayService.GetOutputs(_portalConfiguration.RingSize + 1);
            byte[][]      issuanceCommitments = _gatewayService.GetIssuanceCommitments(issuer, _portalConfiguration.RingSize + 1);
            RequestResult requestResult       = utxoPersistency.TransactionsService.SendAuthenticationRequest(requestInput, outputModels, issuanceCommitments).Result;

            res = true;
            return(Ok(res));
        }
Exemple #6
0
        private void SendOnboardingRequest(UserAttributeTransferDto userAttributeTransfer, IUtxoTransactionsService transactionsService, AssociatedProofPreparation[] associatedProofPreparations = null)
        {
            byte[] target  = userAttributeTransfer.Target.HexStringToByteArray();
            byte[] issuer  = userAttributeTransfer.Source.HexStringToByteArray();
            byte[] payload = userAttributeTransfer.Payload.HexStringToByteArray();
            byte[] assetId = userAttributeTransfer.AssetId.HexStringToByteArray();
            byte[] originalBlindingFactor = userAttributeTransfer.OriginalBlindingFactor.HexStringToByteArray();
            byte[] originalCommitment     = userAttributeTransfer.OriginalCommitment.HexStringToByteArray();
            byte[] lastTransactionKey     = userAttributeTransfer.LastTransactionKey.HexStringToByteArray();
            byte[] lastBlindingFactor     = userAttributeTransfer.LastBlindingFactor.HexStringToByteArray();
            byte[] lastCommitment         = userAttributeTransfer.LastCommitment.HexStringToByteArray();
            byte[] lastDestinationKey     = userAttributeTransfer.LastDestinationKey.HexStringToByteArray();

            RequestInput requestInput = new RequestInput
            {
                AssetId = assetId,
                EligibilityBlindingFactor = originalBlindingFactor,
                EligibilityCommitment     = originalCommitment,
                Issuer = issuer,
                PrevAssetCommitment = lastCommitment,
                PrevBlindingFactor  = lastBlindingFactor,
                PrevDestinationKey  = lastDestinationKey,
                PrevTransactionKey  = lastTransactionKey,
                Target  = target,
                Payload = payload
            };

            OutputModel[] outputModels        = _gatewayService.GetOutputs(_portalConfiguration.RingSize + 1);
            byte[][]      issuanceCommitments = _gatewayService.GetIssuanceCommitments(issuer, _portalConfiguration.RingSize + 1);
            RequestResult requestResult       = transactionsService.SendOnboardingRequest(requestInput, associatedProofPreparations, outputModels, issuanceCommitments).Result;
        }
        public RequestJson RequestPaymentUrl(int cartId)
        {
            string PxPayUserId = _configuration.GetSection("WindCave:PxPayUserId").Value;//.AppSettings["PxPayUserId"];
            string PxPayKey    = _configuration.GetSection("WindCave:PxPayKey").Value;

            PxPay WS = new PxPay(PxPayUserId, PxPayKey);

            RequestInput input  = new RequestInput();
            var          card   = _context.Cart.Find(cartId);
            decimal      amount = ((decimal)card.Price - (decimal)card.SalePrice) * 0.50m + (decimal)card.SalePrice + (decimal)card.DeliveryFee;

            input.AmountInput       = Math.Round(amount, 2).ToString();
            input.CurrencyInput     = "NZD";
            input.MerchantReference = "My Reference";
            input.TxnType           = "Purchase";
            input.Opt = "TO=" + DateTime.UtcNow.AddMinutes(10).ToString("yyMMddHHmm");

            input.UrlFail    = "http://luxedreameventhire.co.nz:80/paymentresult";
            input.UrlSuccess = "http://luxedreameventhire.co.nz:80/paymentresult";

            input.UrlCallback = "http://api.luxedreameventhire.co.nz/api/pxpay/ResponseOutput";

            //input.UrlFail = "http://localhost:4200/paymentresult";
            //input.UrlSuccess = "http://localhost:4200/paymentresult";

            //input.UrlCallback = "http://localhost:5000/api/pxpay/ResponseOutput";

            // TODO: GUID representing unique identifier for the transaction within the shopping cart (normally would be an order ID or similar)
            Guid orderId = Guid.NewGuid();

            input.TxnId = orderId.ToString().Substring(0, 16);
            Payment payment = new Payment();

            payment.TxnId  = input.TxnId;
            payment.CardId = cartId;

            RequestOutput output = WS.GenerateRequest(input);

            if (output.valid == "1")
            {
                payment.url = output.Url;
                _context.Payment.AddAsync(payment);
                _context.SaveChangesAsync();
                return(new RequestJson {
                    Url = output.Url
                });
            }

            return(new RequestJson {
                Url = output.Url
            });
        }
Exemple #8
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string pxPayUserId = SettingsHelper.Payment.UserId;
            string pxPayKey    = SettingsHelper.Payment.Key;

            try
            {
                PaymentDetails paymentDetails = ReadAndValidateInput();

                if (paymentDetails == null)
                {
                    lblMessage.Text = "There was an error processing your request, please try again.";
                    return;
                }

                PxPay wsPxPay = new PxPay(pxPayUserId, pxPayKey);

                RequestInput input = new RequestInput();
                input.AmountInput       = paymentDetails.Amount.ToString(CultureInfo.InvariantCulture);
                input.CurrencyInput     = "NZD";
                input.MerchantReference = paymentDetails.RefNumber;
                input.TxnData1          = paymentDetails.RefType;
                input.TxnData2          = paymentDetails.FullName;
                input.TxnData3          = paymentDetails.Phone;
                input.TxnType           = "Purchase";
                input.UrlFail           = CMS.DocumentEngine.DocumentContext.CurrentDocument.AbsoluteURL;
                input.UrlSuccess        = CMS.DocumentEngine.DocumentContext.CurrentDocument.AbsoluteURL;

                // TODO: GUID representing unique identifier for the transaction within the shopping cart (normally would be an order ID or similar)
                Guid orderId = Guid.NewGuid();
                input.TxnId = orderId.ToString().Substring(0, 16);

                RequestOutput output = wsPxPay.GenerateRequest(input);

                if (output.valid == "1")
                {
                    // Redirect user to payment page

                    Response.Redirect(output.Url);
                }
            }
            catch (Exception ex)
            {
                //log exception to Kentico
                EventLogProvider.LogException("Payment", "POST", ex, 0, "Payment Express Control", null);
                lblMessage.Text = "There was an error processing your request, please contact Vector.";
            }
        }
Exemple #9
0
    public Guid UpsertRequest(
        TInput input,
        MasterSection masterSection,
        RequestInput requestInputs,
        APIDbContext dbContext)
    {
        Guid id = Guid.NewGuid();

        var library = CreateLibrary(input, masterSection);

        dbContext.Set <TLibrary>().Add(library);
        dbContext.SaveChanges();

        var request = RequestHelper.CreateRequest(masterSection, library.Id, requestInputs, dbContext);

        dbContext.Requests.Add(request);
        dbContext.SaveChanges();
        return(request.Id);
    }
Exemple #10
0
        public RequestOutput OnTick(RequestInput requestInput, TimeManager timeManager)
        {
            state.SetInput(requestInput);
            var seed = Guid.NewGuid().GetHashCode();

            Logger.Debug($"seed: {seed}");
            try
            {
                var output = ai.GetCommand(state, 0, timeManager, new Random(seed));
                output.Debug += $". Command: {output.Command}. Seed: {seed}. Elapsed: {timeManager.Elapsed}. ElapsedGlobal: {timeManager.ElapsedGlobal}";
                return(output);
            }
            catch (Exception e)
            {
                #if LOCAL_RUNNER
                throw;
                #endif
                var direction = default(Direction);
                var curDir    = state.players[0].dir;
                if (curDir != null)
                {
                    for (var d = 3; d <= 5; d++)
                    {
                        var nd   = (Direction)(((int)curDir.Value + d) % 4);
                        var next = state.players[0].arrivePos.NextCoord(nd);
                        if (next != ushort.MaxValue)
                        {
                            direction = nd;
                            if (state.territory[next] == 0)
                            {
                                break;
                            }
                        }
                    }
                }
                return(new RequestOutput {
                    Command = direction, Debug = $"Failure. Seed: {seed}. Elapsed: {timeManager.Elapsed}. ElapsedGlobal: {timeManager.ElapsedGlobal}", Error = e.ToString()
                });
            }
        }
Exemple #11
0
    public InsertMutationResponse UpsertMethodB(
        LibraryInputB inputB,
        RequestInput requestInputs)
    {
        var ok        = false;
        var errors    = new List <string>();
        var requestId = default(Guid);

        if (requestInputs != null)
        {
            var @class        = new ClassB();
            var masterSection = _dbContext.MasterSections.SingleOrDefault(
                ms => ms.Name == requestInputs.MasterSection);
            requestId = @class.UpsertRequest(
                inputB,
                masterSection,
                requestInputs,
                _dbContext);
            ok = true;
        }
        return(new InsertMutationResponse(ok, errors, requestId));
    }
Exemple #12
0
            /// <summary>
            /// Generates the XML required for a GenerateRequest call
            /// </summary>
            /// <param name="input"></param>
            /// <returns></returns>
            private string GenerateRequestXml(RequestInput input)
            {
                StringWriter sw = new StringWriter();

                XmlWriterSettings settings = new XmlWriterSettings();

                settings.Indent = true;
                settings.NewLineOnAttributes = false;
                settings.OmitXmlDeclaration  = true;


                using (XmlWriter writer = XmlWriter.Create(sw, settings))
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement("GenerateRequest");
                    writer.WriteElementString("PxPayUserId", _PxPayUserId);
                    writer.WriteElementString("PxPayKey", _PxPayKey);

                    PropertyInfo[] properties = input.GetType().GetProperties();

                    foreach (PropertyInfo prop in properties)
                    {
                        if (prop.CanWrite)
                        {
                            string val = (string)prop.GetValue(input, null);

                            if (val != null || val != string.Empty)
                            {
                                writer.WriteElementString(prop.Name, val);
                            }
                        }
                    }
                    writer.WriteEndElement();
                    writer.WriteEndDocument();
                    writer.Flush();
                }

                return(sw.ToString());
            }
Exemple #13
0
        public IActionResult SendCompromisedProofs([FromBody] UnauthorizedUseDto unauthorizedUse)
        {
            ulong accountId = ulong.Parse(User.Identity.Name, CultureInfo.InvariantCulture);

            UserRootAttribute rootAttribute = _dataAccessService.GetUserAttributes(accountId).FirstOrDefault();

            UtxoPersistency utxoPersistency = _executionContextManager.ResolveUtxoExecutionServices(accountId);

            byte[] target = unauthorizedUse.Target.HexStringToByteArray();
            byte[] compromisedKeyImage = unauthorizedUse.KeyImage.HexStringToByteArray();
            byte[] issuer  = rootAttribute.Source.HexStringToByteArray();
            byte[] assetId = rootAttribute.AssetId;
            byte[] originalBlindingFactor = rootAttribute.OriginalBlindingFactor;
            byte[] originalCommitment     = rootAttribute.OriginalCommitment;
            byte[] lastTransactionKey     = rootAttribute.LastTransactionKey;
            byte[] lastBlindingFactor     = rootAttribute.LastBlindingFactor;
            byte[] lastCommitment         = rootAttribute.LastCommitment;
            byte[] lastDestinationKey     = rootAttribute.LastDestinationKey;

            RequestInput requestInput = new RequestInput
            {
                AssetId = assetId,
                EligibilityBlindingFactor = originalBlindingFactor,
                EligibilityCommitment     = originalCommitment,
                Issuer = issuer,
                PrevAssetCommitment = lastCommitment,
                PrevBlindingFactor  = lastBlindingFactor,
                PrevDestinationKey  = lastDestinationKey,
                PrevTransactionKey  = lastTransactionKey,
                Target = target
            };

            OutputModel[] outputModels        = _gatewayService.GetOutputs(_portalConfiguration.RingSize + 1);
            byte[][]      issuanceCommitments = _gatewayService.GetIssuanceCommitments(issuer, _portalConfiguration.RingSize + 1);
            RequestResult requestResult       = utxoPersistency.TransactionsService.SendCompromisedProofs(requestInput, compromisedKeyImage, outputModels, issuanceCommitments).Result;

            return(Ok(requestResult.Result));
        }
Exemple #14
0
 public RequestOutput GenerateRequest(RequestInput input)
 {
     RequestOutput result = new RequestOutput(SubmitXml(GenerateRequestXml(input)));
     return result;
 }
Exemple #15
0
        public IActionResult CreateDpsUI([FromBody] DpsInputDto dpsInput)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Invalid input!"));
            }
            var orderId   = dpsInput.OrderId;
            var returnUrl = dpsInput.ReturnUrl;

            var    siteName          = _config["CurrentSite"];
            string host_url          = "http://" + HttpContext.Request.Host + siteName;
            string host_url1         = _config["ApiUrl"] + siteName; // "http://api171.gpos.nz/dollaritems";
            string sReturnUrlFail    = host_url1 + "/api/dps/result?t=result&ret=fail&orderId=" + orderId;
            string sReturnUrlSuccess = host_url1 + "/api/dps/result?action=paymentSuccess&orderId=" + orderId;

            //PxPayUserId = _contextf.Settings.Where(s => s.Cat == "DPS" && s.Name == "PxPayUserId").FirstOrDefault().Value;
            //PxPayKey = _contextf.Settings.Where(s => s.Cat == "DPS" && s.Name == "PxPayKey").FirstOrDefault().Value;
            //sServiceUrl = _contextf.Settings.Where(s => s.Cat == "DPS" && s.Name == "sServiceUrl").FirstOrDefault().Value;
            //if (PxPayUserId == null || PxPayKey == null || sServiceUrl == null)
            //{
            //    PxPayUserId = Startup.Configuration["PxPayUserId"];
            //    PxPayKey = Startup.Configuration["PxPayKey"];
            //    sServiceUrl = Startup.Configuration["sServiceUrl"];
            //}
            //get order total

            var order = _context.Orders.Where(o => o.Id == Convert.ToInt32(orderId))
                        .Join(_context.Invoice,
                              o => o.InvoiceNumber,
                              i => i.InvoiceNumber,
                              (o, i) => new { o.InvoiceNumber, o.Id, Total = i.Total ?? 0 }).FirstOrDefault();
            decimal orderAmount = 0;

            if (order != null)
            {
                orderAmount = order.Total;
            }
            else
            {
                return(BadRequest());
            }

            PxPay        WS    = new PxPay(sServiceUrl, PxPayUserId, PxPayKey);
            RequestInput input = new RequestInput();

            input.AmountInput       = Math.Round(orderAmount, 2).ToString();
            input.CurrencyInput     = "NZD";
            input.MerchantReference = orderId;
            input.TxnType           = "Purchase";
            input.UrlFail           = sReturnUrlFail;
            input.UrlSuccess        = sReturnUrlSuccess;
            input.TxnData1          = returnUrl;

            Guid newOrderId = Guid.NewGuid();

            input.TxnId = newOrderId.ToString().Substring(0, 16);
            RequestOutput output = WS.GenerateRequest(input);

            if (output.valid == "1")
            {
                var result = output.Url;
                return(Ok(result));
            }

            return(NotFound());
        }
Exemple #16
0
        public void SetInput(RequestInput input, string my = "i")
        {
            if (players == null)
            {
                players = new Player[input.players.Count];

                territory = new byte[Env.CELLS_COUNT];
                lines     = new byte[Env.Y_CELLS_COUNT * Env.X_CELLS_COUNT];

                undos = new UndoPool(players.Length);
            }

            isGameOver = false;

            capture.Init(players.Length);

            time        = input.tick_num;
            playersLeft = input.players.Count;

            for (var c = 0; c < Env.CELLS_COUNT; c++)
            {
                territory[c] = 0xFF;
                lines[c]     = 0;
            }

            var keys = new[] { my }.Concat(input.players.Keys.Where(k => k != my)).ToList();

            for (var i = 0; i < players.Length; i++)
            {
                var key = i < keys.Count ? keys[i] : "unknown";

                if (players[i] == null)
                {
                    players[i] = new Player();
                }

                if (!input.players.TryGetValue(key, out var playerData))
                {
                    players[i].status = PlayerStatus.Eliminated;
                }
                else
                {
                    var accel = 0;
                    if (playerData.bonuses.Any(b => b.type == BonusType.N))
                    {
                        accel++;
                    }
                    if (playerData.bonuses.Any(b => b.type == BonusType.S))
                    {
                        accel--;
                    }

                    var speed = accel == 0 ? Env.SPEED
                        : accel == -1 ? Env.SLOW_SPEED
                        : accel == 1 ? Env.NITRO_SPEED
                        : throw new InvalidOperationException();

                    var v          = playerData.position;
                    var arriveTime = 0;
                    while (!v.InCellCenter())
                    {
                        v += GetShift(playerData.direction ?? throw new InvalidOperationException(), speed);
                        arriveTime++;
                    }

                    players[i].arrivePos = v.ToCellCoords().ToCoord();
                    if (arriveTime == 0)
                    {
                        players[i].pos = players[i].arrivePos;
                    }
                    else
                    {
                        players[i].pos = players[i].arrivePos.NextCoord((Direction)(((int)(playerData.direction ?? throw new InvalidOperationException()) + 2) % 4));
                    }

                    players[i].status = playerData.direction == null && i != 0
                        ? PlayerStatus.Broken
                        : PlayerStatus.Active;

                    players[i].dir       = playerData.direction;
                    players[i].score     = playerData.score;
                    players[i].shiftTime = accel == 0 ? Env.TICKS_PER_REQUEST
                        : accel == -1 ? Env.SLOW_TICKS_PER_REQUEST
                        : accel == 1 ? Env.NITRO_TICKS_PER_REQUEST
                        : throw new InvalidOperationException();

                    players[i].arriveTime                = arriveTime;
                    players[i].slowLeft                  = playerData.bonuses.FirstOrDefault(b => b.type == BonusType.S)?.ticks ?? 0;
                    players[i].nitroLeft                 = playerData.bonuses.FirstOrDefault(b => b.type == BonusType.N)?.ticks ?? 0;
                    players[i].lineCount                 = playerData.lines.Length;
                    players[i].territory                 = playerData.territory.Length;
                    players[i].slowsCollected            = 0;
                    players[i].nitrosCollected           = 0;
                    players[i].sawsCollected             = 0;
                    players[i].killedBy                  = 0;
                    players[i].opponentTerritoryCaptured = 0;

                    for (var k = 0; k < playerData.lines.Length; k++)
                    {
                        var lv = playerData.lines[k].ToCellCoords().ToCoord();
                        players[i].line[k] = lv;
                        lines[lv]          = (byte)(lines[lv] | (1 << i));
                    }

                    for (var k = 0; k < playerData.territory.Length; k++)
                    {
                        var lv = playerData.territory[k].ToCellCoords().ToCoord();
                        territory[lv] = (byte)i;
                    }
                }
            }

            if (bonuses == null || bonuses.Length < input.bonuses.Length)
            {
                bonuses = new Bonus[input.bonuses.Length];
            }

            bonusCount = 0;
            for (var i = 0; i < input.bonuses.Length; i++)
            {
                bonuses[bonusCount++] = new Bonus(input.bonuses[i]);
            }

            V GetShift(Direction direction, int d) =>
            direction == Direction.Up ? V.Get(0, d)
                : direction == Direction.Down ? V.Get(0, -d)
                : direction == Direction.Right ? V.Get(d, 0)
                : direction == Direction.Left ? V.Get(-d, 0)
                : throw new InvalidOperationException($"Unknown direction: {direction}");
        }
Exemple #17
0
        public bool AutomationRequest(RequestInput _requestInput)
        {
            //string strExchangeTopic = ConfigurationManager.AppSettings["ExchangeTopicName"];
            //string strRoutingLevel = ConfigurationManager.AppSettings["RoutingSupport"];

            string     strExchangeTopic = string.Empty;
            string     strRoutingLevel  = string.Empty;
            string     routingKey       = string.Empty;
            BOTService client           = new BOTService();

            strExchangeTopic = "robot.x.automation";
            strRoutingLevel  = "ProfileLevel";

            DataTable dt = client.GetRQDetailsByName(_requestInput.AutomationGroupName, _requestInput.TenantName);

            if (dt.Rows.Count > 0)
            {
                string servername = dt.Rows[0][0].ToString();

                var factory = new ConnectionFactory()
                {
                };
                factory.UserName = dt.Rows[0][2].ToString();
                factory.Password = dt.Rows[0][3].ToString();
                factory.HostName = dt.Rows[0][0].ToString();
                factory.Port     = (int)dt.Rows[0][1];

                using (var connection = factory.CreateConnection())
                    using (var channel = connection.CreateModel())
                    {
                        _requestInput.UniqueRequestNumber = "MsgReqNo_" + DateTime.Now.Ticks.ToString();

                        if (strRoutingLevel == "ProfileLevel")
                        {
                            routingKey = _requestInput.TenantName + "." + _requestInput.AutomationGroupName;
                        }
                        else
                        {
                            routingKey = _requestInput.TenantName + "." + _requestInput.AutomationGroupName + "." + _requestInput.AutomationProcessName;
                        }

                        var props = channel.CreateBasicProperties();
                        props.DeliveryMode = 2; //persistent
                        props.Headers      = new Dictionary <string, object>();
                        props.Headers["source_message_id"] = "MsgReqNo_" + DateTime.Now.Ticks.ToString();

                        #region CalculateQueueDepth

                        #endregion CalculateQueueDepth

                        //var message = RobotLibrary.XMLHelper.Serialize(_requestInput);
                        var message = JsonConvert.SerializeObject(_requestInput);
                        var body    = Encoding.UTF8.GetBytes(message);
                        channel.BasicPublish(exchange: strExchangeTopic,
                                             routingKey: routingKey,
                                             basicProperties: props,
                                             body: body);
                    }
                return(true); //acknowledgement
            }
            return(false);
        }
Exemple #18
0
        public bool AutomationRequestForProcess(string action, string botname, string ProcessName, DataTable result, string chronExpression)
        {
            string UserId      = string.Empty;
            string BotId       = string.Empty;
            string Password    = string.Empty;
            string RobotPwd    = string.Empty;
            int    TenantId    = 0;
            int    GroupId     = 0;
            string ServerName  = string.Empty;
            string MachineName = string.Empty;
            int    PortNumber  = 0;

            BOTService botServiceClient = new BOTService();

            try
            {
                if ((result.Rows[0][1] != null) && (result.Rows[0][1] != System.DBNull.Value))
                {
                    UserId = (string)result.Rows[0][1];
                }
                if ((result.Rows[0][2] != null) && (result.Rows[0][2] != System.DBNull.Value))
                {
                    Password = (string)result.Rows[0][2];
                }
                if ((result.Rows[0][3] != null) && (result.Rows[0][3] != System.DBNull.Value))
                {
                    TenantId = (int)result.Rows[0][3];
                }
                if ((result.Rows[0][3] != null) && (result.Rows[0][3] != System.DBNull.Value))
                {
                    GroupId = (int)result.Rows[0][4];
                }
                if ((result.Rows[0][7] != null) && (result.Rows[0][7] != System.DBNull.Value))
                {
                    ServerName = (string)result.Rows[0][7];
                }
                if ((result.Rows[0][8] != null) && (result.Rows[0][8] != System.DBNull.Value))
                {
                    PortNumber = (int)result.Rows[0][8];
                }
                if ((result.Rows[0][10] != null) && (result.Rows[0][10] != System.DBNull.Value))
                {
                    MachineName = (string)result.Rows[0][10];
                }
                if ((result.Rows[0][11] != null) && (result.Rows[0][11] != System.DBNull.Value))
                {
                    BotId = (string)result.Rows[0][11];
                }
                if ((result.Rows[0][12] != null) && (result.Rows[0][12] != System.DBNull.Value))
                {
                    RobotPwd = (string)result.Rows[0][12];
                }
                string message = action + "!#~=~!#" + botname + "!#~=~!#" + BotId + "!#~=~!#" + RobotPwd + "!#~=~!#" + TenantId + "!#~=~!#" + GroupId + "!#~=~!#" + "robot.q.Process" + "!#~=~!#" + chronExpression;

                var factory = new ConnectionFactory()
                {
                    HostName = ServerName
                };
                factory.UserName = UserId;
                factory.Password = Password;
                using (var connection = factory.CreateConnection())
                    using (var channel = connection.CreateModel())
                    {
                        //var props = channel.CreateBasicProperties();
                        //props.DeliveryMode = 1; //non persistent
                        //props.Headers = new Dictionary<string, object>();

                        //Logger.Log.Logger.LogData("ScheduleAdded", Logger.LogLevel.Debug);

                        /*load Generator Code*/
                        if (action == "Start" || "schedule" == action)
                        {
                            try
                            {
                                ConnectionFactory factory1 = new ConnectionFactory();

                                factory1.HostName = "localhost";
                                factory1.UserName = "******";
                                factory1.Password = "******";

                                using (var connection1 = factory.CreateConnection())
                                {
                                    using (var channel1 = connection.CreateModel())
                                    {
                                        //channel1.QueuePurge("robot.q.automation");
                                    }
                                }
                                //BOTService AutomationRequest = new BOTService();

                                RequestInput _requestInput = new RequestInput();

                                _requestInput.TenantName            = "InnoWise";                   // need to remove Hardcoding.
                                _requestInput.AutomationGroupName   = "Default";
                                _requestInput.AutomationProcessName = ProcessName;
                                List <string> lstSearchParam = new List <string>();
                                lstSearchParam.Add("SearchField1");
                                lstSearchParam.Add("Infosys Ltd.");
                                _requestInput.InputSearchParameters      = lstSearchParam;
                                _requestInput.RequestNumber              = "100";
                                _requestInput.RequestTimeoutSLAInSeconds = 100000;
                                AutomationRequest(_requestInput);
                            }
                            catch (Exception e)
                            {
                            }
                        }


                        //BOTService botServiceClient = new BOTService();
                        int result1        = botServiceClient.PiyushLogs("Process Started By Piyush in Hello Job");
                        int ScheduleStatus = botServiceClient.CreateScheduleStatus("robot.q.Process", botname, chronExpression, "STARTED", GroupId, TenantId, DateTime.Now.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"), "");

                        var props = channel.CreateBasicProperties();
                        props.DeliveryMode = 1; //non persistent
                        props.Headers      = new Dictionary <string, object>();

                        var body = Encoding.UTF8.GetBytes(message);
                        channel.BasicPublish(exchange: "",
                                             routingKey: MachineName,
                                             basicProperties: props,
                                             body: body);
                    }
                return(true); //acknowledgement
            }
            catch (Exception ex)
            {
                int ScheduleStatus = botServiceClient.CreateScheduleStatus("robot.q.Process", botname, chronExpression, "ERROR", GroupId, TenantId, DateTime.Now.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"), DateTime.Now.ToLocalTime().ToString());
                int ScheduleError  = botServiceClient.PiyushLogs("Error in HelloJob : " + ex.Message);
                return(false);
            }
        }
            /// <summary>
            ///
            /// </summary>
            /// <param name="input"></param>
            /// <returns></returns>
            public RequestOutput GenerateRequest(RequestInput input)
            {
                RequestOutput result = new RequestOutput(SubmitXml(GenerateRequestXml(input)));

                return(result);
            }
Exemple #20
0
	public static Guid UpsertRequest(
	  IInput inputg,
	  MasterSection masterSection,
	  RequestInput requestInputs,
	  APIDbContext dbContext