void ProcessResult(ApiInfo rpInfo)
        {
            var rData = (RawExpeditionResult)rpInfo.Data;
            var rFleet = KanColleGame.Current.Port.Fleets[int.Parse(rpInfo.Parameters["api_deck_id"])];
            var rExpedition = rFleet.ExpeditionStatus.Expedition ?? KanColleGame.Current.MasterInfo.GetExpeditionFromName(rData.Name);
            var rMaterials = rData.Result != 0 ? rData.Materials.ToObject<int[]>() : null;

            using (var rCommand = Connection.CreateCommand())
            {
                rCommand.CommandText = "INSERT INTO expedition(time, result, expedition, fuel, bullet, steel, bauxite, item1, item1_count, item2, item2_count) " +
                    "VALUES(@time, @result, @expedition, @fuel, @bullet, @steel, @bauxite, @item1, @item1_count, @item2, @item2_count);";
                rCommand.Parameters.AddWithValue("@time", rpInfo.Timestamp);
                rCommand.Parameters.AddWithValue("@result", (int)rData.Result);
                rCommand.Parameters.AddWithValue("@expedition", rExpedition.ID);
                rCommand.Parameters.AddWithValue("@fuel", rMaterials != null ? rMaterials[0] : (int?)null);
                rCommand.Parameters.AddWithValue("@bullet", rMaterials != null ? rMaterials[1] : (int?)null);
                rCommand.Parameters.AddWithValue("@steel", rMaterials != null ? rMaterials[2] : (int?)null);
                rCommand.Parameters.AddWithValue("@bauxite", rMaterials != null ? rMaterials[3] : (int?)null);

                rCommand.Parameters.AddWithValue("@item1", GetItemID(rData.RewardItems[0], rData.Item1?.ID));
                rCommand.Parameters.AddWithValue("@item1_count", rData.Item1 != null ? rData.Item1.Count : (int?)null);
                rCommand.Parameters.AddWithValue("@item2", GetItemID(rData.RewardItems[1], rData.Item2?.ID));
                rCommand.Parameters.AddWithValue("@item2_count", rData.Item2 != null ? rData.Item2.Count : (int?)null);

                rCommand.ExecuteNonQuery();
            }
        }
        internal protected AerialCombatStage(BattleInfo rpOwner, ApiInfo rpInfo) : base(rpOwner)
        {
            var rRawData = rpInfo.Data as IAerialCombatSecondRound;

            AerialCombatFirstRound = new AerialCombatPhase(this, rRawData.AerialCombat, PhaseRound.First);
            AerialCombatSecondRound = new AerialCombatPhase(this, rRawData.AerialCombatSecondRound, PhaseRound.Second);
        }
Ejemplo n.º 3
0
        public override ApiInfo CancelPayment( Order order, IDictionary<string, string> settings )
        {
            ApiInfo apiInfo = null;

              try {
            order.MustNotBeNull( "order" );
            settings.MustNotBeNull( "settings" );
            settings.MustContainKey( "Vendor", "settings" );

            Dictionary<string, string> inputFields = new Dictionary<string, string>();

            inputFields[ "VPSProtocol" ] = "2.23";
            inputFields[ "TxType" ] = "CANCEL";
            inputFields[ "Vendor" ] = settings[ "Vendor" ];
            inputFields[ "VendorTxCode" ] = order.CartNumber;
            inputFields[ "VPSTxId" ] = order.TransactionInformation.TransactionId;
            inputFields[ "SecurityKey" ] = order.Properties[ "securityKey" ];

            IDictionary<string, string> responseFields = GetFields( MakePostRequest( GetMethodUrl( "CANCEL", settings ), inputFields ) );

            if ( responseFields[ "Status" ] == "OK" ) {
              apiInfo = new ApiInfo( order.TransactionInformation.TransactionId, PaymentState.Cancelled );
            } else {
              LoggingService.Instance.Log( "Sage pay(" + order.OrderNumber + ") - Error making API request: " + responseFields[ "StatusDetail" ] );
            }
              } catch ( Exception exp ) {
            LoggingService.Instance.Log( exp, "Sage pay(" + order.OrderNumber + ") - Cancel payment" );
              }

              return apiInfo;
        }
        public override void ProcessCore(ApiInfo rpInfo)
        {
            var rSortie = SortieInfo.Current;
            if (rSortie == null)
                return;

            rSortie.LandBaseAerialSupportRequests = rpInfo.Parameters.Where(r => r.Key.StartsWith("api_strike_point_")).SelectMany(r => r.Value.Split(',').Select(int.Parse)).Distinct().ToArray();
        }
        public override void ProcessCore(ApiInfo rpInfo, RawDay rpData)
        {
            if (Game.Practice == null)
                return;

            var rParticipantFleet = Game.Port.Fleets[int.Parse(rpInfo.Parameters["api_deck_id"])];

            Game.Practice.Battle = new BattleInfo(rpInfo.Timestamp, rParticipantFleet);
        }
        internal protected DayNormalStage(BattleInfo rpOwner, ApiInfo rpInfo) : base(rpOwner)
        {
            var rRawData = rpInfo.Data as RawDay;

            LandBaseAerialSupport = new LandBaseAerialSupportPhase(this, rRawData.LandBaseAerialSupport);
            AerialCombat = new AerialCombatPhase(this, rRawData.AerialCombat);
            SupportingFire = new SupportingFirePhase(this, rRawData.SupportingFire);
            OpeningASW = new OpeningASWPhase(this, rRawData.OpeningASW);
            OpeningTorpedo = new TorpedoSalvoPhase(this, rRawData.OpeningTorpedoSalvo);

            ShellingFirstRound = new ShellingPhase(this, rRawData.ShellingFirstRound);
            ShellingSecondRound = new ShellingPhase(this, rRawData.ShellingSecondRound);

            ClosingTorpedo = new TorpedoSalvoPhase(this, rRawData.ClosingTorpedoSalvo);
        }
        internal protected EnemyCombinedFleetDay(BattleInfo rpOwner, ApiInfo rpInfo) : base(rpOwner)
        {
            var rRawData = rpInfo.Data as RawEnemyCombinedFleetDay;

            LandBaseAerialSupport = new LandBaseAerialSupportPhase(this, rRawData.LandBaseAerialSupport);
            AerialCombat = new AerialCombatPhase(this, rRawData.AerialCombat);
            SupportingFire = new SupportingFirePhase(this, rRawData.SupportingFire);
            OpeningASW = new OpeningASWPhase(this, rRawData.OpeningASW, true);
            OpeningTorpedo = new TorpedoSalvoPhase(this, rRawData.OpeningTorpedoSalvo, true);

            ShellingFirstRound = new ShellingPhase(this, rRawData.ShellingFirstRound, rpIsEnemyEscortFleet: true);
            ClosingTorpedo = new TorpedoSalvoPhase(this, rRawData.ClosingTorpedoSalvo, true);

            ShellingSecondRound = new ShellingPhase(this, rRawData.ShellingSecondRound);
            ShellingThirdRound = new ShellingPhase(this, rRawData.ShellingThirdRound);
        }
Ejemplo n.º 8
0
            public async Task ReturnsObjectIfNotNew()
            {
                var apiInfo = new ApiInfo(
                    new Dictionary <string, Uri>
                {
                    {
                        "next",
                        new Uri("https://api.github.com/repos/rails/rails/issues?page=4&per_page=5")
                    },
                    {
                        "last",
                        new Uri("https://api.github.com/repos/rails/rails/issues?page=131&per_page=5")
                    },
                    {
                        "first",
                        new Uri("https://api.github.com/repos/rails/rails/issues?page=1&per_page=5")
                    },
                    {
                        "prev",
                        new Uri("https://api.github.com/repos/rails/rails/issues?page=2&per_page=5")
                    }
                },
                    new List <string>
                {
                    "user"
                },
                    new List <string>
                {
                    "user",
                    "public_repo",
                    "repo",
                    "gist"
                },
                    "5634b0b187fd2e91e3126a75006cc4fa",
                    new RateLimit(100, 75, 1372700873)
                    );
                var connection = Substitute.For <IConnection>();

                connection.GetLastApiInfo().Returns(apiInfo);
                var client = new GitHubClient(connection);

                var result = client.GetLastApiInfo();

                Assert.NotNull(result);

                var temp = connection.Received(1).GetLastApiInfo();
            }
        void InitializeAnchorageRepairSnapshots(ApiInfo rpInfo)
        {
            if (r_AnchorageRepairSnapshotsInitialized)
            {
                return;
            }

            var rRepairingShips = Port.Fleets.Table.Values.SelectMany(r => r.AnchorageRepair.RepairingShips);
            var rAbsentShipIDs  = r_AnchorageRepairSnapshots.Keys.Except(rRepairingShips.Select(r => r.ID)).Where(r =>
            {
                Ship rShip;
                if (!Port.Ships.TryGetValue(r, out rShip))
                {
                    return(true);
                }

                return(rShip.HP.Current < rShip.HP.Maximum);
            }).ToArray();

            var rCommand = Connection.CreateCommand();

            if (rAbsentShipIDs.Length > 0)
            {
                rCommand.CommandText = "DELETE FROM anchorage_repair WHERE ship IN (" + string.Join(", ", rAbsentShipIDs) + ");";

                foreach (var rID in rAbsentShipIDs)
                {
                    r_AnchorageRepairSnapshots.Remove(rID);
                }
            }

            foreach (var rShip in rRepairingShips.Where(r => !r_AnchorageRepairSnapshots.ContainsKey(r.ID)))
            {
                r_AnchorageRepairSnapshots[rShip.ID] = new AnchorageRepairSnapshot(rShip, rShip.HP.Current, rShip.RepairTime.Value.TotalMinutes, rShip.RepairFuelConsumption, rShip.RepairSteelConsumption);
            }

            if (r_AnchorageRepairSnapshots.Count == 0)
            {
                r_AnchorageRepairStartTime = 0;

                rCommand.CommandText += "DELETE FROM common WHERE key = 'anchorage_repair_start_time';";
            }

            r_AnchorageRepairSnapshotsInitialized = true;

            rCommand.PostToTransactionQueue();
        }
