示例#1
0
        private async Task MessageReceivedAsync1(IDialogContext context, IAwaitable <object> result)
        {
            var activity = await result as Activity;
            var reply    = context.MakeMessage();

            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

            if (activity.Value != null)
            {
                JObject res  = JObject.Parse(activity.Value.ToString());
                string  res1 = res.Property("test").Value.ToString();

                AdaptiveCards.AdaptiveCard card3 = new AdaptiveCards.AdaptiveCard();
                card3.Body.Add(new TextBlock()
                {
                    Text = $"Thank you for selecting ! {res1}"
                });
                Attachment attachment3 = new Attachment()
                {
                    ContentType = AdaptiveCards.AdaptiveCard.ContentType,
                    Content     = card3
                };
                reply.Attachments.Add(attachment3);
                await context.PostAsync(reply);

                context.Done("");
            }
        }
示例#2
0
 private async Task HandleSystemMessage(Activity message)
 {
     if (message.Type == ActivityTypes.DeleteUserData)
     {
         // Implement user deletion here
         // If we handle user deletion, return a real message
     }
     else if (message.Type == ActivityTypes.ConversationUpdate)
     {
         IConversationUpdateActivity update = message;
         using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
         {
             var client = scope.Resolve <IConnectorClient>();
             if (update.MembersAdded.Any())
             {
                 var reply = message.CreateReply();
                 foreach (var newMember in update.MembersAdded)
                 {
                     // the bot is always added as a user of the conversation, since we don't
                     // want to display the adaptive card twice ignore the conversation update triggered by the bot
                     if (newMember.Name.ToLower() != "bot")
                     {
                         try
                         {
                             // read the json in from our file
                             string json = File.ReadAllText(HttpContext.Current.Request.MapPath("~\\AdaptiveCards\\MyCard.json"));
                             // use Newtonsofts JsonConvert to deserialized the json into a C# AdaptiveCard object
                             AdaptiveCards.AdaptiveCard card = JsonConvert.DeserializeObject <AdaptiveCards.AdaptiveCard>(json);
                             // put the adaptive card as an attachment to the reply message
                             reply.Attachments.Add(new Attachment
                             {
                                 ContentType = AdaptiveCard.ContentType,
                                 Content     = card
                             });
                         }
                         catch (Exception e)
                         {
                             // if an error occured add the error text as the message
                             reply.Text = e.Message;
                         }
                         await client.Conversations.ReplyToActivityAsync(reply);
                     }
                 }
             }
         }
     }
     else if (message.Type == ActivityTypes.ContactRelationUpdate)
     {
         // Handle add/remove from contact lists
         // Activity.From + Activity.Action represent what happened
     }
     else if (message.Type == ActivityTypes.Typing)
     {
         // Handle knowing tha the user is typing
     }
     else if (message.Type == ActivityTypes.Ping)
     {
     }
 }
        private void _timer_Tick(object sender, EventArgs e)
        {
            if (_dirty)
            {
                _dirty = false;
                try
                {
                    this.cardError.Children.Clear();

                    if (this.textBox.Text.Trim().StartsWith("<"))
                    {
                        var           types = Assembly.GetAssembly(typeof(AdaptiveCard)).ExportedTypes.Where(t => t.IsAssignableFrom(typeof(TypedElement))).ToArray();
                        XmlSerializer ser   = new XmlSerializer(typeof(AdaptiveCard), extraTypes: types);
                        _card = (AdaptiveCard)ser.Deserialize(new StringReader(this.textBox.Text));
                    }
                    else
                    {
                        var result = AdaptiveCard.FromJson(this.textBox.Text);
                        if (result.Card != null)
                        {
                            _card = result.Card;
                        }
                    }

                    this.cardGrid.Children.Clear();
                    if (_card != null)
                    {
                        this.Renderer = new XamlRendererExtended(this.HostConfig)
                        {
                            Resources = this.Resources
                        };
                        var result = this.Renderer.RenderCard(_card);
                        if (result.FrameworkElement != null)
                        {
                            // Wire up click handler
                            result.OnAction += _onAction;

                            var uiCard = result.FrameworkElement;

                            uiCard.Effect = new DropShadowEffect()
                            {
                                BlurRadius    = 15,
                                Direction     = -90,
                                RenderingBias = RenderingBias.Quality,
                                ShadowDepth   = 2
                            };

                            this.cardGrid.Children.Add(uiCard);
                        }
                    }
                }
                catch (Exception err)
                {
                    HandleParseError(err);
                }
            }
        }
