Ejemplo n.º 1
0
        public void UpdateCardPreviewList(CeQueryExModel cardQueryMdoel)
        {
            var dataSet = new DataSet();
            var sql     = GetModelSql(cardQueryMdoel);

            // 保存上次查询的实例
            MemoryQueryModel = cardQueryMdoel;
            DataManager.FillDataToDataSet(dataSet, sql);

            var previewModels = CardUtils.GetCardPreviewModels(dataSet);

            CardPreviewModels.Clear();
            RestrictUtils.GetRestrictCardList(previewModels, cardQueryMdoel.Restrict).ForEach(CardPreviewModels.Add);
            // 更新统计
            CardPreviewCountValue = "查询结果:" + CardPreviewModels.Count;
            OnPropertyChanged(nameof(CardPreviewCountValue));
            // 跟踪历史
            if (MemoryQueryModel.CeQueryModel.Number.Equals(string.Empty))
            {
                return;
            }
            var firstOrDefault = CardPreviewModels
                                 .Select((previewModel, index) => new { previewModel.Number, Index = index })
                                 .FirstOrDefault(i => i.Number.Equals(MemoryQueryModel.CeQueryModel.Number));

            if (null == firstOrDefault)
            {
                return;
            }
            var position = firstOrDefault.Index;

            if (position == -1)
            {
                return;
            }
            _selectedItem = CardPreviewModels[position];
        }
Ejemplo n.º 2
0
    void AddCardToBuild(Card card)
    {
        if (CurrentBuild.Count >= maxCards)
        {
            return;
        }

        if (currentPoints + card.Cost > maxPoints)
        {
            return;
        }

        int index = OneOfEach.IndexOf(card);

        if (index >= 0)
        {
            Card builtCard = CardList.SpawnCard(card);
            builtCard.transform.position = card.transform.position;
            builtCard.transform.rotation = card.transform.rotation;
            CardUtils.MoveCardTo(builtCard, BuildCorner.TransformPoint(new Vector3(CurrentBuild.Count * 0.15f, 0f, -CurrentBuild.Count * 0.01f)),
                                 Quaternion.LookRotation(-BuildCorner.forward));

            CurrentBuild.Add(builtCard);

            currentPoints  += card.Cost;
            PointsLeft.text = (maxPoints - currentPoints).ToString();          // + "/" + maxPoints.ToString();

            if (isP1)
            {
                DeckBuilds.P1Build.Add(MasterCardList.Cards[index]);
            }
            else
            {
                DeckBuilds.P2Build.Add(MasterCardList.Cards[index]);
            }
        }
    }
Ejemplo n.º 3
0
        private async Task <R4UCard> ParseOriginalCard(WikiCardContext context, WikiSetContext setContext)
        {
            var card         = new R4UCard();
            var mainInfoBox  = context.MainInfoBox;
            var extraInfoBox = context.ExtraInfoBox;

            card.Name    = new MultiLanguageString();
            card.Name.JP = mainInfoBox.GetValueOrDefault("kanji", mainInfoBox["name"]);
            card.Name.EN = mainInfoBox["name"];
            card.Type    = TranslateType(mainInfoBox["card type"]);
            card.Set     = setContext.Set;
            if (card.Type == CardType.Character)
            {
                card.Cost   = int.Parse(mainInfoBox["cost"]);
                card.ATK    = int.Parse(mainInfoBox["atk"]);
                card.DEF    = int.Parse(mainInfoBox["def"]);
                card.Traits = await ParseTraits(context.RawMainInfoBox["trait"], setContext);
            }
            if (extraInfoBox.TryGetValue("card flavor(s)", out var flavor))
            {
                card.Flavor    = new MultiLanguageString();
                card.Flavor.EN = flavor;
            }
            if (extraInfoBox.TryGetValue("card abilities", out var abilities))
            {
                card.Effect = TranslateEffect(abilities);
                card.Color  = CardUtils.InferFromEffect(card.Effect);
            }
            else
            {
                // Assumed. All Partner cards do not have effects, and vanilla cards have [Relaxing]
                card.Color = CardColor.Red;
            }

            return(card);
        }
Ejemplo n.º 4
0
        private async Task <DialogTurnResult> ProcessConfirmationStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var infoList = new List <RequestedInfo>();

            if (stepContext.GetValue <bool>(FROMNOTIFICATION))
            {
                var result = (bool)stepContext.Result;

                if (result)
                {
                    var requests = await PurchaseController.GetOrderRequests();

                    if (requests.Count == 0)
                    {
                        await stepContext.Context.SendActivityAsync("There's no pending orders to validate" +
                                                                    "you're done for today!");

                        return(await stepContext.EndDialogAsync(null, cancellationToken));
                    }
                    else if (requests.Count == 1)
                    {
                        return(await stepContext.NextAsync(requests[0].CartId, cancellationToken));
                    }
                    else
                    {
                        foreach (OrderRequest request in requests)
                        {
                            infoList.Add(await RequestedInfo.BuildRequestedInfoAsync(request.Cart, PrestashopApi));
                        }
                    }
                }
                else
                {
                    return(await stepContext.EndDialogAsync(null, cancellationToken));
                }
            }
            else
            {
                var words = ((string)stepContext.Options).Split(new char[] { ' ' }).ToList();

                var customers = (await PrestashopApi.GetCustomerByWords(words.ToFilterParameterList())).Customers;

                var carts = await PurchaseController.GetCartFromUserList(customers);

                foreach (Models.Cart cart in carts)
                {
                    infoList.Add(await RequestedInfo.BuildRequestedInfoAsync(cart, PrestashopApi));
                }
            }

            var attachments = CardUtils.RequestedListToCarousel(infoList);

            var reply = stepContext.Context.Activity.CreateReply();

            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
            reply.Attachments      = attachments;

            await stepContext.Context.SendActivityAsync(MessageFactory.Text(chooseMsg), cancellationToken);

            await stepContext.Context.SendActivityAsync(reply, cancellationToken);

            return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text("") }));
        }
Ejemplo n.º 5
0
        public void TestCardFromJsonFailure(string cardJsonString, string comment)
        {
            JObject cardJson = JObject.Parse(cardJsonString);

            Assert.Throws <ArgumentException>("cardObject", () => CardUtils.CardFromJson(cardJson));
        }
