Ejemplo n.º 1
0
 public IOHelper(CardHelper card, IOSetInfo ioSet, AxisSetInfo axisSet, AbsolutePosSetInfo apSet, PortHelper plcHelper, PortHelper _232Helper, FormMain form)
 {
     this.card = card;
     this.form = form;
     this.ioSet = ioSet;
     this.axisSet = axisSet;
     this.apSet = apSet;
     this.plcHelper = plcHelper;
     this._232Helper = _232Helper;
 }
Ejemplo n.º 2
0
 private void RollCards()
 {
     Cards = new List <Card>();
     foreach (var suit in Enum.GetValues(typeof(CardSuit)))
     {
         foreach (var cardName in Enum.GetNames(typeof(CardName)))
         {
             Cards.Add(new Card()
             {
                 Name = cardName, Suit = (CardSuit)suit
             });
         }
     }
     CardHelper.Shuffle(Cards);
 }
Ejemplo n.º 3
0
        // Get incident list from messaging extension action command.
        public InvokeResponse GetIncientListFromMEAction(List <IncidentDetails> currentIncidentList)
        {
            if (currentIncidentList == null)
            {
                return(CreateInvokeResponse(new MessagingExtensionActionResponse
                {
                    Task = new TaskModuleContinueResponse
                    {
                        Value = new TaskModuleTaskInfo
                        {
                            Card = CardHelper.GetNoInicidentFoundCard(),
                            Height = 200,
                            Width = 400,
                            Title = "No Incident found",
                        },
                    },
                }));
            }
            else
            {
                var incidentList   = new IncidentList();
                var listOfIncident = new List <IncidentChoiceSet>();
                foreach (var incident in currentIncidentList)
                {
                    var incidentdetail = new IncidentChoiceSet()
                    {
                        title = $"Incident title: {incident.IncidentTitle}, Created by: {incident.CreatedBy}",
                        value = incident.IncidentId
                    };
                    listOfIncident.Add(incidentdetail);
                }
                incidentList.incidentList = listOfIncident.ToArray();

                return(CreateInvokeResponse(new MessagingExtensionActionResponse
                {
                    Task = new TaskModuleContinueResponse()
                    {
                        Value = new TaskModuleTaskInfo
                        {
                            Card = CardHelper.GetInicidentListCard(incidentList),
                            Height = 460,
                            Width = 600,
                            Title = "Incident list",
                        },
                    },
                }));
            }
        }
Ejemplo n.º 4
0
        private static async Task SendCard(IDialogContext context, Card card)
        {
            try
            {
                // Title
                var title = CardHelper.GetTitle(card.IntentionId);
                await context.PostAsync(title);

                //send a feeback to user
                var activity = context.MakeMessage();
                activity.Type = ActivityTypes.Typing;
                await context.PostAsync(activity);

                // Image
                var imageMessage = context.MakeMessage();
                imageMessage.Attachments.Add(new Attachment {
                    ContentType = "image/jpg", ContentUrl = card.ImageLink
                });
                await context.PostAsync(imageMessage);

                // Buttons
                var reply = context.MakeMessage();

                if (reply.ChannelId == null)
                {
                    reply.ChannelId = "facebook";
                }

                if (reply.ChannelId.Equals("facebook", StringComparison.InvariantCultureIgnoreCase))
                {
                    reply.Text = card.Content.Replace("\n", "<br/>");
                    var channelData = new FacebookChannelData
                    {
                        QuickReplies = new[]
                        {
                            new FacebookTextQuickReply("Show another", $"SHOW_ANOTHER_{card.IntentionId}"),
                            new FacebookTextQuickReply("Change topic", "CHANGE_TOPIC")
                        }
                    };
                    reply.ChannelData = channelData;
                    await context.PostAsync(reply);
                }
            }
            catch (Exception)
            {
                await context.PostAsync("We don't understand your request. Please type a new message");
            }
        }
Ejemplo n.º 5
0
        public async Task UserDoesNotExist()
        {
            var db   = DbHelper.GetEmptyTestDB();
            var user = await UserHelper.CreateInDbAsync(db);

            var languageId = await CardLanguagHelper.CreateAsync(db);

            var frontSide = RandomHelper.String();
            var card      = await CardHelper.CreateAsync(db, user, language : languageId, frontSide : frontSide);

            using var dbContext = new MemCheckDbContext(db);
            var r = UpdateCardHelper.RequestForFrontSideChange(card, RandomHelper.String(), Guid.NewGuid());
            await Assert.ThrowsExceptionAsync <InvalidOperationException>(async() => await new UpdateCard(dbContext.AsCallContext()).RunAsync(r));

            await CardHelper.AssertCardHasFrontSide(db, card.Id, frontSide);
        }