Ejemplo n.º 10
0
        public override ApiInfo GetStatus(Order order, IDictionary <string, string> settings)
        {
            ApiInfo apiInfo = null;

            try
            {
                order.MustNotBeNull("order");
                settings.MustNotBeNull("settings");
                settings.MustContainKey("brq_websitekey", "settings");
                settings.MustContainKey("secret_key", "settings");
                settings.MustContainKey("test_mode", "settings");

                IDictionary <string, string> inputFields = new Dictionary <string, string>();
                inputFields["brq_websitekey"]  = settings["brq_websitekey"];
                inputFields["brq_transaction"] = order.TransactionInformation.TransactionId;

                Dictionary <string, string> response = MakeNVPGatewayRequest("TransactionStatus", inputFields, settings);

                /// todo: handle Refunds initated from Payment Plaza
                // these are not recognized here

                if (response.ContainsKey("BRQ_STATUSCODE"))
                {
                    if (response.ContainsKey("BRQ_RELATEDTRANSACTION_REFUND"))
                    {
                        if (response["BRQ_STATUSCODE"].Equals("190"))
                        {
                            apiInfo = new ApiInfo(order.TransactionInformation.TransactionId, PaymentState.Refunded);
                        }
                    }
                    else
                    {
                        if (response["BRQ_STATUSCODE"].Equals("190"))
                        {
                            apiInfo = new ApiInfo(order.TransactionInformation.TransactionId, PaymentState.Captured);
                        }
                    }
                }
            }
            catch (Exception exp)
            {
                LoggingService.Instance.Error <BuckarooPayments>(String.Concat("Buckaroo-Payments (", order.OrderNumber, ")"), exp);
            }

            return(apiInfo);
        }
Ejemplo n.º 11
0
        public override ApiInfo RefundPayment(Order order, IDictionary <string, string> settings)
        {
            ApiInfo apiInfo = null;

            try
            {
                order.MustNotBeNull("order");
                settings.MustNotBeNull("settings");
                settings.MustContainKey("brq_websitekey", "settings");
                settings.MustContainKey("secret_key", "settings");
                settings.MustContainKey("test_mode", "settings");

                //Check that the Iso code exists
                Currency currency = CurrencyService.Instance.Get(order.StoreId, order.CurrencyId);
                if (!Iso4217CurrencyCodes.ContainsKey(currency.IsoCode))
                {
                    throw new Exception("You must specify an ISO 4217 currency code for the " + currency.Name + " currency");
                }

                // request via the NVP gateway
                Dictionary <string, string> inputFields = new Dictionary <string, string>();
                inputFields["brq_websitekey"] = settings["brq_websitekey"];

                inputFields["brq_invoicenumber"]       = order.CartNumber;
                inputFields["brq_currency"]            = currency.IsoCode;
                inputFields["brq_culture"]             = currency.CultureName;
                inputFields["brq_amount_credit"]       = order.TotalPrice.Value.WithVat.ToString("0.00", CultureInfo.InvariantCulture);
                inputFields["brq_originaltransaction"] = order.TransactionInformation.TransactionId;

                Dictionary <string, string> response = MakeNVPGatewayRequest("TransactionRequest", inputFields, settings);
                if (response.ContainsKey("BRQ_STATUSCODE") && response.ContainsKey("BRQ_TRANSACTIONS"))
                {
                    // set the transaction id to the transaction that contains the refund (important)
                    // just return 'Refunded' (if you use 'PendingExternalSystem' the status 'Refunded' will not be shown in TeaCommerce)
                    apiInfo = new ApiInfo(response["BRQ_TRANSACTIONS"], PaymentState.Refunded);
                }

                LoggingService.Instance.Info <BuckarooPayments>(String.Concat("Buckaroo-Payments (", order.OrderNumber, ") - Refunded Order from back-end"));
                return(apiInfo);
            }
            catch (Exception exp)
            {
                LoggingService.Instance.Error <BuckarooPayments>(String.Concat("Buckaroo-Payments (", order.OrderNumber, ")"), exp);
            }
            return(apiInfo);
        }
        public override ApiInfo RefundPayment(Order order, IDictionary <string, string> settings)
        {
            ApiInfo apiInfo = null;

            try
            {
                order.MustNotBeNull("order");
                settings.MustNotBeNull("settings");
                settings.MustContainKey("SECURITY.SENDER", "settings");
                settings.MustContainKey("USER.LOGIN", "settings");
                settings.MustContainKey("USER.PWD", "settings");
                settings.MustContainKey("TRANSACTION.CHANNEL", "settings");
                settings.MustContainKey("TRANSACTION.MODE", "settings");

                Dictionary <string, string> inputFields = new Dictionary <string, string>();
                inputFields["REQUEST.VERSION"] = "1.0";

                inputFields["SECURITY.SENDER"]     = settings["SECURITY.SENDER"];
                inputFields["USER.LOGIN"]          = settings["USER.LOGIN"];
                inputFields["USER.PWD"]            = settings["USER.PWD"];
                inputFields["TRANSACTION.CHANNEL"] = settings["TRANSACTION.CHANNEL"];

                inputFields["PRESENTATION.CURRENCY"] = CurrencyService.Instance.Get(order.StoreId, order.CurrencyId).IsoCode;
                inputFields["PRESENTATION.AMOUNT"]   = (order.TransactionInformation.AmountAuthorized.Value).ToString("0.00", CultureInfo.InvariantCulture);

                inputFields["PAYMENT.CODE"] = "CC.RF";
                inputFields["IDENTIFICATION.REFERENCEID"] = order.TransactionInformation.TransactionId;
                inputFields["TRANSACTION.MODE"]           = settings["TRANSACTION.MODE"];

                IDictionary <string, string> responseKvps = MakePostRequest(settings, inputFields);
                if (responseKvps["PROCESSING.RESULT"] == "ACK")
                {
                    apiInfo = new ApiInfo(responseKvps["IDENTIFICATION.UNIQUEID"], PaymentState.Refunded);
                }
                else
                {
                    LoggingService.Instance.Warn <Axcess>("Axcess(" + order.OrderNumber + ") - Error making API request - PROCESSING.CODE: " + responseKvps["PROCESSING.CODE"]);
                }
            }
            catch (Exception exp)
            {
                LoggingService.Instance.Error <Axcess>("Axcess(" + order.OrderNumber + ") - Refund payment", exp);
            }

            return(apiInfo);
        }
        public override void ProcessCore(ApiInfo rpInfo, RawMapExploration rpData)
        {
            var rFleet     = Game.Port.Fleets[int.Parse(rpInfo.Parameters["api_deck_id"])];
            var rAreaID    = int.Parse(rpInfo.Parameters["api_maparea_id"]);
            var rAreaSubID = int.Parse(rpInfo.Parameters["api_mapinfo_no"]);

            var rSortie = new SortieInfo(rpInfo.Timestamp, rFleet, rAreaID * 10 + rAreaSubID);

            Game.Sortie = rSortie;

            var rMap = rSortie.Map;

            if (!rMap.IsEventMap)
            {
                Logger.Write(LoggingLevel.Info, string.Format(StringResources.Instance.Main.Log_Sortie,
                                                              rFleet.ID, rFleet.Name, rMap.MasterInfo.TranslatedName, rAreaID, rAreaSubID));
            }
            else
            {
                if (rMap.HP.Current == 9999 && rMap.HP.Maximum == 9999)
                {
                    rMap.HP.Set(rpData.EventMap.Maximum, rpData.EventMap.Current);
                }

                var rDifficulty = string.Empty;
                switch (rMap.Difficulty.Value)
                {
                case EventMapDifficulty.Easy:
                    rDifficulty = StringResources.Instance.Main.Map_Difficulty_Easy;
                    break;

                case EventMapDifficulty.Normal:
                    rDifficulty = StringResources.Instance.Main.Map_Difficulty_Normal;
                    break;

                case EventMapDifficulty.Hard:
                    rDifficulty = StringResources.Instance.Main.Map_Difficulty_Hard;
                    break;
                }

                Logger.Write(LoggingLevel.Info, string.Format(StringResources.Instance.Main.Log_Sortie_Event,
                                                              rFleet.ID, rFleet.Name, rMap.MasterInfo.TranslatedName, rAreaSubID, rDifficulty));
            }

            rSortie.Explore(rpInfo.Timestamp, rpData);
        }
Ejemplo n.º 14
0
        public SignInPage()
        {
            InitializeComponent();
            DataContext = TLContainer.Current.Resolve <SignInViewModel, ISignInDelegate>(this);

            Transitions = ApiInfo.CreateSlideTransition();

            Diagnostics.Text = $"Unigram " + GetVersion();

            ViewModel.PropertyChanged += OnPropertyChanged;



            var token = ElementCompositionPreview.GetElementVisual(Token);

            token.Opacity = 0;
        }