示例#4
0
 private FrameworkElement Render(Cards.AdaptiveCard card, out string json)
 {
     try
     {
         RenderedAdaptiveCard rendered = renderer.RenderAdaptiveCard(Convert(card, out json));
         return(rendered.FrameworkElement);
     }
     catch (Exception)
     {
         json = null;
         return(null);
     }
 }
示例#5
0
 private async Task HandleSystemMessage(Activity message)
 {
     if (message.Type == ActivityTypes.DeleteUserData)
     {
         // Implement user deletion here
         // If we handle user deletion, return a real message
     }
     else if (message.Type == ActivityTypes.ConversationUpdate)
     {
         IConversationUpdateActivity update = message;
         using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
         {
             var client = scope.Resolve <IConnectorClient>();
             if (update.MembersAdded.Count > 0)
             {
                 var reply = message.CreateReply();
                 foreach (var newMember in update.MembersAdded)
                 {
                     if (newMember.Name.ToLower() != "bot")
                     {
                         try
                         {
                             string json = File.ReadAllText(HttpContext.Current.Request.MapPath("~\\AdaptiveCards\\MyCard.json"));
                             AdaptiveCards.AdaptiveCard card = JsonConvert.DeserializeObject <AdaptiveCards.AdaptiveCard>(json);
                             reply.Attachments.Add(new Attachment
                             {
                                 ContentType = AdaptiveCard.ContentType,
                                 Content     = card
                             });
                         }
                         catch (Exception e)
                         {
                             reply.Text = e.Message;
                         }
                         await client.Conversations.ReplyToActivityAsync(reply);
                     }
                 }
             }
         }
     }
     else if (message.Type == ActivityTypes.ContactRelationUpdate)
     {
     }
     else if (message.Type == ActivityTypes.Typing)
     {
     }
     else if (message.Type == ActivityTypes.Ping)
     {
     }
 }
示例#6
0
        public async Task Services(IDialogContext context, LuisResult result)
        {
            var reply = context.MakeMessage();

            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
            AdaptiveCards.AdaptiveCard card2 = new AdaptiveCards.AdaptiveCard();
            await Greet(context, result);

            card2.Body.Add(new TextBlock()
            {
                Text = "Please Select:"
            });
            card2.Body.Add(new ChoiceSet()
            {
                Id      = "test",
                Style   = ChoiceInputStyle.Expanded,
                Choices = new List <Choice>()
                {
                    new Choice()
                    {
                        Title = "Service request", Value = "Service request", IsSelected = true
                    },
                    new Choice()
                    {
                        Title = "Incidence", Value = "Incidence"
                    },
                    new Choice()
                    {
                        Title = "Trouble Shooting", Value = "Trouble Shooting"
                    }
                }
            });

            card2.Actions.Add(new SubmitAction()
            {
                Title = "Submit"
            });

            Attachment attachment2 = new Attachment()
            {
                ContentType = AdaptiveCards.AdaptiveCard.ContentType,
                Content     = card2
            };


            reply.Attachments.Add(attachment2);
            await context.PostAsync(reply);

            context.Wait(MessageReceivedAsync1);
        }
示例#7
0
 private RenderCards.AdaptiveCard Convert(Cards.AdaptiveCard source, out string json)
 {
     try
     {
         json = source.ToJson();
         RenderCards.AdaptiveCardParseResult result = RenderCards.AdaptiveCard.FromJsonString(json);
         return(result.AdaptiveCard);
     }
     catch (Exception)
     {
         json = null;
         return(null);
     }
 }