Ejemplo n.º 6
0
 public Attachment ToAttachment()
 {
     return(CardUtils.AdaptiveCardToAttachment(ToAdaptiveCard()));
 }
Ejemplo n.º 7
0
    /// <summary>
    /// 巴十 发牌
    /// </summary>
    /// <param name="number"></param>
    void dealBs()
    {
        if (pnumber >= plist.Count - 8)
        {
            //对牌进行排序
            CardManager.Instance.fList = CardUtils.GetInstance().sortlist(CardManager.Instance.fList, CardManager.Instance.color);

            CardManager.Instance.sList = CardUtils.GetInstance().sortlist(CardManager.Instance.sList, CardManager.Instance.color);

            CardManager.Instance.tList = CardUtils.GetInstance().sortlist(CardManager.Instance.tList, CardManager.Instance.color);

            //添加底牌
            for (int i = plist.Count - 8; i < plist.Count; i++)
            {
                //print("值:" +list[i].value + "--花色:" + list[i].color+"---i="+i);
                CardManager.Instance.blist.Add(plist[i]);
            }

            isSend = false;
            //标记牌已经发完
            CardManager.Instance.isSend = true;
            return;
        }
        //自己的牌
        if (pnumber % 4 == 0)
        {
            addPoker(plist[pnumber]);
        }
        //第二个人的牌
        else if (pnumber % 4 == 1)
        {
            cm.fList.Add(plist[pnumber]);
            //把抢庄的牌加入集合
            if (plist[pnumber].value == 10 && (plist[pnumber].color == 1 || plist[pnumber].color == 3))
            {
                cm.fRob.Add(new Poker(plist[pnumber].name, 2, plist[pnumber].color));
            }
            else if (plist[pnumber].value == 11)
            {
                cm.fRob.Add(new Poker(plist[pnumber].name, 1, plist[pnumber].color));
            }
        }
        //第三个人的牌
        else if (pnumber % 4 == 2)
        {
            cm.sList.Add(plist[pnumber]);
            //把抢庄的牌加入集合
            if (plist[pnumber].value == 10 && (plist[pnumber].color == 1 || plist[pnumber].color == 3))
            {
                cm.sRob.Add(new Poker(plist[pnumber].name, 2, plist[pnumber].color));
            }
            else if (plist[pnumber].value == 11)
            {
                cm.sRob.Add(new Poker(plist[pnumber].name, 1, plist[pnumber].color));
            }
        }
        //第四个人的牌
        else if (pnumber % 4 == 3)
        {
            cm.tList.Add(plist[pnumber]);
            //把抢庄的牌加入集合
            if (plist[pnumber].value == 10 && (plist[pnumber].color == 1 || plist[pnumber].color == 3))
            {
                cm.tRob.Add(new Poker(plist[pnumber].name, 2, plist[pnumber].color));
            }
            else if (plist[pnumber].value == 11)
            {
                cm.tRob.Add(new Poker(plist[pnumber].name, 1, plist[pnumber].color));
            }
        }

        print(plist[pnumber].ToString());
    }
Ejemplo n.º 8
0
    /// <summary>
    /// 初始化出牌的点击事件
    /// </summary>
    void Start()
    {   //通过标签拿到对象
        // scoreText = GameObject.FindWithTag("score") as Text;
        // canvas = GetComponent<Canvas>();
        cd   = CardUtils.GetInstance();
        game = gameObject.GetComponent <player>();
        //出牌点击事件
        playCard.onClick.AddListener(delegate()
        {
            playCardOnClick();
        });
        //再来一局按钮
        restart.onClick.AddListener(delegate()
        {
            restart.gameObject.SetActive(false);
            game.SendMessage("RestartGame");
        });
        //埋牌点击事件
        BuriedCard.onClick.AddListener(delegate()
        {
            BuriecdCard();
        });
        //一打三
        radio.onClick.AddListener(delegate()
        {   //设置两边的队友
            CardManager.Instance.banker.Add(0);
            CardManager.Instance.civilians.Add(1);
            CardManager.Instance.civilians.Add(2);
            CardManager.Instance.civilians.Add(3);
            //隐藏找朋友按钮
            radio.gameObject.SetActive(false);
            select.gameObject.SetActive(false);
            //显示出牌按钮
            playCard.gameObject.SetActive(true);
        });
        //找朋友
        select.onClick.AddListener(delegate()
        {
            List <int> count = new List <int>();
            count.Add(PlayRules.Instance.findFriends(CardManager.Instance.mList) + PlayRules.Instance.findFriends(CardManager.Instance.blist));
            count.Add(PlayRules.Instance.findFriends(CardManager.Instance.fList));
            count.Add(PlayRules.Instance.findFriends(CardManager.Instance.sList));
            count.Add(PlayRules.Instance.findFriends(CardManager.Instance.tList));
            //默认两个6不成对
            bool f = false;
            //2个主6在哪个人手里
            //  int pdouble=-1;
            //查找主6 是否成对
            for (int i = 0; i < count.Count; i++)
            {
                if (count[i] == 2)
                {
                    f = true;
                }
            }
            //主6成对
            if (f)
            {
                CardManager.Instance.banker.Add(0);
                CardManager.Instance.banker.Add(2);
                CardManager.Instance.civilians.Add(1);
                CardManager.Instance.civilians.Add(3);
            }
            //主6没成对
            else
            { //存有6的
                List <int> list = new List <int>();
                //存没有6的
                List <int> nlist = new List <int>();
                //找出6在那个人手里
                for (int i = 0; i < count.Count; i++)
                {
                    if (count[i] >= 0)
                    {
                        list.Add(i);
                    }
                    else
                    {
                        nlist.Add(i);
                    }
                }
                //自己没有6
                if (count[0] == 0)
                {
                    foreach (int item in nlist)
                    {
                        CardManager.Instance.banker.Add(item);
                    }

                    foreach (int item in list)
                    {
                        CardManager.Instance.civilians.Add(item);
                    }
                }
                //自己有6
                else if (count[0] == 1)
                {
                    foreach (int item in list)
                    {
                        CardManager.Instance.banker.Add(item);
                    }

                    foreach (int item in nlist)
                    {
                        CardManager.Instance.civilians.Add(item);
                    }
                }
            }
            //隐藏找朋友按钮
            radio.gameObject.SetActive(false);
            select.gameObject.SetActive(false);
            //显示出牌按钮
            playCard.gameObject.SetActive(true);
        });
    }
