Exemplo n.º 1
0
        private async Task <ImageSource> UpdateImageSource(ImageSource imageSource)
        {
            DailyChallengeInfo info = await tableService.GetLatestInfo();

            info.currentSource = imageSource;

            await tableService.SaveLatestInfo(info);

            return(info.currentSource);
        }
Exemplo n.º 2
0
        public async Task <DailyChallengeInfo> GetLatestInfo()
        {
            string rowKey       = "DailyChallengeInfo";
            string partitionKey = typeof(DailyChallengeInfo).ToString();

            try
            {
                TableOperation retrieveOperation = TableOperation.Retrieve <DailyChallengeInfo>(partitionKey, rowKey);
                TableResult    result            = await cloudTable.ExecuteAsync(retrieveOperation);

                DailyChallengeInfo info = result.Result as DailyChallengeInfo;
                if (info == null)
                {
                    List <DailyChallengeUser> basicUsers = new List <DailyChallengeUser>();
                    basicUsers.Add(new DailyChallengeUser()
                    {
                        id       = "1",
                        username = "******"
                    });
                    info = new DailyChallengeInfo()
                    {
                        PartitionKey      = partitionKey,
                        RowKey            = rowKey,
                        currentImageIndex = 0,
                        currentSource     = ImageSource.Bing,
                        users             = new List <DailyChallengeUser>()
                    };
                    await SaveLatestInfo(info);

                    if (info.users == null)
                    {
                        if (info.SerializedUsers == null)
                        {
                            info.users = new List <DailyChallengeUser>();
                        }
                        else
                        {
                            info.users = JsonConvert.DeserializeObject <List <DailyChallengeUser> >(info.SerializedUsers);
                        }
                    }
                }
                if (info.serializableImageSource != null)
                {
                    info.currentSource = (ImageSource)Enum.Parse(typeof(ImageSource), info.serializableImageSource);
                }
                return(info);
            }
            catch (Exception exp)
            {
                //TODO: add some logging
                throw exp;
            }
        }
Exemplo n.º 3
0
        private async Task <int> IncrementAndReturnImageIndex()
        {
            DailyChallengeInfo info = await tableService.GetLatestInfo();

            info.currentImageIndex++;

            if (info.currentImageIndex > 7)
            {
                info.currentImageIndex = 0;
            }

            await tableService.SaveLatestInfo(info);

            return(info.currentImageIndex);
        }
Exemplo n.º 4
0
        public async Task SaveLatestInfo(DailyChallengeInfo info)
        {
            if (info.users == null)
            {
                info.users = new List <DailyChallengeUser>();
            }
            info.SerializedUsers = JsonConvert.SerializeObject(info.users);

            info.serializableImageSource = info.currentSource.ToString();
            info.PartitionKey            = typeof(DailyChallengeInfo).ToString();
            info.RowKey = "DailyChallengeInfo";
            TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(info);

            // Execute the operation.
            TableResult result = await cloudTable.ExecuteAsync(insertOrMergeOperation);
        }