Ejemplo n.º 6
0
        public async Task UserNotOwnerOfDeck()
        {
            var db   = DbHelper.GetEmptyTestDB();
            var user = await UserHelper.CreateInDbAsync(db);

            var deck = await DeckHelper.CreateAsync(db, user);

            var card = await CardHelper.CreateAsync(db, user);

            await DeckHelper.AddCardAsync(db, deck, card.Id);

            var otherUser = await UserHelper.CreateInDbAsync(db);

            using var dbContext = new MemCheckDbContext(db);
            await Assert.ThrowsExceptionAsync <InvalidOperationException>(async() => await new RemoveCardFromDeck(dbContext.AsCallContext()).RunAsync(new RemoveCardFromDeck.Request(otherUser, deck, card.Id)));
        }
        public void Given_A_Valid_SpellOrTrap_CardType_Should_Map_CardType_To_Correct_YgoCardType(string cardType, YgoCardType expected)
        {
            // Arrange
            var yugiohCard = new YugiohCard
            {
                Property = "Normal",
                CardType = cardType
            };
            var cardInputModel = new CardInputModel();

            // Act
            var result = CardHelper.MapBasicCardInformation(yugiohCard, cardInputModel);

            // Assert
            result.CardType.Should().Be(expected);
        }
Ejemplo n.º 8
0
        public async Task UserNotAllowedToViewACard()
        {
            var db          = DbHelper.GetEmptyTestDB();
            var cardCreator = await UserHelper.CreateInDbAsync(db);

            var cardNotAllowed = await CardHelper.CreateAsync(db, cardCreator, userWithViewIds : cardCreator.AsArray());

            var deckOwner = await UserHelper.CreateInDbAsync(db);

            var deck = await DeckHelper.CreateAsync(db, deckOwner);

            var publicCard = await CardHelper.CreateAsync(db, cardCreator);

            using var dbContext = new MemCheckDbContext(db);
            await Assert.ThrowsExceptionAsync <InvalidOperationException>(async() => await new AddCardsInDeck(dbContext.AsCallContext()).RunAsync(new AddCardsInDeck.Request(deckOwner, deck, new[] { publicCard.Id, cardNotAllowed.Id })));
        }
 public string ReflectionAdaptiveCard([FromBody] TaskInfo taskInfo)
 {
     try
     {
         _telemetry.TrackEvent("ReflectionAdaptiveCard");
         CardHelper card   = new CardHelper(_configuration, _telemetry);
         var        data   = card.CreateNewReflect(taskInfo);
         string     output = JsonConvert.SerializeObject(data);
         return(output);
     }
     catch (Exception e)
     {
         _telemetry.TrackEvent("ReflectionAdaptiveCard Exception " + e);
         return(null);
     }
 }
Ejemplo n.º 10
0
        private void SetHoleCardsItems()
        {
            FilterSectionItem filterSectionItem = this.FilterSectionCollection.FirstOrDefault(x => x.ItemType == EnumFilterSectionItemType.HoleCards);
            var selectedHoleCards = HoleCardsModel.HoleCardsCollection.Where(x => x.IsChecked);

            if (selectedHoleCards == null || !HoleCardsModel.HoleCardsCollection.Any(x => !x.IsChecked))
            {
                filterSectionItem.IsActive = false;
                return;
            }

            string selectedHoleCardsString = String.Join(",", CardHelper.GetHandsFormatted(selectedHoleCards.Select(x => x.Name).ToList()));

            filterSectionItem.Name     = String.Format("Hole Cards={0}", selectedHoleCardsString);
            filterSectionItem.IsActive = true;
        }
Ejemplo n.º 11
0
        private Card[] GenerateCards()
        {
            var now = DateTime.Now;

            Card[] cards = Enumerable.Range(1, Constants.CardCount)
                           .Select(i =>
            {
                Tuple <Suit, Rank> cardData = CardHelper.GetCardById(i);
                var card = new Card {
                    Id = i, CreationTime = now, Suit = cardData.Item1, Rank = cardData.Item2
                };
                return(card);
            })
                           .ToArray();
            return(cards);
        }
Ejemplo n.º 12
0
        public async Task EmptyDB_OriginalVersionDoesNotExist()
        {
            var db     = DbHelper.GetEmptyTestDB();
            var userId = await UserHelper.CreateInDbAsync(db);

            var language = await CardLanguagHelper.CreateAsync(db);

            var card = await CardHelper.CreateAsync(db, userId, language : language);

            using (var dbContext = new MemCheckDbContext(db))
                await new UpdateCard(dbContext.AsCallContext()).RunAsync(UpdateCardHelper.RequestForFrontSideChange(card, RandomHelper.String()));
            using (var dbContext = new MemCheckDbContext(db))
                await dbContext.CardPreviousVersions.Where(previous => previous.Card == card.Id).SingleAsync();
            using (var dbContext = new MemCheckDbContext(DbHelper.GetEmptyTestDB()))
                await Assert.ThrowsExceptionAsync <InvalidOperationException>(async() => await new GetCardDiff(dbContext.AsCallContext()).RunAsync(new GetCardDiff.Request(userId, card.Id, Guid.NewGuid())));
        }