Ejemplo n.º 15
0
        internal protected DayNormalStage(BattleInfo rpOwner, ApiInfo rpInfo) : base(rpOwner)
        {
            var rRawData = rpInfo.Data as RawDay;

            LandBaseJetAircraftAerialSupport = new LandBaseJetAircraftAerialSupport(this, rRawData.LandBaseJetAircraftAerialSupport);
            JetAircraftAerialCombat          = new AerialCombatPhase(this, rRawData.JetAircraftAerialCombat);
            LandBaseAerialSupport            = new LandBaseAerialSupportPhase(this, rRawData.LandBaseAerialSupport);
            AerialCombat   = new AerialCombatPhase(this, rRawData.AerialCombat);
            SupportingFire = new SupportingFirePhase(this, rRawData.SupportingFire);
            OpeningASW     = new OpeningASWPhase(this, rRawData.OpeningASW);
            OpeningTorpedo = new TorpedoSalvoPhase(this, rRawData.OpeningTorpedoSalvo);

            ShellingFirstRound  = new ShellingPhase(this, rRawData.ShellingFirstRound);
            ShellingSecondRound = new ShellingPhase(this, rRawData.ShellingSecondRound);

            ClosingTorpedo = new TorpedoSalvoPhase(this, rRawData.ClosingTorpedoSalvo);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Retrieve an api service id from a layout api service id.
        /// </summary>
        /// <param name="api">An ApiInfo object.</param>
        /// <param name="apiService">A service id.</param>
        /// <returns>A service id.</returns>
        public static string GetApiService(
            this ApiInfo api,
            string apiService)
        {
            if (!api.IsValid() ||
                !apiService.IsValid())
            {
                return(null);
            }

            if (api.Id.ToLower().Equals(apiService.ToLower()))
            {
                return(apiService.ToPascalCase());
            }

            return(null);
        }
        internal protected CombinedFleetSTFDayNormalStage(BattleInfo rpOwner, ApiInfo rpInfo) : base(rpOwner)
        {
            var rRawData = rpInfo.Data as RawEnemyCombinedFleetDay;

            LandBaseAerialSupport = new LandBaseAerialSupportPhase(this, rRawData.LandBaseAerialSupport);
            AerialCombat          = new AerialCombatPhase(this, rRawData.AerialCombat);
            SupportingFire        = new SupportingFirePhase(this, rRawData.SupportingFire);
            OpeningASW            = new OpeningASWPhase(this, rRawData.OpeningASW, true);
            OpeningTorpedo        = new TorpedoSalvoPhase(this, rRawData.OpeningTorpedoSalvo, true, true);

            ShellingFirstRound  = new ShellingPhase(this, rRawData.ShellingFirstRound);
            ShellingSecondRound = new ShellingPhase(this, rRawData.ShellingSecondRound);

            ShellingThirdRound = new ShellingPhase(this, rRawData.ShellingThirdRound, true, true);

            ClosingTorpedo = new TorpedoSalvoPhase(this, rRawData.ClosingTorpedoSalvo, true, true);
        }
Ejemplo n.º 18
0
        void Repair(ApiInfo rpInfo)
        {
            var rShip      = Port.Ships[int.Parse(rpInfo.Parameters["api_ship_id"])];
            var rUseBucket = rpInfo.Parameters["api_highspeed"] == "1";

            var rCommand = Connection.CreateCommand();

            rCommand.CommandText =
                "INSERT OR IGNORE INTO sortie_consumption_detail(id, type) VALUES((SELECT max(id) FROM sortie_participant_ship WHERE ship_id = @ship_id AND type = 0), 1);" +
                "UPDATE sortie_consumption_detail SET fuel = coalesce(fuel, 0) + @fuel, steel = coalesce(steel, 0) + @steel, bucket = coalesce(bucket, 0) + @bucket WHERE id = (SELECT max(id) FROM sortie_participant_ship WHERE ship_id = @ship_id AND type = 0) AND type = 1;";
            rCommand.Parameters.AddWithValue("@ship_id", rShip.ID);
            rCommand.Parameters.AddWithValue("@fuel", rShip.RepairFuelConsumption);
            rCommand.Parameters.AddWithValue("@steel", rShip.RepairSteelConsumption);
            rCommand.Parameters.AddWithValue("@bucket", rUseBucket ? 1 : 0);

            rCommand.PostToTransactionQueue();
        }
Ejemplo n.º 19
0
        void ProcessFirstStage(ApiInfo rpInfo)
        {
            SetEnemy((RawBattleBase)rpInfo.Data);
            SetFormationAndEngagementForm(rpInfo);

            switch (rpInfo.Api)
            {
            case "api_req_sortie/battle":
            case "api_req_practice/battle":
                First = new DayNormalStage(this, rpInfo);
                break;

            case "api_req_battle_midnight/sp_midnight": First = new NightOnlyStage(this, rpInfo); break;

            case "api_req_sortie/airbattle":
            case "api_req_combined_battle/airbattle":
                First = new AerialCombatStage(this, rpInfo);
                break;

            case "api_req_sortie/ld_airbattle":
            case "api_req_combined_battle/ld_airbattle":
                First = new AerialAttackStage(this, rpInfo);
                break;

            case "api_req_combined_battle/battle": First = new CombinedFleetCTFDayNormalStage(this, rpInfo); break;

            case "api_req_combined_battle/battle_water": First = new CombinedFleetSTFDayNormalStage(this, rpInfo); break;

            case "api_req_combined_battle/sp_midnight": First = new CombinedFleetNightOnlyStage(this, rpInfo); break;

            case "api_req_combined_battle/ec_battle": First = new EnemyCombinedFleetDay(this, rpInfo); break;
            }

            First.Process(rpInfo);
            First.ProcessMVP();
            Result.Update(First, Second);

            IsInitialized = true;

            CurrentStage = First;
            OnPropertyChanged(nameof(First));
            OnPropertyChanged(nameof(CurrentStage));
            OnPropertyChanged(nameof(AerialCombat));
            OnPropertyChanged(nameof(IsInitialized));
        }
        public override ApiInfo GetStatus(Order order, IDictionary <string, string> settings)
        {
            ApiInfo apiInfo = null;

            try
            {
                try
                {
                    returnArray returnData = GetWannafindServiceClient(settings).checkTransaction(int.Parse(order.TransactionInformation.TransactionId), string.Empty, order.CartNumber, string.Empty, string.Empty);

                    PaymentState paymentState = PaymentState.Initialized;

                    switch (returnData.returncode)
                    {
                    case 5:
                        paymentState = PaymentState.Authorized;
                        break;

                    case 6:
                        paymentState = PaymentState.Captured;
                        break;

                    case 7:
                        paymentState = PaymentState.Cancelled;
                        break;

                    case 8:
                        paymentState = PaymentState.Refunded;
                        break;
                    }

                    apiInfo = new ApiInfo(order.TransactionInformation.TransactionId, paymentState);
                }
                catch (WebException)
                {
                    LoggingService.Instance.Warn <Wannafind>("Wannafind(" + order.OrderNumber + ") - Error making API request - Wrong credentials or IP address not allowed");
                }
            }
            catch (Exception exp)
            {
                LoggingService.Instance.Error <Wannafind>("Wannafind(" + order.OrderNumber + ") - Get status", exp);
            }

            return(apiInfo);
        }
Ejemplo n.º 21
0
        public override void ProcessCore(ApiInfo rpInfo, RawBattleResult rpData)
        {
            if (!Preference.Instance.Game.ShowDrop)
            {
                return;
            }

            var rMasterInfo = KanColleGame.Current.MasterInfo;

            string rDroppedShip = null;

            if (rpData.DroppedShip != null)
            {
                var rShip = rMasterInfo.Ships[rpData.DroppedShip.ID];

                if (rShip.Rarity < 4)
                {
                    rDroppedShip = rShip.TranslatedName;
                }
                else if (rShip.Rarity < 7)
                {
                    rDroppedShip = "[b]" + rShip.TranslatedName + "[/b]";
                }
                else
                {
                    rDroppedShip = "[b][color=yellow]" + rShip.TranslatedName + "[/color][/b]";
                }
            }

            if (rDroppedShip == null && rpData.DroppedItem == null)
            {
                return;
            }

            if (rDroppedShip != null && rpData.DroppedItem != null)
            {
                Logger.Write(LoggingLevel.Info, string.Format(StringResources.Instance.Main.Log_ShipAndItem_Dropped,
                                                              rDroppedShip, rMasterInfo.Items[rpData.DroppedItem.ID].TranslatedName));
            }
            else
            {
                Logger.Write(LoggingLevel.Info, string.Format(StringResources.Instance.Main.Log_ShipOrItem_Dropped,
                                                              rpData.DroppedShip != null ? rDroppedShip : rMasterInfo.Items[rpData.DroppedItem.ID].TranslatedName));
            }
        }
Ejemplo n.º 22
0
        private Stream GenerateAssemblyApiInfo(Stream assemblyStream)
        {
            // try loading the file as an assembly, and then create the API info
            try
            {
                assemblyStream.Position = 0;

                var config = new ApiInfoConfig
                {
                    IgnoreResolutionErrors = true
                };

                var info = new MemoryStream();

                using (var writer = new StreamWriter(info, UTF8NoBOM, DefaultSaveBufferSize, true))
                {
                    ApiInfo.Generate(assemblyStream, writer, config);
                }

                assemblyStream.Position = 0;
                info.Position           = 0;

                return(info);
            }
            catch (BadImageFormatException)
            {
            }

            // try loading as an API info
            try
            {
                assemblyStream.Position = 0;

                var xdoc = XDocument.Load(assemblyStream);

                assemblyStream.Position = 0;

                return(assemblyStream);
            }
            catch (XmlException)
            {
            }

            throw new InvalidOperationException("Input was in an incorrect format.");
        }
Ejemplo n.º 23
0
        public override ApiInfo CancelPayment(Order order, IDictionary <string, string> settings)
        {
            ApiInfo apiInfo = null;

            try {
                order.MustNotBeNull("order");
                settings.MustNotBeNull("settings");

                AnnulAuthorizationRequest request = new AnnulAuthorizationRequest(order.TransactionInformation.TransactionId, order.TransactionInformation.AmountAuthorized.Value);
                GetClient(settings).AnnulAuthorization(request);

                apiInfo = new ApiInfo(order.TransactionInformation.TransactionId, PaymentState.Cancelled);
            } catch (Exception exp) {
                LoggingService.Instance.Error <Paynova>("Paynova(" + order.OrderNumber + ") - Refund payment", exp);
            }

            return(apiInfo);
        }
Ejemplo n.º 24
0
        public override void ProcessCore(ApiInfo rpInfo, RawPort rpData)
        {
            Game.MasterInfo.WaitForInitialization();

            var rSortie = Game.Sortie;

            if (rSortie != null)
            {
                rSortie.ReturnTime = rpInfo.Timestamp;
                Game.RaiseReturnedFromSortie(rSortie);
                Game.Sortie = null;
            }

            Game.Practice = null;

            Game.Port.UpdateAdmiral(rpData.Basic);
            Game.Port.UpdatePort(rpData);
        }
Ejemplo n.º 25
0
        public override ApiInfo CancelPayment(Order order, IDictionary <string, string> settings)
        {
            ApiInfo apiInfo = null;

            try {
                order.MustNotBeNull("order");
                settings.MustNotBeNull("settings");
                settings.MustContainKey("apiKey", "settings");

                Dictionary <string, string> parameters = new Dictionary <string, string>();

                apiInfo = MakeApiRequest(order.TransactionInformation.TransactionId, settings["apiKey"], "cancel", parameters);
            } catch (Exception exp) {
                LoggingService.Instance.Error <QuickPay10>("QuickPay(" + order.OrderNumber + ") - Cancel payment", exp);
            }

            return(apiInfo);
        }
Ejemplo n.º 26
0
            /// <summary>
            /// 使用初始化
            /// </summary>
            internal static void Initialize(string path)
            {
                // 创建默认配置
                if (!System.IO.File.Exists(path))
                {
                    using (var cfg = new dpz3.File.ConfFile(path)) {
                        var group = cfg["Ecp"];
                        group["url"] = "https://v5.lywos.com";
                        group["id"]  = "";
                        group["key"] = "";
                        cfg.Save();
                    }
                }

                using (var cfg = new dpz3.File.ConfFile(path)) {
                    Ecp = new ApiInfo(cfg["Ecp"]);
                }
            }
Ejemplo n.º 27
0
        /// <summary>
        /// Retrieve all ViewModels from an api.
        /// </summary>
        /// <param name="api">An ApiInfo object.</param>
        /// <returns>A list of ViewModels id.</returns>
        public static List <string> GetApiViewModelsId(this ApiInfo api)
        {
            var viewModels = new List <string>();

            if (!api.IsValid())
            {
                return(viewModels);
            }

            if (api.Actions.IsValid())
            {
                viewModels = viewModels
                             .Union(api.Actions.GetApiActionListViewModelsId())
                             .ToList();
            }

            return(viewModels);
        }
Ejemplo n.º 28
0
        public async Task <IApiResponse <T> > GetByQueryAsync <T>(
            ApiInfo serviceInfo,
            string pathWithQuery,
            string token = null,
            params KeyValuePair <string, string>[] queryValues)
            where T : class
        {
            using (var content = new FormUrlEncodedContent(queryValues))
            {
                var query = await content.ReadAsStringAsync();

                var requestWithQuery = string.Concat(pathWithQuery, "?", query);

                var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestWithQuery);

                return(await SendAsync <T>(serviceInfo, httpRequestMessage, token));
            }
        }