Exemplo n.º 5
0
        private async Task <DialogTurnResult> IntroStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            TelemetryClient.TrackTrace("Main dialog started", Severity.Information, null);
            if (string.IsNullOrEmpty(Configuration["DailyChallengeTableConnectionString"]))
            {
                TelemetryClient.TrackTrace("Connection String not defined", Severity.Error, null);
                await stepContext.Context.SendActivityAsync(
                    MessageFactory.Text("NOTE: Storage Connection String is not configured. To continue, add 'DailyChallengeTableConnectionString' to the appsettings.json file."), cancellationToken);

                return(await stepContext.EndDialogAsync(null, cancellationToken));
            }
            else
            {
                IMessageActivity reply = null;

                TelemetryClient.TrackTrace("Get Daily Challenge and Team Info", Severity.Information, null);
                DailyChallenge dailyChallenge = await tableService.GetDailyChallenge();

                DailyChallengeTeam team = await tableService.getDailyChallengeTeamInfo();

                TelemetryClient.TrackTrace("Check whether today's challenge exists", Severity.Information, null);
                if (dailyChallenge.photoUrl == null)
                {
                    TelemetryClient.TrackTrace("No Daily Challenge so check details", Severity.Information, null);
                    var activity = stepContext.Context.Activity;
                    if (team.ChannelData == null)
                    {
                        team.ChannelData = activity.GetChannelData <TeamsChannelData>();
                    }
                    var teamsChannelData = team.ChannelData;

                    var    channelId = teamsChannelData.Channel.Id;
                    var    tenantId  = teamsChannelData.Tenant.Id;
                    string myBotId   = activity.Recipient.Id;
                    string teamId    = teamsChannelData.Team.Id;
                    string teamName  = teamsChannelData.Team.Name;

                    await this.tableService.SaveDailyChallengeTeamInfo(new DailyChallengeTeam()
                    {
                        ServiceUrl    = activity.ServiceUrl,
                        TeamId        = teamId,
                        TeamName      = teamName,
                        TenantId      = tenantId,
                        InstallerName = "Automatic",
                        BotId         = myBotId,
                        ChannelId     = channelId,
                        ChannelData   = teamsChannelData
                    });

                    reply = MessageFactory.Attachment(new List <Attachment>());
                    Attachment attachment = null;

                    DailyChallengeInfo info = await GetInfo(stepContext);

                    if (info.currentSource == ImageSource.Google)
                    {
                        TelemetryClient.TrackTrace("Current source is Google so get an image", Severity.Information, null);
                        attachment = await GetGoogleImageChoiceAttachment();

                        TelemetryClient.TrackTrace("Loaded Google image", Severity.Information, null);
                    }
                    else
                    {
                        TelemetryClient.TrackTrace("Current source is Bing so get the latest image", Severity.Information, null);
                        int imageIndex = info.currentImageIndex;
                        attachment = await GetBingImageChoiceAttachment(imageIndex);

                        TelemetryClient.TrackTrace("Loaded Bing image", Severity.Information, null);
                    }

                    reply.Attachments.Add(attachment);
                    TelemetryClient.TrackTrace("Sending image reply", Severity.Information, null);
                    return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = (Activity)reply }, cancellationToken));
                }
                else
                {
                    if (!dailyChallenge.resultSet)
                    {
                        // Pass on the check results message from the proactive controller if set
                        PromptOptions options = null;
                        if (stepContext != null && stepContext.Options != null)
                        {
                            options = (PromptOptions)stepContext.Options;
                        }
                        return(await stepContext.ReplaceDialogAsync(nameof(ChallengeGuesserDialog), options, cancellationToken));
                    }
                    else
                    {
                        IMessageActivity winningReply = MessageFactory.Attachment(new List <Attachment>());

                        winningReply.Attachments.Add(AttachmentHelper.ResultCardAttachment(dailyChallenge.winnerName, dailyChallenge.photoUrl, dailyChallenge.winnerGuess, dailyChallenge.distanceToEntry.ToString("#.##"), dailyChallenge.extractedLocation, dailyChallenge.text));
                        await stepContext.Context.SendActivityAsync(winningReply);

                        return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
                    }
                }
            }
        }
Exemplo n.º 6
0
        private async Task <ImageSource> GetImageSource(WaterfallStepContext context)
        {
            DailyChallengeInfo info = await tableService.GetLatestInfo();

            return(info.currentSource);
        }
Exemplo n.º 7
0
        private async Task <int> GetImageIndex(WaterfallStepContext context)
        {
            DailyChallengeInfo info = await tableService.GetLatestInfo();

            return(info.currentImageIndex);
        }
Exemplo n.º 8
0
        private async Task <DailyChallengeInfo> GetInfo(WaterfallStepContext context)
        {
            DailyChallengeInfo info = await tableService.GetLatestInfo();

            return(info);
        }