示例#8
0
 private Cards.AdaptiveCard GetCard(AdaptiveItem item)
 {
     Cards.AdaptiveCard card = new Cards.AdaptiveCard()
     {
         Id   = random.Next(1, 100000000).ToString(),
         Body = new List <AdaptiveElement>()
         {
             new Cards.AdaptiveColumnSet()
             {
                 Columns = new List <Cards.AdaptiveColumn>()
                 {
                     new Cards.AdaptiveColumn()
                     {
                         Width = auto,
                         Items = new List <AdaptiveElement>()
                         {
                             new Cards.AdaptiveImage()
                             {
                                 Url = adaptive_card_image
                             }
                         }
                     },
                     new Cards.AdaptiveColumn()
                     {
                         Width = stretch,
                         Items = new List <AdaptiveElement>()
                         {
                             new Cards.AdaptiveTextBlock()
                             {
                                 Text   = item.Title,
                                 Size   = AdaptiveTextSize.ExtraLarge,
                                 Weight = AdaptiveTextWeight.Bolder,
                             },
                             new Cards.AdaptiveTextBlock()
                             {
                                 Text   = item.Body,
                                 Size   = AdaptiveTextSize.Medium,
                                 Weight = AdaptiveTextWeight.Lighter
                             }
                         },
                     }
                 }
             }
         }
     };
     return(card);
 }
示例#9
0
        private IMessageActivity GetAdaptiveCardMessage(IDialogContext context, AdaptiveCards.AdaptiveCard card, string cardName)
        {
            var message = context.MakeMessage();

            if (message.Attachments == null)
            {
                message.Attachments = new List <Attachment>();
            }
            var attachment = new Attachment()
            {
                Content     = card,
                ContentType = "application/vnd.microsoft.card.adaptive",
                Name        = cardName
            };

            message.Attachments.Add(attachment);
            return(message);
        }
示例#10
0
        private void _timer_Tick(object sender, EventArgs e)
        {
            if (_dirty)
            {
                _dirty = false;
                try
                {
                    this.cardError.Children.Clear();

                    if (this.textBox.Text.Trim().StartsWith("<"))
                    {
                        var           types = Assembly.GetAssembly(typeof(AdaptiveCard)).ExportedTypes.Where(t => t.IsAssignableFrom(typeof(TypedElement))).ToArray();
                        XmlSerializer ser   = new XmlSerializer(typeof(AdaptiveCard), extraTypes: types);
                        _card = (AdaptiveCard)ser.Deserialize(new StringReader(this.textBox.Text));
                    }
                    else
                    {
                        _card = JsonConvert.DeserializeObject <AC.AdaptiveCard>(this.textBox.Text);
                    }

                    this.cardGrid.Children.Clear();
                    if (_card != null)
                    {
                        this.Renderer = new XamlRendererExtended(this.HostConfig, this.Resources, _onAction, _OnMissingInput);
                        var uiCard = this.Renderer.RenderAdaptiveCard(_card, hostConfig: HostConfig);
                        uiCard.Effect = new DropShadowEffect()
                        {
                            BlurRadius    = 15,
                            Direction     = -90,
                            RenderingBias = RenderingBias.Quality,
                            ShadowDepth   = 2
                        };

                        this.cardGrid.Children.Add(uiCard);
                    }
                }
                catch (Exception err)
                {
                    HandleParseError(err);
                }
            }
        }