Ejemplo n.º 29
0
        public override ApiInfo CancelPayment( Order order, IDictionary<string, string> settings )
        {
            ApiInfo apiInfo = null;

              try {
            order.MustNotBeNull( "order" );
            settings.MustNotBeNull( "settings" );

            AnnulAuthorizationRequest request = new AnnulAuthorizationRequest( order.TransactionInformation.TransactionId, order.TransactionInformation.AmountAuthorized.Value );
            GetClient( settings ).AnnulAuthorization( request );

            apiInfo = new ApiInfo( order.TransactionInformation.TransactionId, PaymentState.Cancelled );
              } catch ( Exception exp ) {
            LoggingService.Instance.Error<Paynova>( "Paynova(" + order.OrderNumber + ") - Refund payment", exp );
              }

              return apiInfo;
        }
Ejemplo n.º 30
0
        public string GetValue(ApiInfo type)
        {
            string[] input = raw.Replace("\"", "").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            string   nem   = Enum.GetName(typeof(ApiInfo), type).ToLower() + ":";

            if (input.Length > 0)
            {
                foreach (string s in input)
                {
                    if (s.StartsWith(nem))
                    {
                        string si = s.Replace(nem, "");
                        return(ConvertValue(si, type));
                    }
                }
            }
            return("");
        }
Ejemplo n.º 31
0
        public DefaultApisInfo()
        {
            InfoApi = new ApiInfo(
                ApiNames.InfoApiName,
                "query.cgi",
                1);

            AuthApi = new ApiInfo(
                ApiNames.AuthApiName,
                "auth.cgi",
                3,
                FileStationSessionName);

            DownloadStationTaskApi = new ApiInfo(
                ApiNames.DownloadStationTaskApiName,
                "DownloadStation/task.cgi",
                1,
                DownloadStationSessionName);

            FileStationCopyMoveApi = new ApiInfo(
                ApiNames.FileStationCopyMoveApiName,
                "entry.cgi",
                3,
                FileStationSessionName);

            FileStationExtractApi = new ApiInfo(
                ApiNames.FileStationExtractApiName,
                "entry.cgi",
                2,
                FileStationSessionName);

            FileStationListApi = new ApiInfo(
                ApiNames.FileStationListApiName,
                "entry.cgi",
                2,
                FileStationSessionName);

            FileStationUploadApi = new ApiInfo(
                ApiNames.FileStationUploadApiName,
                "entry.cgi",
                2,
                FileStationSessionName);
        }
Ejemplo n.º 32
0
    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        var routes = new List <ApiInfo>();

        var config   = GlobalConfiguration.Configuration;
        var explorer = config.Services.GetApiExplorer();

        foreach (ApiDescription apiDescription in explorer.ApiDescriptions)
        {
            ApiInfo apiInfo = new ApiInfo();
            apiInfo.HttpMethod   = apiDescription.HttpMethod.Method;
            apiInfo.RelativePath = apiDescription.RelativePath;
            routes.Add(apiInfo);
        }

        routes.Sort();
        gvRoutes.DataSource = routes;
        gvRoutes.DataBind();
    }
Ejemplo n.º 33
0
        public override ApiInfo CapturePayment(Order order, IDictionary <string, string> settings)
        {
            ApiInfo apiInfo = null;

            try
            {
                order.MustNotBeNull("order");
                settings.MustNotBeNull("settings");
                settings.MustContainKey("mode", "settings");
                settings.MustContainKey(settings["mode"] + "_api_login_id", "settings");
                settings.MustContainKey(settings["mode"] + "_transaction_key", "settings");

                // Configure AuthorizeNet
                ConfigureAuthorizeNet(settings);

                // Charge the transaction
                var transactionRequest = new createTransactionRequest
                {
                    transactionRequest = new transactionRequestType
                    {
                        transactionType = transactionTypeEnum.priorAuthCaptureTransaction.ToString(),
                        amount          = ToTwoDecimalPlaces(order.TotalPrice.Value.WithVat),
                        refTransId      = order.TransactionInformation.TransactionId
                    }
                };

                var controller = new createTransactionController(transactionRequest);
                controller.Execute();

                var transactionResponse = controller.GetApiResponse();
                if (transactionResponse != null &&
                    transactionResponse.messages.resultCode == messageTypeEnum.Ok)
                {
                    apiInfo = new ApiInfo(order.TransactionInformation.TransactionId, PaymentState.Captured);
                }
            }
            catch (Exception exp)
            {
                LoggingService.Instance.Error <AuthorizeNet>("Authorize.net(" + order.OrderNumber + ") - CapturePayment", exp);
            }

            return(apiInfo);
        }
        private Stream GenerateAssemblyApiInfo(Stream assemblyStream)
        {
            var config = new ApiInfoConfig
            {
                IgnoreResolutionErrors = true
            };

            var info = new MemoryStream();

            using (var writer = new StreamWriter(info, UTF8NoBOM, DefaultSaveBufferSize, true))
            {
                ApiInfo.Generate(assemblyStream, writer, config);
            }

            assemblyStream.Position = 0;
            info.Position           = 0;

            return(info);
        }
Ejemplo n.º 35
0
        private string GetResourceDescription(ApiInfo apiInfo, MixInfo mixInfo)
        {
            if (string.IsNullOrEmpty(apiInfo.Url))
            {
                var description        = mixInfo.ProviderMix[0].DnsName;
                var totalProviderCount = mixInfo.ProviderMix.Sum(p => p.ProviderCount);

                if (totalProviderCount > 1)
                {
                    description = $"{description} + {totalProviderCount - 1} more";
                }

                return(description);
            }
            else
            {
                return(apiInfo.Url);
            }
        }
Ejemplo n.º 36
0
        void ProcessBattleResult(ApiInfo rpInfo)
        {
            var rBattle       = BattleInfo.Current;
            var rCurrentStage = rBattle.CurrentStage;

            if (rCurrentStage.Friend == null)
            {
                return;
            }

            var rSunkShips = rCurrentStage.Friend.Where(r => r.State == BattleParticipantState.Sunk).Select(r => ((FriendShip)r.Participant).Ship).Where(r_SunkShips.Add).ToArray();

            if (rSunkShips.Length == 0)
            {
                return;
            }

            AddShipFate(rSunkShips, Fate.Sunk, rBattle.ID);
        }
Ejemplo n.º 37
0
        public override ApiInfo CancelPayment( Order order, IDictionary<string, string> settings )
        {
            ApiInfo apiInfo = null;

              try {
            XDocument doc = MakeApiRequest( "CANCEL", "DES", order, settings );
            string status = doc.XPathSelectElement( "//ncresponse" ).Attribute( "STATUS" ).Value;

            if ( status == "6" || status == "61" ) {
              apiInfo = new ApiInfo( doc.XPathSelectElement( "//ncresponse" ).Attribute( "PAYID" ).Value, PaymentState.Cancelled );
            } else {
              LoggingService.Instance.Warn<Ogone>( "Ogone - Error making API request - error code: " + doc.XPathSelectElement( "//ncresponse" ).Attribute( "NCERROR" ).Value + " - " + doc.XPathSelectElement( "//ncresponse" ).Attribute( "NCERRORPLUS" ).Value );
            }
              } catch ( Exception exp ) {
            LoggingService.Instance.Error<Ogone>( "Ogone(" + order.OrderNumber + ") - Cancel payment", exp );
              }

              return apiInfo;
        }
        public override ApiInfo CancelPayment(Order order, IDictionary <string, string> settings)
        {
            ApiInfo apiInfo = null;

            try
            {
                order.MustNotBeNull("order");
                settings.MustNotBeNull("settings");
                settings.MustContainKey("SECURITY.SENDER", "settings");
                settings.MustContainKey("USER.LOGIN", "settings");
                settings.MustContainKey("USER.PWD", "settings");
                settings.MustContainKey("TRANSACTION.CHANNEL", "settings");
                settings.MustContainKey("TRANSACTION.MODE", "settings");

                Dictionary <string, string> inputFields = new Dictionary <string, string>();
                inputFields["REQUEST.VERSION"] = "1.0";

                inputFields["SECURITY.SENDER"]     = settings["SECURITY.SENDER"];
                inputFields["USER.LOGIN"]          = settings["USER.LOGIN"];
                inputFields["USER.PWD"]            = settings["USER.PWD"];
                inputFields["TRANSACTION.CHANNEL"] = settings["TRANSACTION.CHANNEL"];

                inputFields["PAYMENT.CODE"] = "CC.RV";
                inputFields["IDENTIFICATION.REFERENCEID"] = order.TransactionInformation.TransactionId;
                inputFields["TRANSACTION.MODE"]           = settings["TRANSACTION.MODE"];

                IDictionary <string, string> responseKvps = MakePostRequest(settings, inputFields);
                if (responseKvps["PROCESSING.RESULT"] == "ACK")
                {
                    apiInfo = new ApiInfo(responseKvps["IDENTIFICATION.UNIQUEID"], PaymentState.Cancelled);
                }
                else
                {
                    LoggingService.Instance.Warn <Axcess>("Axcess(" + order.OrderNumber + ") - Error making API request - PROCESSING.CODE: " + responseKvps["PROCESSING.CODE"]);
                }
            }
            catch (Exception exp)
            {
                LoggingService.Instance.Error <Axcess>("Axcess(" + order.OrderNumber + ") - Cancel payment", exp);
            }

            return(apiInfo);
        }