Exemplo n.º 9
0
        private async Task <DialogTurnResult> IntroStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            DailyChallenge dailyChallenge = await tableService.GetDailyChallenge();

            DailyChallengeInfo info = await tableService.GetLatestInfo();

            DailyChallengeEntriesStatus currentStatus = await CheckWhetherAllEntriesReceived(stepContext, cancellationToken, dailyChallenge, info);

            if (currentStatus.allResultsReceived)
            {
                await CheckResults(stepContext, cancellationToken, dailyChallenge, info);

                return(await stepContext.EndDialogAsync(cancellationToken));
            }
            else
            {
                string messageText = null;
                if (stepContext != null && stepContext.Result != null)
                {
                    messageText = stepContext.Result.ToString();
                }
                else if (stepContext != null && stepContext.Context != null && stepContext.Context.Activity != null && stepContext.Context.Activity.Text != null)
                {
                    messageText = stepContext.Context.Activity.Text;
                }
                else if (stepContext != null && stepContext.Options != null)
                {
                    PromptOptions options = (PromptOptions)stepContext.Options;
                    messageText = options.Prompt.Text;
                }
                if (messageText != null)
                {
                    if (messageText.ToLower().Contains("check results"))
                    {
                        await CheckResults(stepContext, cancellationToken, dailyChallenge, info);

                        return(await stepContext.EndDialogAsync(cancellationToken));
                    }

                    var userEntries = dailyChallenge.entries.FindAll(e => e.userName == stepContext.Context.Activity.From.Name);
                    if (userEntries != null && userEntries.Count > 0)
                    {
                        IMessageActivity beginReply   = MessageFactory.Text($"Sorry {stepContext.Context.Activity.From.Name}, we already have a result from you. Time for the next person.");
                        PromptOptions    beginOptions = new PromptOptions()
                        {
                            Prompt = (Activity)beginReply
                        };
                        return(await stepContext.PromptAsync(nameof(TextPrompt), beginOptions, cancellationToken));
                    }
                    return(await stepContext.NextAsync(messageText));
                }

                IMessageActivity reply = MessageFactory.Attachment(new List <Attachment>());
                reply.Attachments.Add(AttachmentHelper.ImageChosen(dailyChallenge.photoUrl));
                PromptOptions promptOptions = new PromptOptions
                {
                    Prompt = (Activity)reply,
                };
                return(await stepContext.PromptAsync(nameof(TextPrompt), promptOptions, cancellationToken));
            }
        }
Exemplo n.º 10
0
        private async Task CheckResults(WaterfallStepContext stepContext, CancellationToken cancellationToken, DailyChallenge dailyChallenge, DailyChallengeInfo info)
        {
            List <DailyChallengeEntry> todayEntries = dailyChallenge.entries;

            string currentWinningUser     = "";
            string currentWinningEntry    = "";
            double currentWinningDistance = double.MaxValue;


            foreach (var entry in todayEntries)
            {
                if (entry.distanceFrom < currentWinningDistance)
                {
                    currentWinningUser     = entry.userName;
                    currentWinningEntry    = entry.imageResponse;
                    currentWinningDistance = entry.distanceFrom;
                }
            }
            try
            {
                DailyChallengeImage image = await tableService.getDailyChallengeImage();

                dailyChallenge.distanceToEntry = currentWinningDistance;
                dailyChallenge.winnerName      = currentWinningUser;
                dailyChallenge.winnerGuess     = currentWinningEntry;
                dailyChallenge.resultSet       = true;

                await tableService.SaveDailyChallenge(dailyChallenge);

                IMessageActivity reply = MessageFactory.Attachment(new List <Attachment>());

                reply.Attachments.Add(AttachmentHelper.ResultCardAttachment(currentWinningUser.ToString(), image.Url, currentWinningEntry, currentWinningDistance.ToString("#.##"), dailyChallenge.extractedLocation, dailyChallenge.text));
                await stepContext.Context.SendActivityAsync(reply);
            }
            catch (Exception exp)
            {
                Console.WriteLine("Error checking results: " + exp.Message);
            }
            return;
        }
Exemplo n.º 11
0
        private async Task <DailyChallengeEntriesStatus> CheckWhetherAllEntriesReceived(WaterfallStepContext stepContext, CancellationToken cancellationToken, DailyChallenge dailyChallenge, DailyChallengeInfo info)
        {
            try
            {
                // Fill in the "standard" properties for BotMessageReceived
                // and add our own property.
                Logger.LogInformation("Checking whether all entries received");
                DailyChallengeEntriesStatus currentStatus = new DailyChallengeEntriesStatus()
                {
                    allResultsReceived = false
                };

                List <DailyChallengeEntry> todayEntries = dailyChallenge.entries;
                if (info.users == null)
                {
                    info.users = new List <DailyChallengeUser>();
                }
                List <DailyChallengeUser> challengeUsers = new List <DailyChallengeUser>();

                var microsoftAppId       = Configuration["MicrosoftAppId"];
                var microsoftAppPassword = Configuration["MicrosoftAppPassword"];

                var connector = new ConnectorClient(new Uri(stepContext.Context.Activity.ServiceUrl), microsoftAppId, microsoftAppPassword);
                var response  = await connector.Conversations.GetConversationMembersWithHttpMessagesAsync(stepContext.Context.Activity.Conversation.Id);

                //var response = (await connectorClient.Conversations.GetConversationMembersAsync());
                foreach (var user in response.Body)
                {
                    challengeUsers.Add(new DailyChallengeUser()
                    {
                        id       = user.Id,
                        username = user.Name
                    });
                }

                int userCount           = challengeUsers.Count;
                int usersWithEntryCount = 0;

                foreach (var user in challengeUsers)
                {
                    if (todayEntries.Exists(matchingItem => matchingItem.userName == user.username))
                    {
                        usersWithEntryCount++;
                    }
                }

                if (usersWithEntryCount >= userCount)
                {
                    currentStatus.allResultsReceived = true;
                }

                currentStatus.userCount           = userCount;
                currentStatus.usersWithEntryCount = usersWithEntryCount;
                return(currentStatus);
            }
            catch (Exception exp)
            {
                Logger.LogError(exp, $"Error checking whether all entries received: {exp.Message} - {exp.StackTrace}", null);
                throw exp;
            }
        }