示例#11
0
        private async Task ProcessTeamAsync(ITurnContext <IMessageActivity> turnContext, LuisResult luisResult, CancellationToken cancellationToken)
        {
            //call Power BI
            var token = "H4sIAAAAAAAEACWSR66DVgAA7_K3RKLzIFIW9GJ6h93DBtMxxbQod8-Psp_NjObvHxde_QRfP3_--Cy3kNZrvuy-eVvyRDy6fLSjrNwCKtJ0UqhnRZ8e39QK2jyct0F0PTganpW0ZzgeMWWNiSMug2RNYObZg6xJhVWlD1E651wxSKztxZhOsfzh4HKuvA6ZcOGUGHvaoyA1GIwsdLcVzPHI3u9AxeVb0ggtIr5JhGttKdVNYxtfT0SLLiKMjBQM4ZuGxvruBFjQcTmeMzWwbQJ8fkw4o_DX-JI3PsWRbdEIERaOohUoaQg2Rb4jeo6ukWqSqIG3QT5UhrILRqTvXY993YmVRTd11jz9PcUatk5PhchRo6wtZbJR2lVfHoDw6bGQs2kb7jBsNLVOozZLtEU-kqyC9NTGG19z1zvncRdydxnUw03r28NeoO0fLOEw-OGdR6yY8wu9cD6t44Uce9fNRJPBs9UzitanR8Hjc7GhgoICWS596Jd71IXDBXbTsFbf7ggy6HzZXN6D6aQ1rsYaexitpvpESZj7PnGPRdeRgvimU6HrhhQyG-AzgJ6g3ic7xTr86oBzEjLiVpOq4iKnofAIlYbCv8YrbztTP7Yu1z_6Jzc_3FGLqi1k33MVD3lHCIIKGfkVwBKnEgHvq1fX-FjgGme-Cl8XmTuQnco34W6CIkbwFT7mOHBYu-Cv9_bCb22854ankXv13f0FDPZ7jdjHbY8DHU7B--uvnz9-xOX6bNOjvH433Rkv34mwfxDsnKrRLo-Z8GXSMKoAz5HZxE0ZZ6E3O5vHUFQPyVifyG7GBrsD9r7XhqmR843xvmRZlOgyRFrSDwKtHbOt6gQrQJJ70ru3dY8GczMtRKD2OvcryGf6gcvSPg0fvlLuCvW5Vo6xEKz6lrPqkRAuaPJpWhD43Z9SORcXOgYO7yjgCR63nn50HsvIoikOeiW9NtduztJbZO36qBacoRRnaRupjnKeXrTC_JThGsq9yvubs7uAHCDludvJPnriTLpvtc8Us2JX5TF5kK6kFN18W87KLNvX0e-y6ADSHThr_BDyoGXSUk7GJC0A1rqdATIVk9Wr8k_cksDU6eP_zNenLhc9_q0sa-HBYrXPDFj4colQHAVk-58KmvcIt-9S_mJGoZmkU5FFkBc8DFUC_YZHxVqdAdNDQFRohpf0NA71HRTPTcEjLbwndO-yaK4M7And3vaU2-KDhdfCk8aGrBsmtAl8DdcKHrsbCUaKEiyHbCjZW0Nif6YNSl5Qb8f2Yv9d4MBGLKyaqMyy57t7vpRAzjq96N58cCx3D5Rht3-PKcUY27kvdJ9TjMg2alrXgPR7M20FZwNF2uTTSwkFJsSF7ip6JEiIUNQHYVEKXxYtYhy_h2WQdzKDhRqhe6oDdMKpPYgMSBa0gQOOyTCrhxvIh5dN2VNzJVNI0roCF1E9Y2dHvxq6ZJW2haskWFWK8LH6Wmmcf6yMaKxedgB6lzUv-i_zP_8CPDqOxZoFAAA=.eyJjbHVzdGVyVXJsIjoiaHR0cHM6Ly9ERi1NU0lULVNDVVMtcmVkaXJlY3QuYW5hbHlzaXMud2luZG93cy5uZXQiLCJlbWJlZEZlYXR1cmVzIjp7Im1vZGVybkVtYmVkIjpmYWxzZX19";
            var PBurl = "https://app.powerbi.com/qnaEmbed?groupId=5832e4e8-3075-4f7a-b967-c5604652a29a";

            HttpWebRequest PBrequest = WebRequest.Create(PBurl) as HttpWebRequest;

            PBrequest.KeepAlive     = true;
            PBrequest.Method        = "POST";
            PBrequest.ContentLength = 0;
            PBrequest.ContentType   = "application/json";

            PBrequest.Headers.Add("Authorization", String.Format("Bearer {0}", token));

            var PBresponse = (HttpWebResponse)PBrequest.GetResponse();

            var encoding = ASCIIEncoding.ASCII;

            var reader = new StreamReader(PBresponse.GetResponseStream(), encoding);

            string PBreply = reader.ReadToEnd();

            var card = new AdaptiveCards.AdaptiveCard();

            card.Speak = PBreply;


            if (PBreply != null && PBreply.Length > 0)
            {
                //await turnContext.SendActivityAsync(MessageFactory.Text(PBreply), cancellationToken);
                var attachment = new Attachment();
                attachment.ContentType = "text/html";
                attachment.Content     = card;
                await turnContext.SendActivityAsync(MessageFactory.Attachment(attachment), cancellationToken);
            }
            else
            {
                await turnContext.SendActivityAsync(MessageFactory.Text("No anwers found from PB"), cancellationToken);
            }
        }
 public async Task ShowMenu(IDialogContext context, IAwaitable <IMessageActivity> message, LuisResult luisResult)
 {
     if (luisResult.TopScoringIntent.Score < 0.5)
     {
         await None(context, luisResult);
     }
     else
     {
         Activity reply = ((Activity)context.Activity).CreateReply();
         string   json  = File.ReadAllText(HttpContext.Current.Request.MapPath("~\\AdaptiveCards\\MyCard.json"));
         // use Newtonsofts JsonConvert to deserialized the json into a C# AdaptiveCard object
         AdaptiveCards.AdaptiveCard card = JsonConvert.DeserializeObject <AdaptiveCards.AdaptiveCard>(json);
         // put the adaptive card as an attachment to the reply message
         reply.Attachments.Add(new Attachment
         {
             ContentType = AdaptiveCard.ContentType,
             Content     = card
         });
         await context.PostAsync(reply);
     }
     context.Done <object>(null);
 }