Ejemplo n.º 13
0
    public void Buy(GameObject card)
    {
        CardHelper c = card.GetComponent <CardHelper>();

        if (IsThereMoney(c.card.goldCost))
        {
            // Debug.Log("Buying card " + c.name);
            deck.Add(CopyCard(card));
            Money.SubtractMoney(c.card.goldCost);
            UpdateMoney();
        }
        else
        {
            return;
        }
    }
Ejemplo n.º 14
0
        public async Task OnlyCardInTheDeck()
        {
            var db   = DbHelper.GetEmptyTestDB();
            var user = await UserHelper.CreateInDbAsync(db);

            var deck = await DeckHelper.CreateAsync(db, user);

            var card = await CardHelper.CreateAsync(db, user);

            await DeckHelper.AddCardAsync(db, deck, card.Id);

            using (var dbContext = new MemCheckDbContext(db))
                await new RemoveCardFromDeck(dbContext.AsCallContext()).RunAsync(new RemoveCardFromDeck.Request(user, deck, card.Id));

            await DeckHelper.CheckDeckDoesNotContainCard(db, deck, card.Id);
        }
Ejemplo n.º 15
0
        public async Task <ActionResult> Duty(string code, string userEmailId)
        {
            Portal portal = new Portal();
            AdaptiveCardRenderer renderer = new AdaptiveCardRenderer();
            var card = await CardHelper.GetMyDetailedCard(code, userEmailId);

            if (card == null)
            {
                return(HttpNotFound());
            }
            RenderedAdaptiveCard renderedCard = renderer.RenderCard(card.Content as AdaptiveCard);
            HtmlTag cardhtml = renderedCard.Html;

            portal.html = cardhtml;
            return(View("AdaptiveCardRenderer", portal));
        }
Ejemplo n.º 16
0
        public async Task CardNotInDeck()
        {
            var db   = DbHelper.GetEmptyTestDB();
            var user = await UserHelper.CreateInDbAsync(db);

            var deck = await DeckHelper.CreateAsync(db, user);

            var cardInDeck = await CardHelper.CreateAsync(db, user);

            await DeckHelper.AddCardAsync(db, deck, cardInDeck.Id);

            var cardNotInDeck = await CardHelper.CreateAsync(db, user);

            using var dbContext = new MemCheckDbContext(db);
            await Assert.ThrowsExceptionAsync <InvalidOperationException>(async() => await new MoveCardsToHeap(dbContext.AsCallContext()).RunAsync(new MoveCardsToHeap.Request(user, deck, RandomHelper.Heap(), new[] { cardInDeck.Id, cardNotInDeck.Id })));
        }
Ejemplo n.º 17
0
        /// <summary>
        /// When OnTurn method receives a fetch invoke activity on bot turn, it calls this method.
        /// </summary>
        /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param>
        /// <param name="taskModuleRequest">Task module invoke request value payload.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>A task that represents a task module response.</returns>
        protected override async Task <TaskModuleResponse> OnTeamsTaskModuleFetchAsync(ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest, CancellationToken cancellationToken)
        {
            turnContext = turnContext ?? throw new ArgumentNullException(nameof(turnContext));

            var activity = (Activity)turnContext.Activity;

            this.RecordEvent(nameof(this.OnTeamsTaskModuleFetchAsync), turnContext);

            var teamsDetails        = activity.TeamsGetTeamInfo();
            var valuesforTaskModule = JsonConvert.DeserializeObject <AdaptiveCardAction>(((JObject)activity.Value).GetValue("data", StringComparison.Ordinal)?.ToString());
            var rewardCycleDetail   = await this.rewardCycleStorageProvider.GetCurrentRewardCycleAsync(teamsDetails.Id);

            if (rewardCycleDetail != null && rewardCycleDetail.CycleId != valuesforTaskModule.RewardCycleId && valuesforTaskModule.Command != Constants.ConfigureAdminAction)
            {
                return(CardHelper.GetErrorMessageTaskModuleResponse(localizer: this.localizer, command: valuesforTaskModule.Command, isCycleClosed: true));
            }
            else if ((rewardCycleDetail == null || rewardCycleDetail.RewardCycleState == (int)RewardCycleState.Inactive) && valuesforTaskModule.Command != Constants.ConfigureAdminAction)
            {
                return(CardHelper.GetErrorMessageTaskModuleResponse(localizer: this.localizer, command: valuesforTaskModule.Command, isCycleClosed: false));
            }

            switch (valuesforTaskModule.Command)
            {
            // Fetch task module to show configure admin card
            case Constants.ConfigureAdminAction:
                this.logger.LogInformation("Fetch task module to show configure admin card.");
                return(CardHelper.GetConfigureAdminTaskModuleResponse(this.options.Value.AppBaseUri, this.instrumentationKey, this.localizer, teamsDetails.Id, updateAdmin: false));

            // Fetch and show task module to endorse an award nomination
            case Constants.EndorseAction:
                bool isEndorsementSuccess = await this.CheckEndorseStatusAsync(turnContext, valuesforTaskModule, cancellationToken);

                this.logger.LogInformation("Fetch and show task module to endorse an award nomination.");
                return(CardHelper.GetEndorseTaskModuleResponse(applicationBasePath: this.options.Value.AppBaseUri, this.localizer, valuesforTaskModule.NomineeNames, valuesforTaskModule.AwardName, rewardCycleDetail.RewardCycleEndDate, isEndorsementSuccess));

            // Fetch and show task module to show new nominate card.
            case Constants.NominateAction:
                this.logger.LogInformation("Fetch and show task module to configure new nominate award card.");
                return(CardHelper.GetNominateTaskModuleResponse(this.options.Value.AppBaseUri, this.instrumentationKey, this.localizer, teamsDetails.Id, valuesforTaskModule.AwardId));

            default:
                this.logger.LogInformation($"Invalid command for task module fetch activity.Command is : {valuesforTaskModule.Command} ");
                await turnContext.SendActivityAsync(this.localizer.GetString("ErrorMessage"));

                return(null);
            }
        }