Ejemplo n.º 39
0
            public void CanCloneWithNullETag()
            {
                var original = new ApiInfo(
                    new Dictionary <string, Uri>
                {
                    {
                        "next",
                        new Uri("https://api.github.com/repos/rails/rails/issues?page=4&per_page=5")
                    },
                    {
                        "last",
                        new Uri("https://api.github.com/repos/rails/rails/issues?page=131&per_page=5")
                    },
                    {
                        "first",
                        new Uri("https://api.github.com/repos/rails/rails/issues?page=1&per_page=5")
                    },
                    {
                        "prev",
                        new Uri("https://api.github.com/repos/rails/rails/issues?page=2&per_page=5")
                    }
                },
                    new List <string>
                {
                    "user"
                },
                    new List <string>(),
                    null,
                    new RateLimit(100, 75, 1372700873)
                    );

                var clone = original.Clone();

                Assert.NotNull(clone);
                Assert.Equal(4, clone.Links.Count);
                Assert.Equal(1, clone.OauthScopes.Count);
                Assert.Equal(0, clone.AcceptedOauthScopes.Count);
                Assert.Null(clone.Etag);
                Assert.Equal(100, clone.RateLimit.Limit);
                Assert.Equal(75, clone.RateLimit.Remaining);
                Assert.Equal(1372700873, clone.RateLimit.ResetAsUtcEpochSeconds);
            }
        static void ProcessCore(ApiSession rpSession)
        {
            var rApi = rpSession.DisplayUrl;
            var rResponse = rpSession.ResponseBodyString;

            try
            {
                var rContent = rResponse.Replace("svdata=", string.Empty);

                ApiParserBase rParser;
                if (!rContent.IsNullOrEmpty() && rContent.StartsWith("{") && r_Parsers.TryGetValue(rApi, out rParser))
                {
                    var rJson = JObject.Parse(rContent);

                    var rResultCode = (int)rJson["api_result"];
                    if (rResultCode != 1)
                    {
                        Logger.Write(LoggingLevel.Error, string.Format(StringResources.Instance.Main.Log_Exception_API_Failed, rApi, rResultCode));
                        return;
                    }

                    var rData = new ApiInfo(rpSession, rApi, rpSession.Parameters, rJson);

                    rParser.Process(rData);
                }
            }
            catch (AggregateException e) when (e.InnerExceptions.Count == 1)
            {
                Logger.Write(LoggingLevel.Error, string.Format(StringResources.Instance.Main.Log_Exception_API_ParseException, e.InnerExceptions[0].Message));

                rpSession.ErrorMessage = e.ToString();
                HandleException(rpSession, e);
            }
            catch (Exception e)
            {
                Logger.Write(LoggingLevel.Error, string.Format(StringResources.Instance.Main.Log_Exception_API_ParseException, e.Message));

                rpSession.ErrorMessage = e.ToString();
                HandleException(rpSession, e);
            }
        }
Ejemplo n.º 41
0
        public override ApiInfo CancelPayment( Order order, IDictionary<string, string> settings )
        {
            ApiInfo apiInfo = null;

              try {
            try {
              int returnCode = GetWannafindServiceClient( settings ).cancelTransaction( int.Parse( order.TransactionInformation.TransactionId ) );
              if ( returnCode == 0 ) {
            apiInfo = new ApiInfo( order.TransactionInformation.TransactionId, PaymentState.Cancelled );
              } else {
            LoggingService.Instance.Log( "Wannafind(" + order.OrderNumber + ") - Error making API request - Error code: " + returnCode );
              }
            } catch ( WebException ) {
              LoggingService.Instance.Log( "Wannafind(" + order.OrderNumber + ") - Error making API request - Wrong credentials or IP address not allowed" );
            }
              } catch ( Exception exp ) {
            LoggingService.Instance.Log( exp, "Wannafind(" + order.OrderNumber + ") - Cancel payment" );
              }

              return apiInfo;
        }
 public void Subscription(ApiInfo rpInfo)
 {
     try
     {
         r_Action(rpInfo);
     }
     catch (SQLiteException e) when (e.ResultCode == SQLiteErrorCode.Error && RecordService.Instance.HistoryCommandTexts.Count > 0)
     {
         Logger.Write(LoggingLevel.Error, string.Format(StringResources.Instance.Main.Log_Exception_API_ParseException, e.Message));
         RecordService.Instance.HandleException(rpInfo.Session, e);
     }
     catch (AggregateException e) when (e.InnerExceptions.Count == 1)
     {
         Logger.Write(LoggingLevel.Error, string.Format(StringResources.Instance.Main.Log_Exception_API_ParseException, e.InnerExceptions[0].Message));
         RecordService.Instance.HandleException(rpInfo.Session, e);
     }
     catch (Exception e)
     {
         Logger.Write(LoggingLevel.Error, string.Format(StringResources.Instance.Main.Log_Exception_API_ParseException, e.Message));
         ApiParserManager.HandleException(rpInfo.Session, e);
     }
 }
Ejemplo n.º 43
0
        public override ApiInfo CancelPayment( Order order, IDictionary<string, string> settings )
        {
            ApiInfo apiInfo = null;

              try {
            order.MustNotBeNull( "order" );
            settings.MustNotBeNull( "settings" );
            settings.MustContainKey( "merchantnumber", "settings" );

            int ePayResponse = 0;

            if ( GetEPayServiceClient().delete( int.Parse( settings[ "merchantnumber" ] ), long.Parse( order.TransactionInformation.TransactionId ), string.Empty, settings.ContainsKey( "webservicepassword" ) ? settings[ "webservicepassword" ] : string.Empty, ref ePayResponse ) ) {
              apiInfo = new ApiInfo( order.TransactionInformation.TransactionId, PaymentState.Cancelled );
            } else {
              LoggingService.Instance.Warn<ePay>( "ePay(" + order.OrderNumber + ") - Error making API request - error code: " + ePayResponse );
            }
              } catch ( Exception exp ) {
            LoggingService.Instance.Error<ePay>( "ePay(" + order.OrderNumber + ") - Cancel payment", exp );
              }

              return apiInfo;
        }
Ejemplo n.º 44
0
        internal void Process(ApiInfo rpInfo, BattleStage rpFirstStage = null)
        {
            var rData = rpInfo.Data as RawBattleBase;
            var rCombinedFleetData = rData as IRawCombinedFleet;

            FriendAndEnemy = new BattleParticipantSnapshot[rCombinedFleetData == null ? 12 : 24];

            for (var i = 1; i < rData.CurrentHPs.Length; i++)
                if (rData.MaximumHPs[i] != -1)
                    FriendAndEnemy[i - 1] = new BattleParticipantSnapshot(rData.MaximumHPs[i], rData.CurrentHPs[i]);

            FriendMain = FriendAndEnemy.Take(6).TakeWhile(r => r != null).ToArray();
            for (var i = 0; i < FriendMain.Count; i++)
                FriendMain[i].Participant = Owner.Participants.FriendMain[i];

            EnemyMain = FriendAndEnemy.Skip(6).TakeWhile(r => r != null).ToArray();
            for (var i = 0; i < EnemyMain.Count; i++)
                EnemyMain[i].Participant = Owner.Participants.EnemyMain[i];

            if (rCombinedFleetData != null)
            {
                BattleParticipantSnapshot[] rFriendAndEnemyEscort;

                if (rpFirstStage == null)
                    rFriendAndEnemyEscort = rCombinedFleetData.EscortFleetCurrentHPs.Zip(rCombinedFleetData.EscortFleetMaximumHPs,
                        (rpCurrent, rpMaximum) => rpMaximum != -1 ? new BattleParticipantSnapshot(rpMaximum, rpCurrent) : null).Skip(1).ToArray();
                else
                {
                    IEnumerable<BattleParticipantSnapshot> rFriendEscort = rpFirstStage.FriendEscort;
                    if (rFriendEscort == null)
                        rFriendEscort = Enumerable.Repeat<BattleParticipantSnapshot>(null, 6);

                    IEnumerable<BattleParticipantSnapshot> rEnemyEscort = rpFirstStage.EnemyEscort;
                    if (rEnemyEscort == null)
                        rEnemyEscort = Enumerable.Repeat<BattleParticipantSnapshot>(null, 6);

                    rFriendAndEnemyEscort = rFriendEscort.Concat(rEnemyEscort).Select(r => r != null ? new BattleParticipantSnapshot(r.Maximum, r.Current) : null).ToArray();
                }

                if (rFriendAndEnemyEscort[0] != null)
                {
                    FriendEscort = rFriendAndEnemyEscort.Take(6).TakeWhile(r => r != null).ToArray();

                    for (var i = 0; i < FriendEscort.Count; i++)
                    {
                        FriendEscort[i].Participant = Owner.Participants.FriendEscort[i];
                        FriendAndEnemy[i + 12] = FriendEscort[i];
                    }
                }

                if ((rpFirstStage == null && rFriendAndEnemyEscort.Length > 6) || (rpFirstStage != null && rpFirstStage.EnemyEscort != null))
                {
                    EnemyEscort = rFriendAndEnemyEscort.Skip(6).ToArray();

                    for (var i = 0; i < EnemyEscort.Count; i++)
                    {
                        EnemyEscort[i].Participant = Owner.Participants.EnemyEscort[i];
                        FriendAndEnemy[i + 18] = EnemyEscort[i];
                    }
                }
            }

            if (FriendEscort == null)
                Friend = FriendMain;
            else
                Friend = FriendMain.Concat(FriendEscort).ToArray();

            if (EnemyEscort == null)
                Enemy = EnemyMain;
            else
                Enemy = EnemyMain.Concat(EnemyEscort).ToArray();

            foreach (var rPhase in Phases)
                rPhase.Process();

            if (!Owner.IsPractice)
                foreach (var rSnapshot in Friend)
                {
                    var rParticipant = (FriendShip)rSnapshot.Participant;
                    if (rSnapshot.State == BattleParticipantState.HeavilyDamaged && rParticipant.EquipedEquipment.Any(r => r.Info.Type == EquipmentType.DamageControl))
                    {
                        rParticipant.IsDamageControlConsumed = false;
                        rParticipant.IsDamageControlVisible = true;
                    }
                }
        }