示例#13
0
        private async Task <IMessageActivity> GetNextScubaMessage(ITurnContext context, Activity activity)
        {
            var resultInfo = await new ScubaCardService().GetNextCardText(context, activity);

            if (!string.IsNullOrEmpty(resultInfo.ErrorMessage))
            {
                var reply = activity.CreateReply(resultInfo.ErrorMessage);
                //cortana's turned based nature requires a 'back' button when validation fails
                if (activity.ChannelId == Channel.Channels.Cortana)
                {
                    var backCard = new AdaptiveCards.AdaptiveCard();
                    backCard.Actions.Add(new AdaptiveCards.AdaptiveSubmitAction()
                    {
                        Data  = "Back",
                        Title = "Back"
                    });
                    reply.Attachments.Add(new Attachment()
                    {
                        Content     = backCard,
                        ContentType = AdaptiveCards.AdaptiveCard.ContentType
                    });
                }
                return(reply);
            }

            if (resultInfo.NotifySubscribers)
            {
                var adapter       = context.Adapter;
                var userScubaData = context.GetConversationState <UserScubaData>();
                var credentials   = ((MicrosoftAppCredentials)context.Services.Get <Microsoft.Bot.Connector.IConnectorClient>("Microsoft.Bot.Connector.IConnectorClient").Credentials);

                var conversationRef = new ConversationReference(activity.Id, activity.From, activity.Recipient, activity.Conversation, activity.ChannelId, activity.ServiceUrl);

                Task.Factory.StartNew(async() => await ReservationSubscriptionService.NotifySubscribers(userScubaData, adapter, credentials, conversationRef));
            }

            return(activity.GetReplyFromText(resultInfo.CardText));
        }
示例#14
0
        public async Task Greet(IDialogContext context, LuisResult result)
        {
            var reply = context.MakeMessage();

            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
            AdaptiveCards.AdaptiveCard card1 = new AdaptiveCards.AdaptiveCard();
            card1.Body.Add(new TextBlock()
            {
                Text   = "Welcome to Adaptive card demo",
                Size   = TextSize.Large,
                Weight = TextWeight.Bolder
            });

            // Create the attachment with adapative card.
            Attachment attachment1 = new Attachment()
            {
                ContentType = AdaptiveCards.AdaptiveCard.ContentType,
                Content     = card1
            };

            reply.Attachments.Add(attachment1);
            await context.PostAsync(reply);
        }