Ejemplo n.º 9
0
        protected virtual void HandlePlayCommand(CommandMatch cmd, IChannelMessageEventArgs msg)
        {
            if (msg.Channel != Config.UnoChannel)
            {
                return;
            }

            lock (TurnLock)
            {
                if (CurrentPlayer.Nick != msg.SenderNickname)
                {
                    ConnectionManager.SendChannelMessageFormat(Config.UnoChannel, "It's not your turn, {0}.", msg.SenderNickname);
                    return;
                }

                var primaryString   = (string)cmd.Arguments[0];
                var secondaryString = (string)cmd.Arguments[1];

                // !play COLOR VALUE for colors or !play VALUE CHOSENCOLOR for wilds
                CardColor?color = CardUtils.ParseColor(primaryString);
                if (!color.HasValue || color.Value == CardColor.Wild)
                {
                    // try parsing it as a value instead (wild card)
                    CardValue?value       = CardUtils.ParseValue(primaryString);
                    CardColor?chosenColor = CardUtils.ParseColor(secondaryString);
                    if (!value.HasValue || (value.Value != CardValue.Wild && value.Value != CardValue.WildDrawFour) || !chosenColor.HasValue)
                    {
                        ConnectionManager.SendChannelMessageFormat(
                            Config.UnoChannel,
                            "{0}: Play a card using !play COLOR VALUE for normal cards or !play VALUE CHOSENCOLOR for wild cards!",
                            msg.SenderNickname
                            );
                        return;
                    }

                    // wild cards can be played independent of top card's color or value

                    // take the card from the player's hand
                    var requestedCard = new Card(CardColor.Wild, value.Value);
                    if (!CurrentPlayer.Hand.Remove(requestedCard))
                    {
                        ConnectionManager.SendChannelMessageFormat(
                            Config.UnoChannel,
                            "{0}: You don't have that card.",
                            msg.SenderNickname
                            );
                        return;
                    }

                    // toss its colorful equivalent on top of the discard pile
                    var disCard = new Card(chosenColor.Value, value.Value);
                    DiscardPile.Push(disCard);

                    // if this is a WD4, feed the next player with 4 cards
                    if (value.Value == CardValue.WildDrawFour)
                    {
                        // advancing here and advancing later simply skips this player
                        AdvanceCurrentPlayerIndex();
                        ConnectionManager.SendChannelMessageFormat(
                            Config.UnoChannel,
                            "{0} draws four cards.",
                            CurrentPlayer.Nick
                            );
                        CurrentPlayer.Hand.UnionWith(DrawCards(4));

                        // inform the player of their new hand
                        SendPlayerHandInfoEvent(CurrentPlayer);
                    }
                }
                else
                {
                    CardValue?value = CardUtils.ParseValue(secondaryString);
                    if (!value.HasValue)
                    {
                        ConnectionManager.SendChannelMessageFormat(
                            Config.UnoChannel,
                            "{0}: Play a card using !play COLOR VALUE for normal cards or !play VALUE CHOSENCOLOR for wild cards!",
                            msg.SenderNickname
                            );
                        return;
                    }

                    // see if this card is playable at all
                    if (TopCard.Color != color.Value && TopCard.Value != value.Value)
                    {
                        ConnectionManager.SendChannelMessageFormat(
                            Config.UnoChannel,
                            "{0}: You cannot play this card.",
                            msg.SenderNickname
                            );
                        return;
                    }

                    // take the card from the player's hand
                    var requestedCard = new Card(color.Value, value.Value);
                    if (!CurrentPlayer.Hand.Remove(requestedCard))
                    {
                        ConnectionManager.SendChannelMessageFormat(
                            Config.UnoChannel,
                            "{0}: You don't have that card.",
                            msg.SenderNickname
                            );
                        return;
                    }

                    // toss it on the top of the discard pile
                    DiscardPile.Push(requestedCard);

                    // if this is a Skip (or a Reverse with less than three players), skip the next player
                    if (value.Value == CardValue.Skip || (value.Value == CardValue.Reverse && Players.Count < 3))
                    {
                        AdvanceCurrentPlayerIndex();
                        ConnectionManager.SendChannelMessageFormat(
                            Config.UnoChannel,
                            "{0} has been skipped.",
                            CurrentPlayer.Nick
                            );
                    }
                    // if this is a Reverse (with at least three players), reverse the direction
                    else if (value.Value == CardValue.Reverse)
                    {
                        PlayerOrderReversed = !PlayerOrderReversed;
                        ConnectionManager.SendChannelMessageFormat(
                            Config.UnoChannel,
                            "{0} reversed the player order.",
                            CurrentPlayer.Nick
                            );
                    }
                    // if this is a D2, feed the next player with 2 cards
                    else if (value.Value == CardValue.DrawTwo)
                    {
                        // advancing here and advancing later simply skips this player
                        AdvanceCurrentPlayerIndex();
                        ConnectionManager.SendChannelMessageFormat(
                            Config.UnoChannel,
                            "{0} draws two cards.",
                            CurrentPlayer.Nick
                            );
                        CurrentPlayer.Hand.UnionWith(DrawCards(2));

                        // inform the player of their new hand
                        SendPlayerHandInfoEvent(CurrentPlayer);
                    }
                }

                // is any player out of cards?
                var firstPlayerWithNoCards = Players.FirstOrDefault(p => p.Hand.Count == 0);
                if (firstPlayerWithNoCards != null)
                {
                    // this player wins!
                    ConnectionManager.SendChannelMessageFormat(
                        Config.UnoChannel,
                        "{0} is the winner!",
                        firstPlayerWithNoCards.Nick
                        );
                    Logger.LogInformation("Uno game won by {0}", firstPlayerWithNoCards.Nick);

                    // clean up the game
                    StopGame();

                    if (BotTestCount > 0)
                    {
                        --BotTestCount;
                        if (BotTestCount > 0)
                        {
                            // start another round, inviting all bots!
                            ConnectionManager.SendChannelMessageFormat(
                                Config.UnoChannel,
                                "I'm in bot test mode; {0} game{1} left!",
                                BotTestCount,
                                (BotTestCount == 1) ? "" : "s"
                                );
                            Logger.LogInformation("{Count} bot test game/s left", BotTestCount);
                            PrepareGame();
                            ConnectionManager.SendChannelMessage(Config.UnoChannel, "?join");
                            BotTestJoinRequested = DateTime.UtcNow;
                        }
                    }

                    return;
                }

                // next player's turn!
                AdvanceToNextPlayer();
            }
        }