Ejemplo n.º 45
0
        public override ApiInfo CapturePayment( Order order, IDictionary<string, string> settings )
        {
            ApiInfo apiInfo = null;

              try {
            order.MustNotBeNull( "order" );
            settings.MustNotBeNull( "settings" );
            settings.MustContainKey( "Vendor", "settings" );

            Dictionary<string, string> inputFields = new Dictionary<string, string>();

            Guid vendorTxCode = Guid.NewGuid();

            inputFields[ "VPSProtocol" ] = "2.23";
            inputFields[ "TxType" ] = "AUTHORISE";
            inputFields[ "Vendor" ] = settings[ "Vendor" ];
            inputFields[ "VendorTxCode" ] = vendorTxCode.ToString();
            inputFields[ "Amount" ] = order.TransactionInformation.AmountAuthorized.Value.ToString( "0.00", CultureInfo.InvariantCulture );
            inputFields[ "Description" ] = settings[ "Description" ].Truncate( 100 );
            inputFields[ "RelatedVPSTxId" ] = order.TransactionInformation.TransactionId;
            inputFields[ "RelatedVendorTxCode" ] = order.CartNumber;
            inputFields[ "RelatedSecurityKey" ] = order.Properties[ "securityKey" ];
            inputFields[ "ApplyAVSCV2" ] = "0";

            IDictionary<string, string> responseFields = GetFields( MakePostRequest( GetMethodUrl( "AUTHORISE", settings ), inputFields ) );

            if ( responseFields[ "Status" ] == "OK" ) {
              order.Properties.AddOrUpdate( new CustomProperty( "vendorTxCode", vendorTxCode.ToString() ) { ServerSideOnly = true } );
              order.Properties.AddOrUpdate( new CustomProperty( "txAuthNo", responseFields[ "TxAuthNo" ] ) { ServerSideOnly = true } );
              order.Properties.AddOrUpdate( new CustomProperty( "securityKey", responseFields[ "SecurityKey" ] ) { ServerSideOnly = true } );
              order.Save();

              apiInfo = new ApiInfo( responseFields[ "VPSTxId" ], PaymentState.Captured );
            } else {
              LoggingService.Instance.Log( "Sage pay(" + order.OrderNumber + ") - Error making API request: " + responseFields[ "StatusDetail" ] );
            }
              } catch ( Exception exp ) {
            LoggingService.Instance.Log( exp, "Sage pay(" + order.OrderNumber + ") - Cancel payment" );
              }

              return apiInfo;
        }
            public async Task ReturnsObjectIfNotNew()
            {
                var apiInfo = new ApiInfo(
                                new Dictionary<string, Uri>
                                {
                                    {
                                        "next",
                                        new Uri("https://api.github.com/repos/rails/rails/issues?page=4&per_page=5")
                                    },
                                    {
                                        "last",
                                        new Uri("https://api.github.com/repos/rails/rails/issues?page=131&per_page=5")
                                    },
                                    {
                                        "first",
                                        new Uri("https://api.github.com/repos/rails/rails/issues?page=1&per_page=5")
                                    },
                                    {
                                        "prev",
                                        new Uri("https://api.github.com/repos/rails/rails/issues?page=2&per_page=5")
                                    }
                                },
                                new List<string>
                                {
                                    "user",
                                },
                                new List<string>
                                {
                                    "user", 
                                    "public_repo",
                                    "repo",
                                    "gist"
                                },
                                "5634b0b187fd2e91e3126a75006cc4fa",
                                new RateLimit(100, 75, 1372700873)
                            );
                var connection = Substitute.For<IConnection>();
                connection.GetLastApiInfo().Returns(apiInfo);
                var client = new GitHubClient(connection);

                var result = client.GetLastApiInfo();

                Assert.NotNull(result);

                var temp = connection.Received(1).GetLastApiInfo();
            }
        void ProcessResult(ApiInfo rpInfo)
        {
            if (!r_CurrentBattleID.HasValue)
                return;

            using (var rTransaction = Connection.BeginTransaction())
            {
                using (var rCommand = Connection.CreateCommand())
                {
                    rCommand.CommandText = "UPDATE battle_detail.battle SET result = @result WHERE id = @id;";
                    rCommand.Parameters.AddWithValue("@id", r_CurrentBattleID.Value);
                    rCommand.Parameters.AddWithValue("@result", CompressJson(rpInfo.Json["api_data"]));

                    if (rpInfo.Api == "api_req_practice/battle_result")
                    {
                        rCommand.CommandText += "UPDATE battle_detail.practice SET rank = @rank WHERE id = @id;";
                        rCommand.Parameters.AddWithValue("@rank", (int)((RawBattleResult)rpInfo.Data).Rank);
                    }

                    rCommand.ExecuteNonQuery();
                }

                var rStage = BattleInfo.Current.CurrentStage;
                ProcessHeavilyDamagedShip(rStage.FriendMain, ParticipantFleetType.Main);
                if (rStage.FriendEscort != null)
                    ProcessHeavilyDamagedShip(rStage.FriendEscort, ParticipantFleetType.Escort);

                rTransaction.Commit();
            }

            r_CurrentBattleID = null;
        }
        void ProcessPracticeFirstStage(ApiInfo rpInfo)
        {
            var rParticipantFleet = KanColleGame.Current.Port.Fleets[int.Parse(rpInfo.Parameters["api_deck_id"])];
            var rPractice = KanColleGame.Current.Practice;
            var rOpponent = rPractice.Opponent;
            r_CurrentBattleID = rPractice.Battle.ID;

            using (var rTransaction = Connection.BeginTransaction())
            using (var rCommand = Connection.CreateCommand())
            {
                var rCommandTextBuilder = new StringBuilder(1024);
                rCommandTextBuilder.Append("INSERT OR IGNORE INTO practice_opponent(id, name) VALUES(@opponent_id, @opponent_name);" +
                    "INSERT OR IGNORE INTO practice_opponent_comment(id, comment) VALUES(@opponent_comment_id, @opponent_coment);" +
                    "INSERT OR IGNORE INTO practice_opponent_fleet(id, name) VALUES(@opponent_fleet_name_id, @opponent_fleet_name);" +
                    "INSERT INTO practice(id, opponent, opponent_level, opponent_experience, opponent_rank, opponent_comment, opponent_fleet) VALUES(@battle_id, @opponent_id, @opponent_level, @opponent_experience, @opponent_rank, @opponent_comment_id, @opponent_fleet_name_id);" +
                    "INSERT INTO battle_detail.battle(id, first) VALUES(@battle_id, @first);");
                rCommand.Parameters.AddWithValue("@opponent_id", rOpponent.RawData.ID);
                rCommand.Parameters.AddWithValue("@opponent_name", rOpponent.Name);
                rCommand.Parameters.AddWithValue("@opponent_comment_id", rOpponent.RawData.CommentID ?? -1);
                rCommand.Parameters.AddWithValue("@opponent_coment", rOpponent.Comment);
                rCommand.Parameters.AddWithValue("@opponent_fleet_name_id", rOpponent.RawData.FleetNameID ?? -1);
                rCommand.Parameters.AddWithValue("@opponent_fleet_name", rOpponent.FleetName);
                rCommand.Parameters.AddWithValue("@opponent_level", rOpponent.Level);
                rCommand.Parameters.AddWithValue("@opponent_experience", rOpponent.RawData.Experience[0]);
                rCommand.Parameters.AddWithValue("@opponent_rank", (int)rOpponent.Rank);
                rCommand.Parameters.AddWithValue("@battle_id", r_CurrentBattleID.Value);
                rCommand.Parameters.AddWithValue("@first", CompressJson(rpInfo.Json["api_data"]));

                ProcessParticipantFleet(rCommandTextBuilder, rParticipantFleet, ParticipantFleetType.Main);

                rCommand.CommandText = rCommandTextBuilder.ToString();
                rCommand.ExecuteNonQuery();

                rTransaction.Commit();
            }
        }
Ejemplo n.º 49
0
        public override ApiInfo GetStatus( Order order, IDictionary<string, string> settings )
        {
            ApiInfo apiInfo = null;

              try {
            order.MustNotBeNull( "order" );
            settings.MustNotBeNull( "settings" );
            settings.MustContainKey( "apiusername", "settings" );
            settings.MustContainKey( "apipassword", "settings" );

            Dictionary<string, string> inputFields = new Dictionary<string, string>();

            try {
              string response = MakePostRequest( "https://@payment.architrade.com/cgi-adm/payinfo.cgi?transact=" + order.TransactionInformation.TransactionId, inputFields, new NetworkCredential( settings[ "apiusername" ], settings[ "apipassword" ] ) );

              Regex regex = new Regex( @"status=(\d+)" );
              string status = regex.Match( response ).Groups[ 1 ].Value;

              PaymentState paymentState = PaymentState.Initialized;

              switch ( status ) {
            case "2":
              paymentState = PaymentState.Authorized;
              break;
            case "5":
              paymentState = PaymentState.Captured;
              break;
            case "6":
              paymentState = PaymentState.Cancelled;
              break;
            case "11":
              paymentState = PaymentState.Refunded;
              break;
              }

              apiInfo = new ApiInfo( order.TransactionInformation.TransactionId, paymentState );
            } catch ( WebException ) {
              LoggingService.Instance.Log( "DIBS(" + order.OrderNumber + ") - Error making API request - wrong credentials" );
            }

              } catch ( Exception exp ) {
            LoggingService.Instance.Log( exp, "DIBS(" + order.OrderNumber + ") - Get status" );
              }

              return apiInfo;
        }