示例#15
0
        /// <summary>
        /// The POST method for the ticket controller.
        /// </summary>
        /// <param name="cardResponse">Value from the POST request body.</param>
        /// <returns>The asynchronous task.</returns>
        // POST api/ticket
        public async Task <HttpResponseMessage> Post(Models.CardResponse cardResponse)
        {
            HttpRequestMessage request = this.ActionContext.Request;

            // Validate that we have a bearer token.
            if (request.Headers.Authorization == null ||
                !string.Equals(request.Headers.Authorization.Scheme, BearerTokenType, StringComparison.OrdinalIgnoreCase) ||
                string.IsNullOrEmpty(request.Headers.Authorization.Parameter))
            {
                return(request.CreateErrorResponse(HttpStatusCode.Unauthorized, new HttpError()));
            }

            string bearerToken = request.Headers.Authorization.Parameter;
            ActionableMessageTokenValidator validator = new ActionableMessageTokenValidator();

            // ValidateTokenAsync will verify the following
            // 1. The token is issued by Microsoft and its digital signature is valid.
            // 2. The token has not expired.
            // 3. The audience claim matches the service domain URL.
            ActionableMessageTokenValidationResult result = await validator.ValidateTokenAsync(bearerToken, WebServiceHost);

            if (!result.ValidationSucceeded)
            {
                if (result.Exception != null)
                {
                    Trace.TraceError(result.Exception.ToString());
                }

                return(request.CreateErrorResponse(HttpStatusCode.Unauthorized, new HttpError()));
            }

            // We have a valid token. Your application should verify the sender and/or the ActionPerformer
            //
            // You should also return the CARD-ACTION-STATUS header in the response.
            // The value of the header will be displayed to the user.
            if (!result.Sender.ToLower().EndsWith(SenderEmailDomain))
            {
                HttpResponseMessage errorResponse = request.CreateErrorResponse(HttpStatusCode.Forbidden, new HttpError());
                errorResponse.Headers.Add("CARD-ACTION-STATUS", "Invalid sender or the action performer is not allowed.");
                return(errorResponse);
            }

            // prepare the response
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);

            response.Headers.Add("CARD-ACTION-STATUS", "Comment recorded...");

            // Further business logic code here to process the support ticket.
            #region Business logic code here to process the support ticket.
            List <Models.Comment> comments = new List <Models.Comment>();

            string newComment = cardResponse.Comment;

            if (cardResponse.CachedComments != null)
            {
                JArray cachedComments = (JArray)cardResponse.CachedComments;
                comments.AddRange(cachedComments.ToObject <List <Models.Comment> >());
            }

            // add this comment
            comments.Add(new Models.Comment()
            {
                ActionPerformer = result.ActionPerformer, CommentDate = DateTime.Now, CommentText = newComment
            });

            // create the card
            AdaptiveCards.AdaptiveCard refreshCard = CreateRefreshCard(comments);
            if (refreshCard != null)
            {
                // add the Action.Http block to the card.
                refreshCard.Actions.Add(CreateHttpAction(comments));
                response.Headers.Add("CARD-UPDATE-IN-BODY", "true");

                response.Content = new StringContent(refreshCard.ToJson());
            }
            #endregion

            return(response);
        }
示例#16
0
        private async Task AfterQnA(IDialogContext context, IAwaitable <object> result)
        {
            string message = null;

            try
            {
                message = (string)await result;
            }
            catch (Exception e)
            {
                await context.PostAsync($"QnAMaker: {e.Message}");

                // Wait for the next message
                context.Wait(MessageReceivedAsync);
            }

            // Display the answer from QnA Maker Service
            var answer = message;

            if (((IMessageActivity)context.Activity).Text.ToLowerInvariant().Contains("trivia"))
            {
                // Since we are not needing to pass any message to start trivia, we can use call instead of forward
                context.Call(new TriviaDialog(), AfterTrivia);
            }
            else if (((IMessageActivity)context.Activity).Text.ToLowerInvariant().Contains("joke"))
            {
                // Since we are not needing to pass any message to start trivia, we can use call instead of forward
                context.Call(new JokesDialog(), AfterJoke);
            }
            else if (((IMessageActivity)context.Activity).Text.ToLowerInvariant().Contains("menu"))
            {
                Activity reply = ((Activity)context.Activity).CreateReply();
                try
                {
                    // read the json in from our file
                    string json = File.ReadAllText(HttpContext.Current.Request.MapPath("~\\AdaptiveCards\\MyCard.json"));
                    // use Newtonsofts JsonConvert to deserialized the json into a C# AdaptiveCard object
                    AdaptiveCards.AdaptiveCard card = JsonConvert.DeserializeObject <AdaptiveCards.AdaptiveCard>(json);
                    // put the adaptive card as an attachment to the reply message
                    reply.Attachments.Add(new Attachment
                    {
                        ContentType = AdaptiveCard.ContentType,
                        Content     = card
                    });
                }
                catch (Exception e)
                {
                    // if an error occured add the error text as the message
                    reply.Text = e.Message;
                }
                await context.PostAsync(reply);

                context.Wait(MessageReceivedAsync);
            }
            else if (!string.IsNullOrEmpty(answer))
            {
                Activity reply = ((Activity)context.Activity).CreateReply();

                string[] qnaAnswerData = answer.Split('|');
                string   title         = qnaAnswerData[0];
                string   description   = qnaAnswerData[1];
                string   url           = qnaAnswerData[2];
                string   imageURL      = qnaAnswerData[3];

                if (title == "")
                {
                    char charsToTrim = '|';
                    await context.PostAsync(answer.Trim(charsToTrim));
                }

                else
                {
                    HeroCard card = new HeroCard
                    {
                        Title    = title,
                        Subtitle = description,
                    };
                    card.Buttons = new List <CardAction>
                    {
                        new CardAction(ActionTypes.OpenUrl, "Learn More", value: url)
                    };
                    card.Images = new List <CardImage>
                    {
                        new CardImage(url = imageURL)
                    };
                    reply.Attachments.Add(card.ToAttachment());
                    await context.PostAsync(reply);
                }
                context.Wait(MessageReceivedAsync);
            }
            else
            {
                await context.PostAsync("No good match found in KB.");

                int length = (((IMessageActivity)context.Activity).Text ?? string.Empty).Length;
                await context.PostAsync($"You sent {((IMessageActivity)context.Activity).Text} which was {length} characters");

                context.Wait(MessageReceivedAsync);
            }
        }