Ejemplo n.º 18
0
        public async Task AdditionalSideImageDiff()
        {
            var db       = DbHelper.GetEmptyTestDB();
            var userName = RandomHelper.String();
            var userId   = await UserHelper.CreateInDbAsync(db, userName : userName);

            var originalVersionDate        = RandomHelper.Date();
            var originalVersionDescription = RandomHelper.String();
            var language = await CardLanguagHelper.CreateAsync(db);

            var originalVersionImageName = RandomHelper.String();
            var originalVersionImage     = await ImageHelper.CreateAsync(db, userId, originalVersionImageName);

            var card = await CardHelper.CreateAsync(db, userId, originalVersionDate, language : language, additionalSideImages : originalVersionImage.AsArray(), versionDescription : originalVersionDescription);

            var newVersionDate        = RandomHelper.Date(originalVersionDate);
            var newVersionDescription = RandomHelper.String();
            var newVersionImageName   = RandomHelper.String();
            var newVersionImage       = await ImageHelper.CreateAsync(db, userId, newVersionImageName);

            using (var dbContext = new MemCheckDbContext(db))
                await new UpdateCard(dbContext.AsCallContext(), newVersionDate).RunAsync(UpdateCardHelper.RequestForAdditionalSideImageChange(card, newVersionImage.AsArray(), versionDescription: newVersionDescription));
            Guid previousVersionId;

            using (var dbContext = new MemCheckDbContext(db))
                previousVersionId = (await dbContext.CardPreviousVersions.Where(previous => previous.Card == card.Id).SingleAsync()).Id;
            using (var dbContext = new MemCheckDbContext(db))
            {
                var diffRequest = new GetCardDiff.Request(userId, card.Id, previousVersionId);
                var result      = await new GetCardDiff(dbContext.AsCallContext()).RunAsync(diffRequest);
                Assert.AreEqual(userName, result.CurrentVersionCreator);
                Assert.AreEqual(userName, result.OriginalVersionCreator);
                Assert.AreEqual(newVersionDate, result.CurrentVersionUtcDate);
                Assert.AreEqual(originalVersionDate, result.OriginalVersionUtcDate);
                Assert.AreEqual(newVersionDescription, result.CurrentVersionDescription);
                Assert.AreEqual(originalVersionDescription, result.OriginalVersionDescription);
                Assert.AreEqual(new(newVersionImageName, originalVersionImageName), result.ImagesOnAdditionalSide);
                Assert.IsNull(result.FrontSide);
                Assert.IsNull(result.BackSide);
                Assert.IsNull(result.Language);
                Assert.IsNull(result.AdditionalInfo);
                Assert.IsNull(result.Tags);
                Assert.IsNull(result.UsersWithView);
                Assert.IsNull(result.ImagesOnFrontSide);
                Assert.IsNull(result.ImagesOnBackSide);
            }
        }
Ejemplo n.º 19
0
        public async Task ReduceVisibility_NoUserHasInDeck_OtherAuthor()
        {
            var db = DbHelper.GetEmptyTestDB();
            var cardCreatorName = RandomHelper.String();
            var cardCreator     = await UserHelper.CreateInDbAsync(db, userName : cardCreatorName);

            var languageId = await CardLanguagHelper.CreateAsync(db);

            var card = await CardHelper.CreateAsync(db, cardCreator, language : languageId, userWithViewIds : Array.Empty <Guid>());

            var newVersionCreatorName = RandomHelper.String();
            var newVersionCreator     = await UserHelper.CreateInDbAsync(db, userName : newVersionCreatorName);

            using (var dbContext = new MemCheckDbContext(db))
            {
                var r = UpdateCardHelper.RequestForFrontSideChange(card, RandomHelper.String(), newVersionCreator);
                await new UpdateCard(dbContext.AsCallContext()).RunAsync(r);
            }

            using (var dbContext = new MemCheckDbContext(db))
            {
                var r = UpdateCardHelper.RequestForVisibilityChange(card, cardCreator.AsArray(), cardCreator);
                var e = await Assert.ThrowsExceptionAsync <RequestInputException>(async() => await new UpdateCard(dbContext.AsCallContext()).RunAsync(r));

                Assert.IsTrue(e.Message.Contains(newVersionCreatorName));
            }

            using (var dbContext = new MemCheckDbContext(db))
            {
                var r = UpdateCardHelper.RequestForVisibilityChange(card, new[] { newVersionCreator }, newVersionCreator);
                var e = await Assert.ThrowsExceptionAsync <RequestInputException>(async() => await new UpdateCard(dbContext.AsCallContext()).RunAsync(r));

                Assert.IsTrue(e.Message.Contains(cardCreatorName));
            }

            using (var dbContext = new MemCheckDbContext(db))
            {
                var r = UpdateCardHelper.RequestForVisibilityChange(card, new[] { cardCreator, newVersionCreator });
                await new UpdateCard(dbContext.AsCallContext()).RunAsync(r);
            }

            using (var dbContext = new MemCheckDbContext(db))
            {
                CardVisibilityHelper.CheckUserIsAllowedToViewCards(dbContext, cardCreator, card.Id);
                CardVisibilityHelper.CheckUserIsAllowedToViewCards(dbContext, newVersionCreator, card.Id);
            }
        }