Ejemplo n.º 50
0
        public override ApiInfo GetStatus( Order order, IDictionary<string, string> settings )
        {
            ApiInfo apiInfo = null;

              try {
            order.MustNotBeNull( "order" );
            settings.MustNotBeNull( "settings" );
            settings.MustContainKey( "merchantnumber", "settings" );

            TransactionInformationType tit = new TransactionInformationType();
            int ePayResponse = 0;

            if ( GetEPayServiceClient().gettransaction( int.Parse( settings[ "merchantnumber" ] ), long.Parse( order.TransactionInformation.TransactionId ), settings.ContainsKey( "webservicepassword" ) ? settings[ "webservicepassword" ] : string.Empty, ref tit, ref ePayResponse ) ) {
              apiInfo = new ApiInfo( tit.transactionid.ToString( CultureInfo.InvariantCulture ), GetPaymentState( tit.status, tit.creditedamount ) );
            } else {
              LoggingService.Instance.Warn<ePay>( "ePay(" + order.OrderNumber + ") - Error making API request - error code: " + ePayResponse );
            }
              } catch ( Exception exp ) {
            LoggingService.Instance.Error<ePay>( "ePay(" + order.OrderNumber + ") - Get status", exp );
              }

              return apiInfo;
        }
Ejemplo n.º 51
0
        public override ApiInfo GetStatus( Order order, IDictionary<string, string> settings )
        {
            ApiInfo apiInfo = null;

              try {
            try {
              returnArray returnData = GetWannafindServiceClient( settings ).checkTransaction( int.Parse( order.TransactionInformation.TransactionId ), string.Empty, order.CartNumber, string.Empty, string.Empty );

              PaymentState paymentState = PaymentState.Initialized;

              switch ( returnData.returncode ) {
            case 5:
              paymentState = PaymentState.Authorized;
              break;
            case 6:
              paymentState = PaymentState.Captured;
              break;
            case 7:
              paymentState = PaymentState.Cancelled;
              break;
            case 8:
              paymentState = PaymentState.Refunded;
              break;
              }

              apiInfo = new ApiInfo( order.TransactionInformation.TransactionId, paymentState );

            } catch ( WebException ) {
              LoggingService.Instance.Log( "Wannafind(" + order.OrderNumber + ") - Error making API request - Wrong credentials or IP address not allowed" );
            }
              } catch ( Exception exp ) {
            LoggingService.Instance.Log( exp, "Wannafind(" + order.OrderNumber + ") - Get status" );
              }

              return apiInfo;
        }
Ejemplo n.º 52
0
        public override ApiInfo GetStatus( Order order, IDictionary<string, string> settings )
        {
            ApiInfo apiInfo = null;

              try {
            XDocument doc = GetStatusInternal( order, settings );
            string status = doc.XPathSelectElement( "//ncresponse" ).Attribute( "STATUS" ).Value;

            PaymentState paymentState = PaymentState.Error;
            switch ( status ) {
              case "5":
              case "51":
            paymentState = PaymentState.Authorized;
            break;
              case "9":
              case "91":
            paymentState = PaymentState.Captured;
            break;
              case "6":
              case "61":
            paymentState = PaymentState.Cancelled;
            break;
              case "7":
              case "71":
              case "8":
              case "81":
            paymentState = PaymentState.Refunded;
            break;
            }

            if ( paymentState != PaymentState.Error ) {
              apiInfo = new ApiInfo( doc.XPathSelectElement( "//ncresponse" ).Attribute( "PAYID" ).Value, paymentState );
            } else {
              LoggingService.Instance.Warn<Ogone>( "Ogone - Error making API request - error code: " + doc.XPathSelectElement( "//ncresponse" ).Attribute( "NCERROR" ).Value + " - " + doc.XPathSelectElement( "//ncresponse" ).Attribute( "NCERRORPLUS" ).Value );
            }

              } catch ( Exception exp ) {
            LoggingService.Instance.Error<Ogone>( "Ogone(" + order.OrderNumber + ") - Get status", exp );
              }

              return apiInfo;
        }
Ejemplo n.º 53
0
        public override ApiInfo RefundPayment( Order order, IDictionary<string, string> settings )
        {
            ApiInfo apiInfo = null;

              try {
            XDocument statusDoc = GetStatusInternal( order, settings );
            string statusStatus = statusDoc.XPathSelectElement( "//ncresponse" ).Attribute( "STATUS" ).Value;

            if ( statusStatus != "91" ) {
              XDocument doc = MakeApiRequest( "REFUND", "RFS", order, settings );
              string status = doc.XPathSelectElement( "//ncresponse" ).Attribute( "STATUS" ).Value;

              if ( status == "7" || status == "71" || status == "8" || status == "81" ) {
            apiInfo = new ApiInfo( doc.XPathSelectElement( "//ncresponse" ).Attribute( "PAYID" ).Value, PaymentState.Refunded );
              } else {
            LoggingService.Instance.Warn<Ogone>( "Ogone - Error making API request - error code: " + doc.XPathSelectElement( "//ncresponse" ).Attribute( "NCERROR" ).Value + " - " + doc.XPathSelectElement( "//ncresponse" ).Attribute( "NCERRORPLUS" ).Value );
              }
            } else {
              LoggingService.Instance.Warn<Ogone>( "Ogone - Error making API request - can't refund a transaction with status 91 - please try again in 5 minutes" );
            }
              } catch ( Exception exp ) {
            LoggingService.Instance.Error<Ogone>( "Ogone(" + order.OrderNumber + ") - Refund payment", exp );
              }

              return apiInfo;
        }
Ejemplo n.º 54
0
        public override ApiInfo RefundPayment( Order order, IDictionary<string, string> settings )
        {
            ApiInfo apiInfo = null;

              try {
            order.MustNotBeNull( "order" );
            settings.MustNotBeNull( "settings" );
            settings.MustContainKey( "merchant", "settings" );
            settings.MustContainKey( "md5k1", "settings" );
            settings.MustContainKey( "md5k2", "settings" );
            settings.MustContainKey( "apiusername", "settings" );
            settings.MustContainKey( "apipassword", "settings" );

            Dictionary<string, string> inputFields = new Dictionary<string, string>();

            string merchant = settings[ "merchant" ];
            inputFields[ "merchant" ] = merchant;

            string strAmount = ( order.TransactionInformation.AmountAuthorized.Value * 100M ).ToString( "0" );
            inputFields[ "amount" ] = strAmount;

            inputFields[ "orderid" ] = order.CartNumber;
            inputFields[ "transact" ] = order.TransactionInformation.TransactionId;
            inputFields[ "textreply" ] = "yes";

            Currency currency = CurrencyService.Instance.Get( order.StoreId, order.CurrencyId );
            if ( !Iso4217CurrencyCodes.ContainsKey( currency.IsoCode ) ) {
              throw new Exception( "You must specify an ISO 4217 currency code for the " + currency.Name + " currency" );
            }
            inputFields[ "currency" ] = Iso4217CurrencyCodes[ currency.IsoCode ];

            //MD5(key2 + MD5(key1 + “merchant=<merchant>&orderid=<orderid> &transact=<transact>&amount=<amount>"))
            string md5CheckValue = string.Empty;
            md5CheckValue += settings[ "md5k1" ];
            md5CheckValue += "merchant=" + merchant;
            md5CheckValue += "&orderid=" + order.CartNumber;
            md5CheckValue += "&transact=" + order.TransactionInformation.TransactionId;
            md5CheckValue += "&amount=" + strAmount;

            inputFields[ "md5key" ] = GenerateMD5Hash( settings[ "md5k2" ] + GenerateMD5Hash( md5CheckValue ) );

            try {
              string response = MakePostRequest( "https://payment.architrade.com/cgi-adm/refund.cgi", inputFields, new NetworkCredential( settings[ "apiusername" ], settings[ "apipassword" ] ) );

              Regex reg = new Regex( @"result=(\d*)" );
              string result = reg.Match( response ).Groups[ 1 ].Value;

              if ( result == "0" ) {
            apiInfo = new ApiInfo( order.TransactionInformation.TransactionId, PaymentState.Refunded );
              } else {
            LoggingService.Instance.Log( "DIBS(" + order.OrderNumber + ") - Error making API request - error message: " + result );
              }
            } catch ( WebException ) {
              LoggingService.Instance.Log( "DIBS(" + order.OrderNumber + ") - Error making API request - wrong credentials" );
            }

              } catch ( Exception exp ) {
            LoggingService.Instance.Log( exp, "DIBS(" + order.OrderNumber + ") - Refund payment" );
              }

              return apiInfo;
        }
        void ProcessSortieFirstStage(ApiInfo rpInfo)
        {
            var rSortie = SortieInfo.Current;
            r_CurrentBattleID = BattleInfo.Current.ID;

            using (var rTransaction = Connection.BeginTransaction())
            using (var rCommand = Connection.CreateCommand())
            {
                var rCommandTextBuilder = new StringBuilder(1024);
                rCommandTextBuilder.Append("INSERT INTO battle_detail.battle(id, first) VALUES(@battle_id, @first);");
                rCommand.Parameters.AddWithValue("@battle_id", r_CurrentBattleID.Value);
                rCommand.Parameters.AddWithValue("@first", CompressJson(rpInfo.Json["api_data"]));

                ProcessParticipantFleet(rCommandTextBuilder, rSortie.Fleet, ParticipantFleetType.Main);
                if (rSortie.EscortFleet != null)
                    ProcessParticipantFleet(rCommandTextBuilder, rSortie.EscortFleet, ParticipantFleetType.Escort);

                var rData = rpInfo.Data as RawDay;
                if (rData != null && rData.SupportingFireType != 0)
                {
                    var rSupportFire = rData.SupportingFire;
                    var rFleetID = (rSupportFire.SupportShelling?.FleetID ?? rSupportFire.AerialSupport?.FleetID).Value;
                    ProcessParticipantFleet(rCommandTextBuilder, KanColleGame.Current.Port.Fleets[rFleetID], ParticipantFleetType.SupportFire);
                }

                rCommand.CommandText = rCommandTextBuilder.ToString();
                rCommand.ExecuteNonQuery();

                rTransaction.Commit();
            }
        }