示例#17
0
        private async Task AnswerPOQnA(ITurnContext <IMessageActivity> turnContext, LuisResult luisResult, CancellationToken cancellationToken)
        {
            var card = new AdaptiveCards.AdaptiveCard(new AdaptiveSchemaVersion(1, 0));

            //var pictureUrl = "";

            card.Body.Add(new AdaptiveTextBlock()
            {
                Text = "Purchase Order Help"
            });

            //card.Body.Add(new AdaptiveImage()
            //{
            //    Type = "Image",
            //    Url = new Uri(pictureUrl),
            //    Size = AdaptiveImageSize.Medium
            //});

            card.Body.Add(new AdaptiveTextBlock()
            {
                Text  = "Thank you, hope this helps...",
                Color = AdaptiveTextColor.Accent
            });

            var options = new QnAMakerOptions {
                Top = 1
            };
            var response = await myBotServices.POHowToQnA.GetAnswersAsync(turnContext, options);

            if (response != null && response.Length > 0)
            {
                card.Body.Add(new AdaptiveTextBlock()
                {
                    Text  = response[0].Answer,
                    Color = AdaptiveTextColor.Accent
                });

                Attachment attach = new Attachment()
                {
                    ContentType = AdaptiveCard.ContentType,
                    Content     = card
                };

                var msg = MessageFactory.Attachment(new Attachment
                {
                    ContentType = AdaptiveCard.ContentType,
                    Content     = card
                });

                await turnContext.SendActivityAsync(msg, cancellationToken);
            }
            else
            {
                await turnContext.SendActivityAsync(MessageFactory.Text("No anwers found from KB"), cancellationToken);
            }

            //Attachment attach = new Attachment()
            //{
            //    ContentType = AdaptiveCard.ContentType,
            //    Content = card
            //};

            //var options = new QnAMakerOptions { Top = 1 };
            //var response = await myBotServices.POHowToQnA.GetAnswersAsync(turnContext, options);

            //if (response != null && response.Length > 0)
            //{
            //    await turnContext.SendActivityAsync(MessageFactory.Text(response[0].Answer), cancellationToken);
            //}
            //else
            //{
            //    await turnContext.SendActivityAsync(MessageFactory.Text("No anwers found from KB"), cancellationToken);
            //}
        }
示例#18
0
 public FrameworkElement Render(string json)
 {
     Cards.AdaptiveCard card = Parse(json);
     return(Render(card, out json));
 }
示例#19
0
 public FrameworkElement Render(AdaptiveItem item, out string json)
 {
     Cards.AdaptiveCard card = GetCard(item);
     return(Render(card, out json));
 }