Exemplo n.º 12
0
        private async Task <DialogTurnResult> ActStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            BingMapService mapService = new BingMapService(Configuration["BingMapsAPI"]);

            string             guessText = stepContext.Result.ToString();
            DailyChallengeInfo info      = await tableService.GetLatestInfo();

            if (guessText.ToLower().Contains("check results"))
            {
                DailyChallenge dailyChallenge = await tableService.GetDailyChallenge();

                await CheckResults(stepContext, cancellationToken, dailyChallenge, info);

                return(await stepContext.EndDialogAsync(cancellationToken));
            }
            else
            {
                TelemetryClient.TrackTrace("Checking for guess: " + guessText, Severity.Information, null);
                try
                {
                    DailyChallengeEntry entry = await mapService.GetLocationDetails(guessText, Logger);

                    if (entry == null)
                    {
                        var locationSplit = stepContext.Result.ToString().Split(' ');
                        if (locationSplit.Length > 1)
                        {
                            var searchText = guessText.Substring(guessText.IndexOf(' '));
                            entry = await mapService.GetLocationDetails(searchText, Logger);
                        }
                    }

                    if (entry == null)
                    {
                        await stepContext.Context.SendActivityAsync(MessageFactory.Text($"Sorry, bing maps couldn't identify the location '{stepContext.Result.ToString()}'. Please try again."), cancellationToken);

                        return(await stepContext.EndDialogAsync());
                    }
                    else
                    {
                        DailyChallenge dailyChallenge = await tableService.GetDailyChallenge();

                        if (dailyChallenge.entries != null)
                        {
                            var matchingEntries = dailyChallenge.entries.Where <DailyChallengeEntry>(e => e.imageResponse == entry.imageResponse);
                            if (matchingEntries.Count() > 0)
                            {
                                await stepContext.Context.SendActivityAsync(MessageFactory.Text($"Sorry, someone has beaten you to suggesting '{stepContext.Result.ToString()}'. Please try again."), cancellationToken);

                                // This line caused a bit of a meltdown so changing to end dialogue
                                //return await stepContext.BeginDialogAsync(nameof(ChallengeGuesserDialog), null, cancellationToken);
                                return(await stepContext.EndDialogAsync());
                            }
                        }

                        double distanceFromResult = DistanceMeasureHelper.GetDistanceFromResult(entry.latitude, entry.longitude, dailyChallenge.latitude, dailyChallenge.longitude);

                        entry.distanceFrom = distanceFromResult;
                        entry.userName     = stepContext.Context.Activity.From.Name;
                        entry.userId       = stepContext.Context.Activity.From.Id;
                        dailyChallenge.entries.Add(entry);

                        await tableService.SaveDailyChallenge(dailyChallenge);

                        IMessageActivity            reply         = MessageFactory.Attachment(new List <Attachment>());
                        DailyChallengeEntriesStatus currentStatus = await CheckWhetherAllEntriesReceived(stepContext, cancellationToken, dailyChallenge, info);

                        reply.Attachments.Add(AttachmentHelper.AwaitingGuesses(currentStatus.userCount, dailyChallenge.photoUrl, currentStatus.usersWithEntryCount, entry.userName, entry.imageResponse));

                        await stepContext.Context.SendActivityAsync((Activity)reply);

                        return(await stepContext.EndDialogAsync(null, cancellationToken));
                    }
                }
                catch (Exception exp)
                {
                    TelemetryClient.TrackTrace("Error loading results: " + exp.Message + exp.StackTrace, Severity.Error, null);
                    throw exp;
                }
            }
        }