Ejemplo n.º 10
0
        public void UpdateCardDetailModel(int id)
        {
            var cardModel        = CardUtils.GetCardModel(id);
            var isFollower       = CardUtils.IsFollower(id);
            var type             = Dic.TypeCodeDic.FirstOrDefault(dic => cardModel.TypeCode == dic.Key).Value;
            var camp             = Dic.CampCodeDic.FirstOrDefault(dic => cardModel.CampCode == dic.Key).Value;
            var rarity           = Dic.RarityCodeDic.FirstOrDefault(dic => cardModel.RarityCode == dic.Key).Value;
            var pack             = Dic.PackCodeDic.FirstOrDefault(dic => cardModel.PackCode == dic.Key).Value;
            var imageCostPath    = Dic.ImageCostDic.FirstOrDefault(dic => cardModel.Cost == dic.Key).Value;
            var imagePathList    = CardUtils.GetPicturePathList(cardModel.Id);
            var imageCurrentPath = imagePathList[0];
            var atk           = isFollower ? cardModel.Atk.ToString() : "";
            var evoAtk        = isFollower ? cardModel.EvoAtk.ToString() : "";
            var life          = isFollower ? cardModel.Life.ToString() : "";
            var evoLife       = isFollower ? cardModel.EvoLife.ToString() : "";
            var imageAtkPath  = isFollower ? PathManager.AtkPath : "";
            var imageLifePath = isFollower ? PathManager.LifePath : "";
            var skillList     = isFollower
                ? JsonUtils.Deserialize <List <string> >(cardModel.SkillJson)
                : new List <string> {
                cardModel.SkillJson
            };
            var flavourList = isFollower
                ? JsonUtils.Deserialize <List <string> >(cardModel.FlavourJosn)
                : new List <string>()
            {
                cardModel.FlavourJosn
            };
            var evoDescriptionList = isFollower
                ? new List <string> {
                "进化前", "进化后"
            }
                : new List <string> {
                "", ""
            };

            CardDetailModel = new CardDetailModel
            {
                Id                 = id,
                Camp               = camp,
                Type               = type,
                Rarity             = rarity,
                Pack               = pack,
                Name               = cardModel.Name,
                Cv                 = cardModel.Cv,
                Atk                = atk,
                EvoAtk             = evoAtk,
                Life               = life,
                EvoLife            = evoLife,
                SkillList          = skillList,
                FlavourList        = flavourList,
                ImagePathList      = imagePathList,
                ImageCurrentPath   = imageCurrentPath,
                EvoDescriptionList = evoDescriptionList,
                BgRarity           = GetBgRarity(cardModel.RarityCode),
                ImageCostPath      = imageCostPath,
                ImageAtkPath       = imageAtkPath,
                ImageLifePath      = imageLifePath,
            };
            OnPropertyChanged(nameof(CardDetailModel));
        }
Ejemplo n.º 11
0
        public override void execute()
        {
            if (laneSelection)
            {
                foreach (Lane lane in ArenaManager.getLanes())
                {
                    if (lane.PlayerCard != null &&
                        lane.OpponentCard != null)
                    {
                        selectedLane = lane;
                        CardUtils.animateCard(selectedLane.PlayerCard);
                        CardUtils.animateCard(selectedLane.OpponentCard);
                        laneSelection             = false;
                        reveal                    = true;
                        revealPhase               = new RevealPhase();
                        revealPhase.ArenaManager  = ArenaManager;
                        revealPhase.SelectedLane  = selectedLane;
                        revealPhase.StockpileRule = false;
                        break;
                    }
                }
            }

            if (reveal)
            {
                revealPhase.execute();

                if (revealPhase.hasCompleted())
                {
                    laneSelection = true;
                    reveal        = false;
                }
            }
            else
            {
                //true end, figure out winner
                int playerLanes   = 0;
                int opponentLanes = 0;

                foreach (Lane lane in ArenaManager.getLanes())
                {
                    //TODO highlight the lane to the winner
                    if (lane.playerPoints > lane.opponentPoints)
                    {
                        playerLanes++;
                    }
                    else if (lane.playerPoints < lane.opponentPoints)
                    {
                        opponentLanes++;
                    }
                }

                if (playerLanes > opponentLanes)
                {
                    InterfaceManager.gameResultLabel.text  = "You Win";
                    InterfaceManager.gameResultLabel.color = Color.green;
                }
                else if (opponentLanes > playerLanes)
                {
                    InterfaceManager.gameResultLabel.text  = "You Lose";
                    InterfaceManager.gameResultLabel.color = Color.red;
                }
                else
                {
                    InterfaceManager.gameResultLabel.text  = "Draw";
                    InterfaceManager.gameResultLabel.color = Color.black;
                }

                completed = true;
            }
        }