Ejemplo n.º 20
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result)
        {
            if (result != null)
            {
                var activity = await result as Activity;

                if (activity.Text == "주문")
                {
                    await context.PostAsync("주문이 완료 되었습니다. 감사합니다.");

                    context.Done("");
                    return;
                }
                else
                {
                    await context.PostAsync(activity.Text + "를 주문하셨습니다.");
                }
            }
            else
            {
                await context.PostAsync("메뉴를 선택해 주십시오");
            }

            //메뉴 출력
            SqlConnection  con     = new SqlConnection("Server=tcp:greatwalldbserver.database.windows.net,1433;Initial Catalog=greatwalldb;Persist Security Info=False;User ID=winkey;Password=!greatwall1004;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;");
            SqlCommand     cmd     = new SqlCommand("SELECT * FROM Menus", con);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);

            DataSet ds = new DataSet();

            adapter.Fill(ds);

            var message = context.MakeMessage();

            message.Attachments.Add(CardHelper.GetHeroCard("지금 주문", "지금 주문합니다.", this.ServerUrl + "order.jpg", "바로 주문", "주문"));

            foreach (DataRow row in ds.Tables[0].Rows)
            {
                message.Attachments.Add(CardHelper.GetHeroCard(row["Title"].ToString(), row["Subtitle"].ToString(), this.ServerUrl + row["Images"].ToString(), row["Title"].ToString(), row["MenuID"].ToString()));
            }

            message.AttachmentLayout = "carousel";

            await context.PostAsync(message);

            context.Wait(this.MessageReceivedAsync);
        }
        /// <summary>
        /// Invoked when the user opens the messaging extension or searching any content in it.
        /// </summary>
        /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param>
        /// <param name="query">Contains messaging extension query keywords.</param>
        /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param>
        /// <returns>Messaging extension response object to fill compose extension section.</returns>
        /// <remarks>
        /// https://docs.microsoft.com/en-us/dotnet/api/microsoft.bot.builder.teams.teamsactivityhandler.onteamsmessagingextensionqueryasync?view=botbuilder-dotnet-stable.
        /// </remarks>
        protected override async Task <MessagingExtensionResponse> OnTeamsMessagingExtensionQueryAsync(
            ITurnContext <IInvokeActivity> turnContext,
            MessagingExtensionQuery query,
            CancellationToken cancellationToken)
        {
            IInvokeActivity turnContextActivity = turnContext?.Activity;

            try
            {
                MessagingExtensionQuery messageExtensionQuery = JsonConvert.DeserializeObject <MessagingExtensionQuery>(turnContextActivity.Value.ToString());
                string searchQuery    = SearchHelper.GetSearchQueryString(messageExtensionQuery);
                string onCallSMEUsers = string.Empty;
                turnContextActivity.TryGetChannelData <TeamsChannelData>(out var teamsChannelData);

                if (messageExtensionQuery.CommandId == Constants.ActiveCommandId || messageExtensionQuery.CommandId == Constants.ClosedCommandId)
                {
                    onCallSMEUsers = await CardHelper.GetOnCallSMEuserListAsync(turnContext, this.onCallSupportDetailSearchService, this.teamId, this.logger);

                    return(new MessagingExtensionResponse
                    {
                        ComposeExtension = await SearchHelper.GetSearchResultAsync(searchQuery, messageExtensionQuery.CommandId, messageExtensionQuery.QueryOptions.Count, messageExtensionQuery.QueryOptions.Skip, this.ticketSearchService, this.localizer, turnContext.Activity.From.AadObjectId, onCallSMEUsers),
                    });
                }

                if (turnContext != null && teamsChannelData.Team != null && teamsChannelData.Team.Id == this.teamId && (messageExtensionQuery.CommandId == Constants.UrgentCommandId || messageExtensionQuery.CommandId == Constants.AssignedCommandId || messageExtensionQuery.CommandId == Constants.UnassignedCommandId))
                {
                    return(new MessagingExtensionResponse
                    {
                        ComposeExtension = await SearchHelper.GetSearchResultAsync(searchQuery, messageExtensionQuery.CommandId, messageExtensionQuery.QueryOptions.Count, messageExtensionQuery.QueryOptions.Skip, this.ticketSearchService, this.localizer),
                    });
                }

                return(new MessagingExtensionResponse
                {
                    ComposeExtension = new MessagingExtensionResult
                    {
                        Text = this.localizer.GetString("InvalidTeamText"),
                        Type = "message",
                    },
                });
            }
            catch (Exception ex)
            {
                this.logger.LogError(ex, $"Failed to handle the messaging extension command {turnContextActivity.Name}: {ex.Message}", SeverityLevel.Error);
                throw;
            }
        }
        public async Task <IActionResult> WinnerNominationAsync([FromBody] AwardWinner details)
        {
            try
            {
                if (details == null || details.Winners == null)
                {
                    return(this.BadRequest(new { message = "Award winner details can not be null." }));
                }

                var    emails      = string.Join(",", details.Winners.Select(row => row.NomineeUserPrincipalNames)).Split(",").Select(row => row.Trim()).Distinct();
                string teamId      = details.TeamId;
                var    claims      = this.GetUserClaims();
                var    teamDetails = await this.teamStorageProvider.GetTeamDetailAsync(teamId);

                string serviceUrl = teamDetails.ServiceUrl;
                string appBaseUrl = this.botSettingsOptions.Value.AppBaseUri;
                MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);
                var conversationParameters = new ConversationParameters()
                {
                    ChannelData = new TeamsChannelData()
                    {
                        Channel = new ChannelInfo()
                        {
                            Id = teamId
                        }
                    },
                    Activity = (Activity)MessageFactory.Carousel(WinnerCarouselCard.GetAwardWinnerCard(appBaseUrl, details.Winners, this.localizer)),
                    Bot      = new ChannelAccount()
                    {
                        Id = this.microsoftAppCredentials.MicrosoftAppId
                    },
                    IsGroup  = true,
                    TenantId = this.botSettingsOptions.Value.TenantId,
                };

                await((BotFrameworkAdapter)this.adapter).CreateConversationAsync(
                    Constants.TeamsBotFrameworkChannelId,
                    serviceUrl,
                    this.microsoftAppCredentials,
                    conversationParameters,
                    async(turnContext, cancellationToken) =>
                {
                    Activity mentionActivity = await CardHelper.GetMentionActivityAsync(emails, claims.FromId, teamId, turnContext, this.localizer, this.logger, MentionActivityType.Winner, default);
                    await turnContext.SendActivityAsync(mentionActivity, cancellationToken);
                    await turnContext.SendActivityAsync(MessageFactory.Text(this.localizer.GetString("ViewWinnerTabText")), cancellationToken);
                }, default);
Ejemplo n.º 23
0
        public async Task EmptyDeck()
        {
            var db   = DbHelper.GetEmptyTestDB();
            var user = await UserHelper.CreateInDbAsync(db);

            var deck = await DeckHelper.CreateAsync(db, user);

            var tag = await TagHelper.CreateAsync(db);

            await CardHelper.CreateAsync(db, user, tagIds : tag.AsArray());

            using var dbContext = new MemCheckDbContext(db);
            var request = new GetTagsOfDeck.Request(user, deck);
            var result  = await new GetTagsOfDeck(dbContext).RunAsync(request);

            Assert.IsFalse(result.Any());
        }
Ejemplo n.º 24
0
        public async Task <ActionResult> Duty(string code, string userEmailId)
        {
            Portal portal = new Portal();
            AdaptiveCardRenderer renderer = new AdaptiveCardRenderer();
            // var card = await CardHelper.GetMyDetailedCard(code, "10055"); // ${Debugging}
            var card = await CardHelper.GetMyDetailedCard(code, userEmailId, configuration);

            if (card == null)
            {
                return(StatusCode(404));
            }
            RenderedAdaptiveCard renderedCard = renderer.RenderCard(card.Content as AdaptiveCard);
            HtmlTag cardhtml = renderedCard.Html;

            portal.html = cardhtml;
            return(View("AdaptiveCardRenderer", portal));
        }
        public void TestInitialize()
        {
            this.logger             = new Mock <ILogger <CardHelper> >();
            this.memoryCache        = new Mock <IMemoryCache>();
            this.localizer          = new Mock <IStringLocalizer <Strings> >();
            this.hostingEnvironment = new Mock <IWebHostEnvironment>();
            this.botOptions         = Options.Create(new BotOptions {
                ManifestId = "123"
            });

            this.cardHelper = new CardHelper(
                this.logger.Object,
                this.memoryCache.Object,
                this.hostingEnvironment.Object,
                this.localizer.Object,
                this.botOptions);
        }
        /// <summary>
        /// When OnTurn method receives a fetch invoke activity on bot turn, it calls this method..
        /// </summary>
        /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param>
        /// <param name="taskModuleRequest">Task module invoke request value payload.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>A task that represents a task module response.</returns>
        protected override async Task <TaskModuleResponse> OnTeamsTaskModuleFetchAsync(ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest, CancellationToken cancellationToken)
        {
            turnContext = turnContext ?? throw new ArgumentNullException(nameof(turnContext));
            var activity = (Activity)turnContext.Activity;

            this.RecordEvent(nameof(this.OnTeamsTaskModuleFetchAsync), turnContext);

            try
            {
                var    valuesforTaskModule = JsonConvert.DeserializeObject <AdaptiveCardAction>(((JObject)activity.Value).GetValue("data", StringComparison.OrdinalIgnoreCase)?.ToString());
                string command             = valuesforTaskModule.Command;

                switch (command.ToUpperInvariant())
                {
                case Constants.EditRequestAction:
                    string ticketId     = valuesforTaskModule.PostedValues;
                    var    ticketDetail = await this.ticketDetailStorageProvider.GetTicketAsync(ticketId);

                    if (ticketDetail.TicketStatus == (int)TicketState.Closed)
                    {
                        return(CardHelper.GetClosedErrorAdaptiveCard(this.localizer));
                    }

                    this.logger.LogInformation("Fetch and send edit request card.");
                    return(CardHelper.GetEditTicketAdaptiveCard(cardConfigurationStorageProvider: this.cardConfigurationStorageProvider, ticketDetail: ticketDetail, localizer: this.localizer));

                case Constants.ManageExpertsAction:
                    this.logger.LogInformation("Sending manage experts card.");
                    string customAPIAuthenticationToken = this.tokenHelper.GenerateAPIAuthToken(applicationBasePath: activity.ServiceUrl, fromId: activity.From.Id, jwtExpiryMinutes: 60);
                    return(CardHelper.GetTaskModuleResponse(applicationBasePath: this.appBaseUrl, customAPIAuthenticationToken: customAPIAuthenticationToken, telemetryInstrumentationKey: this.telemetryClient.InstrumentationKey, activityId: valuesforTaskModule?.ActivityId, localizer: this.localizer));

                default:
                    this.logger.LogInformation($"Invalid command for task module fetch activity.Command is : {command} ");
                    await turnContext.SendActivityAsync(this.localizer.GetString("ErrorMessage"));

                    return(null);
                }
            }
            catch (Exception ex)
            {
                this.logger.LogError(ex, "Error in fetching task module.");
                return(null);

                throw;
            }
        }
Ejemplo n.º 27
0
        public async Task CardRegisteredForOtherUser()
        {
            var db   = DbHelper.GetEmptyTestDB();
            var user = await UserHelper.CreateInDbAsync(db);

            var card = await CardHelper.CreateAsync(db, user);

            await CardSubscriptionHelper.CreateAsync(db, user, card.Id);

            var otherUser = await UserHelper.CreateInDbAsync(db);

            using var dbContext = new MemCheckDbContext(db);
            var result = new CardRegistrationsLoader(dbContext).RunForCardIds(otherUser, card.Id.AsArray());

            Assert.AreEqual(1, result.Count);
            Assert.IsFalse(result[card.Id]);
        }
        public void Given_A_Valid_Monster_CardType_Should_Map_CardType_To_Correct_YgoCardType(string cardType, YgoCardType expected)
        {
            // Arrange
            var yugiohCard = new YugiohCard
            {
                Attribute = "Dark",
                Types     = "Effect/Ritual",
                CardType  = cardType
            };
            var cardInputModel = new CardInputModel();

            // Act
            var result = CardHelper.MapBasicCardInformation(yugiohCard, cardInputModel);

            // Assert
            result.CardType.Should().Be(expected);
        }
Ejemplo n.º 29
0
        private async Task SendCreateNewJobPostingMessage(IDialogContext context)
        {
            IMessageActivity reply = context.MakeMessage();

            reply.Attachments = new List <Attachment>();

            AdaptiveCard card       = CardHelper.CreateCardForNewJobPosting();
            Attachment   attachment = new Attachment()
            {
                ContentType = AdaptiveCard.ContentType,
                Content     = card
            };

            reply.Attachments.Add(attachment);

            await context.PostAsync(reply);
        }
        public async Task OneCardToRepeat()
        {
            var db   = DbHelper.GetEmptyTestDB();
            var user = await UserHelper.CreateInDbAsync(db);

            var deck = await DeckHelper.CreateAsync(db, user, algorithmId : DefaultHeapingAlgorithm.ID);

            var card = await CardHelper.CreateAsync(db, user);

            await DeckHelper.AddCardAsync(db, deck, card.Id, 1, RandomHelper.Date());

            using var dbContext = new MemCheckDbContext(db);
            var request = new GetUnknownCardsToLearn.Request(user, deck, Array.Empty <Guid>(), Array.Empty <Guid>(), 10);
            var cards   = await new GetUnknownCardsToLearn(dbContext.AsCallContext()).RunAsync(request);

            Assert.IsFalse(cards.Cards.Any());
        }
        public async Task OneNeverLearnt()
        {
            var db   = DbHelper.GetEmptyTestDB();
            var user = await UserHelper.CreateInDbAsync(db);

            var deck = await DeckHelper.CreateAsync(db, user, algorithmId : DefaultHeapingAlgorithm.ID);

            var card = await CardHelper.CreateAsync(db, user);

            await DeckHelper.AddNeverLearntCardAsync(db, deck, card.Id);

            using var dbContext = new MemCheckDbContext(db);
            var request = new GetUnknownCardsToLearn.Request(user, deck, Array.Empty <Guid>(), Array.Empty <Guid>(), 10);
            var cards   = await new GetUnknownCardsToLearn(dbContext.AsCallContext()).RunAsync(request);

            Assert.AreEqual(1, cards.Cards.Count());
        }
Ejemplo n.º 32
0
        public FrmSet(SetInfo info, CardHelper cardHelper, PortHelper _232Helper)
        {
            InitializeComponent();
            var newInfo = info.Clone();
            this.cardHelper = cardHelper;
            this._232Helper = _232Helper;
            this.bindingSourceAxis.DataSource = newInfo;
            this.bindingSourceIO.DataSource = newInfo;
            this.bindingSourceOther.DataSource = newInfo;
            this.bindingSourceAbsolutePos.DataSource = newInfo;
            this.bindingSourceButton.DataSource = newInfo;

            var table = new DataTable();
            table.Columns.Add("ID", typeof(int));
            table.Columns.Add("Name");
            table.Rows.Add(1, L.R("FrmSet.SimpleWheel", "普通手轮"));
            table.Rows.Add(2, L.R("FrmSet.AdvWheel", "多功能键手轮"));
            this.cmbShouLunType.Properties.DataSource = table;
            this.cmbShouLunType.Properties.DisplayMember = "Name";
            this.cmbShouLunType.Properties.ValueMember = "ID";

            table = new DataTable();
            table.Columns.Add("ID", typeof(int));
            table.Columns.Add("Name");
            table.Rows.Add(1, L.R("FrmSet.UpLimit", "上负限位"));
            table.Rows.Add(2, L.R("FrmSet.DownLimit", "下负限位"));

            this.cmbMinusLimitMode.Properties.DataSource = table;
            this.cmbMinusLimitMode.Properties.DisplayMember = "Name";
            this.cmbMinusLimitMode.Properties.ValueMember = "ID";

            table = new DataTable();
            table.Columns.Add("ID");
            table.Columns.Add("Name");
            table.Rows.Add("zh-CN", "中文");
            table.Rows.Add("en-US", "English");

            this.lueLanguage.Properties.DataSource = table;
            this.lueLanguage.Properties.DisplayMember = "Name";
            this.lueLanguage.Properties.ValueMember = "ID";

            table = new DataTable();
            table.Columns.Add("ID");
            table.Columns.Add("Name");
            table.Rows.Add("1", L.R("FrmSet.ScriptMode1", "模式1(多行)"));
            table.Rows.Add("2", L.R("FrmSet.ScriptMode2", "模式2(单行)"));

            this.lueScriptMode.Properties.DataSource = table;
            this.lueScriptMode.Properties.DisplayMember = "Name";
            this.lueScriptMode.Properties.ValueMember = "ID";

            table = new DataTable();
            table.Columns.Add("ID", typeof(int));
            table.Columns.Add("Name");
            table.Rows.Add(0,  L.R("FrmSet.ThrowMode1", "普通穿透"));
            table.Rows.Add(1, L.R("FrmSet.ThrowMode2", "位置模式穿透"));

            this.lueThrowMode.Properties.DataSource = table;
            this.lueThrowMode.Properties.DisplayMember = "Name";
            this.lueThrowMode.Properties.ValueMember = "ID";

            table = new DataTable();
            table.Columns.Add("ID", typeof(int));
            table.Columns.Add("Name");
            table.Rows.Add(0, L.R("FrmSet.ThrowStartMode1", "穿透信号"));
            table.Rows.Add(1, L.R("FrmSet.ThrowStartMode2", "最低位置"));

            this.lueThrowStartMode.Properties.DataSource = table;
            this.lueThrowStartMode.Properties.DisplayMember = "Name";
            this.lueThrowStartMode.Properties.ValueMember = "ID";
        }
Ejemplo n.º 33
0
 public FormMain()
 {
     card = new CardHelper(this);
     plcHelper = new PortHelper("COM1");
     if (AbsolutePosSet.UseAbsolutePos || AbsolutePosSet.UseFushiAbsolutePos)
         _232Helper = new PortHelper("COM2");
     jiagongHistory = new List<JiagongHistoryInfo>();
     IOHelper = new IOHelper(card, setting.Set.IOSet, setting.Set.AxisSet, setting.Set.AbsolutePosSet, plcHelper, _232Helper, this);
     ar = new AutoResetEvent(false);
     thread = new Thread(() => OnShowWait());
     thread.Start();
     Thread.Sleep(100);
     InitializeComponent();
     RefreshButton();
     this.KeyPreview = true;
     waitFrm.Ar.Set();
     ar.WaitOne();
 }