Ejemplo n.º 56
0
        public override ApiInfo CancelPayment( Order order, IDictionary<string, string> settings )
        {
            ApiInfo apiInfo = null;

              try {
            order.MustNotBeNull( "order" );
            settings.MustNotBeNull( "settings" );
            settings.MustContainKey( "merchant", "settings" );
            settings.MustContainKey( "md5k1", "settings" );
            settings.MustContainKey( "md5k2", "settings" );
            settings.MustContainKey( "apiusername", "settings" );
            settings.MustContainKey( "apipassword", "settings" );

            Dictionary<string, string> inputFields = new Dictionary<string, string>();

            string merchant = settings[ "merchant" ];
            inputFields[ "merchant" ] = merchant;

            inputFields[ "orderid" ] = order.CartNumber;
            inputFields[ "transact" ] = order.TransactionInformation.TransactionId;
            inputFields[ "textreply" ] = "yes";

            //MD5(key2 + MD5(key1 + “merchant=<merchant>&orderid=<orderid>&transact=<transact>))
            string md5CheckValue = string.Empty;
            md5CheckValue += settings[ "md5k1" ];
            md5CheckValue += "merchant=" + merchant;
            md5CheckValue += "&orderid=" + order.CartNumber;
            md5CheckValue += "&transact=" + order.TransactionInformation.TransactionId;

            inputFields[ "md5key" ] = GenerateMD5Hash( settings[ "md5k2" ] + GenerateMD5Hash( md5CheckValue ) );

            try {
              string response = MakePostRequest( "https://payment.architrade.com/cgi-adm/cancel.cgi", inputFields, new NetworkCredential( settings[ "apiusername" ], settings[ "apipassword" ] ) );

              Regex reg = new Regex( @"result=(\d*)" );
              string result = reg.Match( response ).Groups[ 1 ].Value;

              if ( result == "0" ) {
            apiInfo = new ApiInfo( order.TransactionInformation.TransactionId, PaymentState.Cancelled );
              } else {
            LoggingService.Instance.Log( "DIBS(" + order.OrderNumber + ") - Error making API request - error message: " + result );
              }
            } catch ( WebException ) {
              LoggingService.Instance.Log( "DIBS(" + order.OrderNumber + ") - Error making API request - wrong credentials" );
            }

              } catch ( Exception exp ) {
            LoggingService.Instance.Log( exp, "DIBS(" + order.OrderNumber + ") - Refund payment" );
              }

              return apiInfo;
        }
        void ProcessSecondStage(ApiInfo rpInfo)
        {
            if (!r_CurrentBattleID.HasValue)
                return;

            using (var rCommand = Connection.CreateCommand())
            {
                rCommand.CommandText = "UPDATE battle_detail.battle SET second = @second WHERE id = @id;";
                rCommand.Parameters.AddWithValue("@id", r_CurrentBattleID.Value);
                rCommand.Parameters.AddWithValue("@second", CompressJson(rpInfo.Json["api_data"]));

                rCommand.ExecuteNonQuery();
            }
        }
Ejemplo n.º 58
0
        public override ApiInfo GetStatus( Order order, IDictionary<string, string> settings )
        {
            ApiInfo apiInfo = null;

              try {
            order.MustNotBeNull( "order" );
            settings.MustNotBeNull( "settings" );
            settings.MustContainKey( "x_login", "settings" );
            settings.MustContainKey( "transactionKey", "settings" );

            GetTransactionDetailsResponseType result = GetAuthorizeNetServiceClient( settings ).GetTransactionDetails( new MerchantAuthenticationType { name = settings[ "x_login" ], transactionKey = settings[ "transactionKey" ] }, order.TransactionInformation.TransactionId );

            if ( result.resultCode == MessageTypeEnum.Ok ) {

              PaymentState paymentState = PaymentState.Initialized;
              switch ( result.transaction.transactionStatus ) {
            case "authorizedPendingCapture":
              paymentState = PaymentState.Authorized;
              break;
            case "capturedPendingSettlement":
            case "settledSuccessfully":
              paymentState = PaymentState.Captured;
              break;
            case "voided":
              paymentState = PaymentState.Cancelled;
              break;
            case "refundSettledSuccessfully":
            case "refundPendingSettlement":
              paymentState = PaymentState.Refunded;
              break;
              }

              apiInfo = new ApiInfo( result.transaction.transId, paymentState );
            } else {
              LoggingService.Instance.Log( "Authorize.net(" + order.OrderNumber + ") - Error making API request - error code: " + result.messages[ 0 ].code + " | description: " + result.messages[ 0 ].text );
            }

              } catch ( Exception exp ) {
            LoggingService.Instance.Log( exp, "Authorize.net(" + order.OrderNumber + ") - Get status" );
              }

              return apiInfo;
        }
Ejemplo n.º 59
0
        public override ApiInfo RefundPayment( Order order, IDictionary<string, string> settings )
        {
            ApiInfo apiInfo = null;

              try {
            order.MustNotBeNull( "order" );
            settings.MustNotBeNull( "settings" );
            settings.MustContainKey( "Vendor", "settings" );
            settings.MustContainKey( "Description", "settings" );

            Dictionary<string, string> inputFields = new Dictionary<string, string>();

            Guid vendorTxCode = Guid.NewGuid();

            inputFields[ "VPSProtocol" ] = "2.23";
            inputFields[ "TxType" ] = "REFUND";
            inputFields[ "Vendor" ] = settings[ "Vendor" ];
            inputFields[ "VendorTxCode" ] = vendorTxCode.ToString();
            inputFields[ "Amount" ] = order.TransactionInformation.AmountAuthorized.Value.ToString( "0.00", CultureInfo.InvariantCulture );
            //Check that the Iso code exists
            Currency currency = CurrencyService.Instance.Get( order.StoreId, order.CurrencyId );
            if ( !Iso4217CurrencyCodes.ContainsKey( currency.IsoCode ) ) {
              throw new Exception( "You must specify an ISO 4217 currency code for the " + currency.Name + " currency" );
            }
            inputFields[ "Currency" ] = currency.IsoCode;
            inputFields[ "Description" ] = settings[ "Description" ].Truncate( 100 );
            inputFields[ "RelatedVPSTxId" ] = order.TransactionInformation.TransactionId;
            inputFields[ "RelatedVendorTxCode" ] = order.Properties[ "vendorTxCode" ];
            inputFields[ "RelatedSecurityKey" ] = order.Properties[ "securityKey" ];
            inputFields[ "RelatedTxAuthNo" ] = order.Properties[ "txAuthNo" ];
            inputFields[ "ApplyAVSCV2" ] = "0";

            IDictionary<string, string> responseFields = GetFields( MakePostRequest( GetMethodUrl( "REFUND", settings ), inputFields ) );

            if ( responseFields[ "Status" ] == "OK" ) {
              order.Properties.AddOrUpdate( new CustomProperty( "vendorTxCode", vendorTxCode.ToString() ) { ServerSideOnly = true } );
              order.Properties.AddOrUpdate( new CustomProperty( "txAuthNo", responseFields[ "TxAuthNo" ] ) { ServerSideOnly = true } );
              order.Save();

              apiInfo = new ApiInfo( responseFields[ "VPSTxId" ], PaymentState.Refunded );
            } else {
              LoggingService.Instance.Log( "Sage pay(" + order.OrderNumber + ") - Error making API request: " + responseFields[ "StatusDetail" ] );
            }
              } catch ( Exception exp ) {
            LoggingService.Instance.Log( exp, "Sage pay(" + order.OrderNumber + ") - Refund payment" );
              }

              return apiInfo;
        }
Ejemplo n.º 60
0
            public async Task ReturnsObjectIfNotNew()
            {
                var apiInfo = new ApiInfo(
                                new Dictionary<string, Uri>
                                {
                                    {
                                        "next",
                                        new Uri("https://api.github.com/repos/rails/rails/issues?page=4&per_page=5")
                                    },
                                    {
                                        "last",
                                        new Uri("https://api.github.com/repos/rails/rails/issues?page=131&per_page=5")
                                    },
                                    {
                                        "first",
                                        new Uri("https://api.github.com/repos/rails/rails/issues?page=1&per_page=5")
                                    },
                                    {
                                        "prev",
                                        new Uri("https://api.github.com/repos/rails/rails/issues?page=2&per_page=5")
                                    }
                                },
                                new List<string>
                                {
                                    "user",
                                },
                                new List<string>
                                {
                                    "user",
                                    "public_repo",
                                    "repo",
                                    "gist"
                                },
                                "5634b0b187fd2e91e3126a75006cc4fa",
                                new RateLimit(100, 75, 1372700873)
                            );

                var httpClient = Substitute.For<IHttpClient>();

                // We really only care about the ApiInfo property...
                var expectedResponse = new Response(HttpStatusCode.OK, null, new Dictionary<string, string>(), "application/json")
                {
                    ApiInfo = apiInfo
                };

                httpClient.Send(Arg.Any<IRequest>(), Arg.Any<CancellationToken>())
                    .Returns(Task.FromResult<IResponse>(expectedResponse));

                var connection = new Connection(new ProductHeaderValue("OctokitTests"),
                    _exampleUri,
                    Substitute.For<ICredentialStore>(),
                    httpClient,
                    Substitute.For<IJsonSerializer>());

                connection.Get<PullRequest>(new Uri("https://example.com"), TimeSpan.MaxValue);

                var result = connection.GetLastApiInfo();

                // No point checking all of the values as they are tested elsewhere
                // Just provde that the ApiInfo is populated
                Assert.Equal(4, result.Links.Count);
                Assert.Equal(1, result.OauthScopes.Count);
                Assert.Equal(4, result.AcceptedOauthScopes.Count);
                Assert.Equal("5634b0b187fd2e91e3126a75006cc4fa", result.Etag);
                Assert.Equal(100, result.RateLimit.Limit);
            }