Ejemplo n.º 12
0
        public virtual void DispatchEvent(object caller, JObject eventObject)
        {
            JToken eventToken;

            if (!eventObject.TryGetValue("event", StringComparison.Ordinal, out eventToken))
            {
                throw new ArgumentException($"missing \"event\" name/value pair in {nameof(eventObject)}", nameof(eventObject));
            }
            if (eventToken.Type != JTokenType.String)
            {
                throw new ArgumentException($"value for \"event\" is not a string in {nameof(eventObject)}", nameof(eventObject));
            }

            string eventName = (string)((JValue)eventToken).Value;

            // any takers?
            Type botType = caller.GetType();

            foreach (MethodInfo method in botType.GetMethods())
            {
                bool thisEvent = method.GetCustomAttributes <EventAttribute>()
                                 .Any(ea => ea.EventName == eventName);
                if (!thisEvent)
                {
                    // no such luck; next!
                    continue;
                }

                // try populating all the parameters
                bool            parameterFailure = false;
                ParameterInfo[] parameters       = method.GetParameters();
                var             arguments        = new object[parameters.Length];
                for (int i = 0; i < parameters.Length; ++i)
                {
                    ParameterInfo parameter = parameters[i];

                    string valueName = parameter.GetCustomAttributes <EventValueAttribute>()
                                       .Select(eva => eva.ValueName)
                                       .FirstOrDefault();

                    if (valueName == null || eventObject[valueName] == null)
                    {
                        // cannot populate the argument from the event

                        if (!parameter.HasDefaultValue)
                        {
                            // and it doesn't have a default value; I give up
                            parameterFailure = true;
                            break;
                        }

                        arguments[i] = parameter.DefaultValue;
                    }
                    else
                    {
                        // okay, see if we can fill it
                        TypeInfo parameterType = parameter.ParameterType.GetTypeInfo();
                        JToken   eventValue    = eventObject.GetValue(valueName);

                        if (parameterType.IsAssignableFrom(typeof(JToken)))
                        {
                            // alright, raw JToken it is
                            arguments[i] = eventValue;
                        }
                        else if (parameterType.IsAssignableFrom(typeof(JValue)) && eventValue is JValue)
                        {
                            arguments[i] = (JValue)eventValue;
                        }
                        else if (parameterType.IsAssignableFrom(typeof(JObject)) && eventValue is JObject)
                        {
                            arguments[i] = (JObject)eventValue;
                        }
                        else if (parameterType.IsAssignableFrom(typeof(JArray)) && eventValue is JArray)
                        {
                            arguments[i] = (JArray)eventValue;
                        }
                        else if (eventValue.Type == JTokenType.Null)
                        {
                            if (!parameterType.IsValueType)
                            {
                                // reference type
                                arguments[i] = null;
                            }
                            else if (parameterType.IsGenericType &&
                                     parameterType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
                            {
                                // nullable value type
                                arguments[i] = null;
                            }
                            else
                            {
                                // nope :(
                                parameterFailure = true;
                                break;
                            }
                        }
                        else if (eventValue.Type == JTokenType.Float || eventValue.Type == JTokenType.Integer)
                        {
                            if (parameterType.IsAssignableFrom(typeof(int)) ||
                                parameterType.IsAssignableFrom(typeof(int?)))
                            {
                                arguments[i] = (int)eventValue;
                            }
                            else if (parameterType.IsAssignableFrom(typeof(long)) ||
                                     parameterType.IsAssignableFrom(typeof(long?)))
                            {
                                arguments[i] = (long)eventValue;
                            }
                            else if (parameterType.IsAssignableFrom(typeof(double)) ||
                                     parameterType.IsAssignableFrom(typeof(double?)))
                            {
                                arguments[i] = (double)eventValue;
                            }
                            else if (parameterType.IsAssignableFrom(typeof(decimal)) ||
                                     parameterType.IsAssignableFrom(typeof(decimal?)))
                            {
                                arguments[i] = (decimal)eventValue;
                            }
                            // add more?
                            else
                            {
                                parameterFailure = true;
                                break;
                            }
                        }
                        else if (eventValue.Type == JTokenType.String)
                        {
                            var stringValue = (string)eventValue;

                            if (parameterType.IsAssignableFrom(typeof(char)) ||
                                parameterType.IsAssignableFrom(typeof(char?)))
                            {
                                if (stringValue.Length == 1)
                                {
                                    arguments[i] = stringValue[0];
                                }
                                else
                                {
                                    parameterFailure = true;
                                    break;
                                }
                            }
                            else if (parameterType.IsAssignableFrom(typeof(string)))
                            {
                                arguments[i] = stringValue;
                            }
                            else
                            {
                                parameterFailure = true;
                                break;
                            }
                        }
                        else if (eventValue.Type == JTokenType.Array)
                        {
                            var arrayValue = (JArray)eventValue;

                            if (arrayValue.All(jv => jv is JObject))
                            {
                                // might be a useful array
                                if (parameterType.IsAssignableFrom(typeof(List <Card>)))
                                {
                                    try
                                    {
                                        List <Card> cards = arrayValue.Select(jv => CardUtils.CardFromJson((JObject)jv))
                                                            .ToList();
                                        arguments[i] = cards;
                                    }
                                    catch (ArgumentException)
                                    {
                                        parameterFailure = true;
                                        break;
                                    }
                                }
                                else if (parameterType.IsAssignableFrom(typeof(List <JObject>)))
                                {
                                    List <JObject> jobjects = arrayValue.Select(jv => (JObject)jv)
                                                              .ToList();
                                    arguments[i] = jobjects;
                                }
                                else
                                {
                                    parameterFailure = true;
                                    break;
                                }
                            }
                            else if (parameterType.IsAssignableFrom(typeof(List <JToken>)))
                            {
                                List <JToken> jtokens = arrayValue.ToList();
                                arguments[i] = jtokens;
                            }
                            else
                            {
                                parameterFailure = true;
                                break;
                            }
                        }
                        else
                        {
                            parameterFailure = true;
                            break;
                        }
                    }
                }

                if (parameterFailure)
                {
                    continue;
                }

                // cool, we found a matching method; run it!
                method.Invoke(caller, arguments);
                break;
            }
        }
Ejemplo n.º 13
0
        public Transaction ProcessSecure3d(Secure3dBuilder builder)
        {
            TransactionType transType     = builder.TransactionType;
            IPaymentMethod  paymentMethod = builder.PaymentMethod;
            ISecure3d       secure3d      = (ISecure3d)paymentMethod;
            string          timestamp     = DateTime.Now.ToString("yyyy-MM-dd'T'hh:mm:ss.ffffff");

            JsonDoc request = new JsonDoc();

            if (transType.Equals(TransactionType.VerifyEnrolled))
            {
                request.Set("request_timestamp", timestamp);
                request.Set("merchant_id", MerchantId);
                request.Set("account_id", AccountId);
                request.Set("method_notification_url", MethodNotificationUrl);

                string hashValue = string.Empty;
                if (paymentMethod is CreditCardData cardData)
                {
                    request.Set("number", cardData.Number);
                    request.Set("scheme", MapCardScheme(CardUtils.GetBaseCardType(cardData.CardType).ToUpper()));
                    hashValue = cardData.Number;
                }
                else if (paymentMethod is RecurringPaymentMethod storedCard)
                {
                    request.Set("payer_reference", storedCard.CustomerKey);
                    request.Set("payment_method_reference", storedCard.Key);
                    hashValue = storedCard.CustomerKey;
                }

                string hash = GenerationUtils.GenerateHash(SharedSecret, timestamp, MerchantId, hashValue);
                SetAuthHeader(hash);

                string rawResponse = DoTransaction(HttpMethod.Post, "protocol-versions", request.ToString());
                return(MapResponse(rawResponse));
            }
            else if (transType.Equals(TransactionType.VerifySignature))
            {
                string hash = GenerationUtils.GenerateHash(SharedSecret, timestamp, MerchantId, builder.ServerTransactionId);
                SetAuthHeader(hash);

                var queryValues = new Dictionary <string, string>();
                queryValues.Add("merchant_id", MerchantId);
                queryValues.Add("request_timestamp", timestamp);

                string rawResponse = DoTransaction(HttpMethod.Get, string.Format("authentications/{0}", builder.ServerTransactionId), null, queryValues);
                return(MapResponse(rawResponse));
            }
            else if (transType.Equals(TransactionType.InitiateAuthentication))
            {
                string orderId = builder.OrderId;
                if (string.IsNullOrEmpty(orderId))
                {
                    orderId = GenerationUtils.GenerateOrderId();
                }
                ThreeDSecure secureEcom = secure3d.ThreeDSecure;

                request.Set("request_timestamp", timestamp);
                request.Set("authentication_source", builder.AuthenticationSource.ToString());
                request.Set("authentication_request_type", builder.AuthenticationRequestType.ToString());
                request.Set("message_category", builder.MessageCategory.ToString());
                request.Set("message_version", "2.1.0");
                request.Set("server_trans_id", secureEcom.ServerTransactionId);
                request.Set("merchant_id", MerchantId);
                request.Set("account_id", AccountId);
                request.Set("challenge_notification_url", ChallengeNotificationUrl);
                request.Set("challenge_request_indicator", builder.ChallengeRequestIndicator.ToString());
                request.Set("method_url_completion", builder.MethodUrlCompletion.ToString());
                request.Set("merchant_contact_url", MerchantContactUrl);
                request.Set("merchant_initiated_request_type", builder.MerchantInitiatedRequestType?.ToString());
                request.Set("whitelist_status", builder.WhitelistStatus);
                request.Set("decoupled_flow_request", builder.DecoupledFlowRequest);
                request.Set("decoupled_flow_timeout", builder.DecoupledFlowTimeout);
                request.Set("decoupled_notification_url", builder.DecoupledNotificationUrl);
                request.Set("enable_exemption_optimization", builder.EnableExemptionOptimization);

                // card details
                string  hashValue  = string.Empty;
                JsonDoc cardDetail = request.SubElement("card_detail");
                if (paymentMethod is CreditCardData cardData)
                {
                    hashValue = cardData.Number;
                    cardDetail.Set("number", cardData.Number);
                    cardDetail.Set("scheme", CardUtils.GetBaseCardType(cardData.CardType).ToUpper());
                    cardDetail.Set("expiry_month", cardData.ExpMonth.ToString());
                    cardDetail.Set("expiry_year", cardData.ExpYear.ToString().Substring(2));
                    cardDetail.Set("full_name", cardData.CardHolderName);

                    if (!string.IsNullOrEmpty(cardData.CardHolderName))
                    {
                        string[] names = cardData.CardHolderName.Split(' ');
                        if (names.Length >= 1)
                        {
                            cardDetail.Set("first_name", names[0]);
                        }
                        if (names.Length >= 2)
                        {
                            cardDetail.Set("last_name", string.Join(" ", names.Skip(1)));
                        }
                    }
                }
                else if (paymentMethod is RecurringPaymentMethod storedCard)
                {
                    hashValue = storedCard.CustomerKey;
                    cardDetail.Set("payer_reference", storedCard.CustomerKey);
                    cardDetail.Set("payment_method_reference", storedCard.Key);
                }

                // order details
                JsonDoc order = request.SubElement("order");
                order.Set("amount", builder.Amount.ToNumericCurrencyString());
                order.Set("currency", builder.Currency);
                order.Set("id", orderId);
                order.Set("address_match_indicator", builder.AddressMatchIndicator ? "true" : "false");
                order.Set("date_time_created", builder.OrderCreateDate?.ToString("yyyy-MM-dd'T'hh:mm'Z'"));
                order.Set("gift_card_count", builder.GiftCardCount);
                order.Set("gift_card_currency", builder.GiftCardCurrency);
                order.Set("gift_card_amount", builder.GiftCardAmount.ToNumericCurrencyString());
                order.Set("delivery_email", builder.DeliveryEmail);
                order.Set("delivery_timeframe", builder.DeliveryTimeframe?.ToString());
                order.Set("shipping_method", builder.ShippingMethod?.ToString());
                order.Set("shipping_name_matches_cardholder_name", builder.ShippingNameMatchesCardHolderName);
                order.Set("preorder_indicator", builder.PreOrderIndicator?.ToString());
                order.Set("reorder_indicator", builder.ReorderIndicator?.ToString());
                order.Set("transaction_type", builder.OrderTransactionType?.ToString());
                order.Set("preorder_availability_date", builder.PreOrderAvailabilityDate?.ToString("yyyy-MM-dd"));

                // shipping address
                Address shippingAddress = builder.ShippingAddress;
                if (shippingAddress != null)
                {
                    JsonDoc shippingAddressElement = order.SubElement("shipping_address");
                    shippingAddressElement.Set("line1", shippingAddress.StreetAddress1);
                    shippingAddressElement.Set("line2", shippingAddress.StreetAddress2);
                    shippingAddressElement.Set("line3", shippingAddress.StreetAddress3);
                    shippingAddressElement.Set("city", shippingAddress.City);
                    shippingAddressElement.Set("postal_code", shippingAddress.PostalCode);
                    shippingAddressElement.Set("state", shippingAddress.State);
                    shippingAddressElement.Set("country", shippingAddress.CountryCode);
                }

                // payer
                JsonDoc payer = request.SubElement("payer");
                payer.Set("email", builder.CustomerEmail);
                payer.Set("id", builder.CustomerAccountId);
                payer.Set("account_age", builder.AccountAgeIndicator?.ToString());
                payer.Set("account_creation_date", builder.AccountCreateDate?.ToString("yyyy-MM-dd"));
                payer.Set("account_change_indicator", builder.AccountChangeIndicator?.ToString());
                payer.Set("account_change_date", builder.AccountChangeDate?.ToString("yyyy-MM-dd"));
                payer.Set("account_password_change_indicator", builder.PasswordChangeIndicator?.ToString());
                payer.Set("account_password_change_date", builder.PasswordChangeDate?.ToString("yyyy-MM-dd"));
                payer.Set("payment_account_age_indicator", builder.PaymentAgeIndicator?.ToString());
                payer.Set("payment_account_creation_date", builder.PaymentAccountCreateDate?.ToString("yyyy-MM-dd"));
                payer.Set("purchase_count_last_6months", builder.NumberOfPurchasesInLastSixMonths);
                payer.Set("transaction_count_last_24hours", builder.NumberOfTransactionsInLast24Hours);
                payer.Set("transaction_count_last_year", builder.NumberOfTransactionsInLastYear);
                payer.Set("provision_attempt_count_last_24hours", builder.NumberOfAddCardAttemptsInLast24Hours);
                payer.Set("shipping_address_creation_indicator", builder.ShippingAddressUsageIndicator?.ToString());
                payer.Set("shipping_address_creation_date", builder.ShippingAddressCreateDate?.ToString("yyyy-MM-dd"));

                // suspicious activity
                if (builder.PreviousSuspiciousActivity != null)
                {
                    payer.Set("suspicious_account_activity", builder.PreviousSuspiciousActivity.Value ? "SUSPICIOUS_ACTIVITY" : "NO_SUSPICIOUS_ACTIVITY");
                }

                // home phone
                if (!string.IsNullOrEmpty(builder.HomeNumber))
                {
                    payer.SubElement("home_phone")
                    .Set("country_code", builder.HomeCountryCode.ToNumeric())
                    .Set("subscriber_number", builder.HomeNumber.ToNumeric());
                }

                // work phone
                if (!string.IsNullOrEmpty(builder.WorkNumber))
                {
                    payer.SubElement("work_phone")
                    .Set("country_code", builder.WorkCountryCode.ToNumeric())
                    .Set("subscriber_number", builder.WorkNumber.ToNumeric());
                }

                // payer login data
                if (builder.HasPayerLoginData)
                {
                    request.SubElement("payer_login_data")
                    .Set("authentication_data", builder.CustomerAuthenticationData)
                    .Set("authentication_timestamp", builder.CustomerAuthenticationTimestamp?.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'"))
                    .Set("authentication_type", builder.CustomerAuthenticationMethod?.ToString());
                }

                // prior authentication data
                if (builder.HasPriorAuthenticationData)
                {
                    request.SubElement("payer_prior_three_ds_authentication_data")
                    .Set("authentication_method", builder.PriorAuthenticationMethod?.ToString())
                    .Set("acs_transaction_id", builder.PriorAuthenticationTransactionId)
                    .Set("authentication_timestamp", builder.PriorAuthenticationTimestamp?.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'"))
                    .Set("authentication_data", builder.PriorAuthenticationData);
                }

                // recurring authorization data
                if (builder.HasRecurringAuthData)
                {
                    request.SubElement("recurring_authorization_data")
                    .Set("max_number_of_instalments", builder.MaxNumberOfInstallments)
                    .Set("frequency", builder.RecurringAuthorizationFrequency)
                    .Set("expiry_date", builder.RecurringAuthorizationExpiryDate?.ToString("yyyy-MM-dd"));
                }

                // billing details
                Address billingAddress = builder.BillingAddress;
                if (billingAddress != null)
                {
                    JsonDoc billingAddressElement = payer.SubElement("billing_address");
                    billingAddressElement.Set("line1", billingAddress.StreetAddress1);
                    billingAddressElement.Set("line2", billingAddress.StreetAddress2);
                    billingAddressElement.Set("line3", billingAddress.StreetAddress3);
                    billingAddressElement.Set("city", billingAddress.City);
                    billingAddressElement.Set("postal_code", billingAddress.PostalCode);
                    billingAddressElement.Set("state", billingAddress.State);
                    billingAddressElement.Set("country", billingAddress.CountryCode);
                }

                // mobile phone
                if (!string.IsNullOrEmpty(builder.MobileNumber))
                {
                    JsonDoc mobilePhone = payer.SubElement("mobile_phone");
                    mobilePhone.Set("country_code", builder.MobileCountryCode.ToNumeric());
                    mobilePhone.Set("subscriber_number", builder.MobileNumber.ToNumeric());
                }

                // browser_data
                BrowserData broswerData = builder.BrowserData;
                if (broswerData != null)
                {
                    JsonDoc browserDataElement = request.SubElement("browser_data");
                    browserDataElement.Set("accept_header", broswerData.AcceptHeader);
                    browserDataElement.Set("color_depth", broswerData.ColorDepth.ToString());
                    browserDataElement.Set("ip", broswerData.IpAddress);
                    browserDataElement.Set("java_enabled", broswerData.JavaEnabled);
                    browserDataElement.Set("javascript_enabled", broswerData.JavaScriptEnabled);
                    browserDataElement.Set("language", broswerData.Language);
                    browserDataElement.Set("screen_height", broswerData.ScreenHeight);
                    browserDataElement.Set("screen_width", broswerData.ScreenWidth);
                    browserDataElement.Set("challenge_window_size", broswerData.ChallengeWindowSize.ToString());
                    browserDataElement.Set("timezone", broswerData.Timezone);
                    browserDataElement.Set("user_agent", broswerData.UserAgent);
                }

                // mobile fields
                if (builder.HasMobileFields)
                {
                    JsonDoc sdkInformationElement = request.SubElement("sdk_information")
                                                    .Set("application_id", builder.ApplicationId)
                                                    .Set("ephemeral_public_key", builder.EphemeralPublicKey)
                                                    .Set("maximum_timeout", builder.MaximumTimeout)
                                                    .Set("reference_number", builder.ReferenceNumber)
                                                    .Set("sdk_trans_id", builder.SdkTransactionId)
                                                    .Set("encoded_data", builder.EncodedData)
                    ;

                    // device render options
                    if (builder.SdkInterface != null || builder.SdkUiTypes != null)
                    {
                        var dro = sdkInformationElement.SubElement("device_render_options");
                        dro.Set("sdk_interface", builder.SdkInterface?.ToString());
                        if (builder.SdkUiTypes != null)
                        {
                            var uiTypes = new List <string>();
                            foreach (var sdkuiType in builder.SdkUiTypes)
                            {
                                uiTypes.Add(sdkuiType.ToString());
                            }
                            dro.Set("sdk_ui_type", uiTypes.ToArray());
                        }
                    }
                }

                string hash = GenerationUtils.GenerateHash(SharedSecret, timestamp, MerchantId, hashValue, secureEcom.ServerTransactionId);
                SetAuthHeader(hash);

                string rawResponse = DoTransaction(HttpMethod.Post, "authentications", request.ToString());
                return(MapResponse(rawResponse));
            }

            throw new ApiException(string.Format("Unknown transaction type {0}.", transType));
        }
Ejemplo n.º 14
0
        private IEnumerable <R4UCard> CreateBaseCards(IHtmlParagraphElement paragraph, Dictionary <string, R4UReleaseSet> setMap)
        {
            List <R4UCard> cards = new List <R4UCard>();

            cards.Add(new R4UCard());

            var card    = cards.First();
            var content = paragraph.InnerHtml;
            var text    = paragraph.GetInnerText();
            var cursor  = text.AsSpanCursor();

            // var space = " ";

            // Format: <Serial> <Rarity> <JP Name with Spaces> <strong>English Name with Spaces</strong><br>
            if (TryGetExceptionalSerialRarityName(cursor.CurrentLine.ToString(), out var exceptionalResults))
            {
                cards = exceptionalResults.Select(res =>
                {
                    var card    = new R4UCard();
                    card.Serial = res.Serial;
                    card.Rarity = res.Rarity;
                    card.Name   = res.Name;
                    return(card);
                }).ToList();
                if (cards.Count < 1)
                {
                    yield break;
                }
                card = cards.First();
            }
            else if (serialRarityJPNameMatcher.IsMatch(content))
            {
                var firstLineMatch = serialRarityJPNameMatcher.Match(content);
                card.Serial  = firstLineMatch.Groups[1].Value.Trim();
                card.Rarity  = firstLineMatch.Groups[2].Value.Trim();
                card.Name    = new MultiLanguageString();
                card.Name.JP = rubyMatcher.Replace(firstLineMatch.Groups[3].Value, "").Trim(); // TODO: Resolve <ruby>永<rt>えい</rt>遠<rt>えん</rt></ruby>の<ruby>巫<rt>み</rt>女<rt>こ</rt></ruby> <ruby>霊<rt>れい</rt>夢<rt>む</rt></ruby>
                card.Name.EN = firstLineMatch.Groups[4].Value.Trim();
            }
            else
            {
                throw new NotImplementedException($"The serial/rarity/JP Name line cannot be parsed. Here's the offending line: {cursor.CurrentLine.ToString()}");
            }

            var releaseID = releaseIDMatcher.Match(card.Serial).Groups[1].Value;

            card.Set = setMap.GetValueOrDefault(releaseID, null) ?? CreateTemporarySet(releaseID);

            // Format: Cost <Cost> / <Series Name> / <Traits>
            cursor.Next();
            var secondLine = cursor.CurrentLine.ToString();

            if (costSeriesTraitMatcher.IsMatch(secondLine))
            {
                card.Type = CardType.Character;
                var secondLineMatch = costSeriesTraitMatcher.Match(cursor.CurrentLine.ToString());
                card.Cost   = int.Parse(secondLineMatch.Groups[1].Value);
                card.Traits = secondLineMatch.Groups[3].Value //
                              .Split(" – ")                   //
                              .Select(str => str.Trim())      //
                              .Select(t => new MultiLanguageString()
                {
                    EN = t
                })                                                     //
                              .ToList();

                cursor.Next();
                card.ATK = cursor.CurrentLine
                           .Slice("ATK ".Length)
                           .AsParsed <int>(int.TryParse);

                cursor.Next();
                string defLine = cursor.CurrentLine.ToString();
                card.DEF = cursor.CurrentLine
                           .Slice("DEF ".Length)
                           .AsParsed <int>(int.TryParse);

                Regex flavorTextMatcher = new Regex(@"" + defLine + @"<br><em>(.+)</em><br>");
                if (flavorTextMatcher.IsMatch(content))
                {
                    cursor.Next();
                    card.Flavor    = new MultiLanguageString();
                    card.Flavor.EN = cursor.CurrentLine.ToString(); // flavorTextMatcher.Match(content).Groups[1].Value;
                }
            }
            else if (seriesRebirthMatcher.IsMatch(secondLine))
            {
                card.Type = CardType.Rebirth;
                var rebirthLine = secondLine;

                Regex flavorTextMatcher = new Regex(@"" + rebirthLine + @"<br><em>(.+)</em><br>");
                if (flavorTextMatcher.IsMatch(content))
                {
                    cursor.Next();
                    card.Flavor    = new MultiLanguageString();
                    card.Flavor.EN = cursor.CurrentLine.ToString(); // flavorTextMatcher.Match(content).Groups[1].Value;
                }
            }
            else
            {
                card.Type  = CardType.Partner;
                card.Color = CardColor.Red;
            }

            if (card.Color != CardColor.Red)
            {
                List <MultiLanguageString> effects = new List <MultiLanguageString>();
                while (cursor.Next())
                {
                    Log.Information("Adding Effect: {eff}", cursor.CurrentLine.ToString());
                    effects.Add(new MultiLanguageString()
                    {
                        EN = cursor.CurrentLine.ToString()
                    });
                }
                effects     = Compress(effects);
                card.Effect = effects.ToArray();
                card.Color  = CardUtils.InferFromEffect(card.Effect);
            }

            yield return(card);

            foreach (var dupCard in cards.Skip(1))
            {
                var detailedDupCard = card.Clone();
                detailedDupCard.Serial = dupCard.Serial;
                detailedDupCard.Rarity = dupCard.Rarity;
                detailedDupCard.Name   = dupCard.Name;
                yield return(detailedDupCard);
            }
        }