public static WikiResult SearchWiki(string queryParameter, ComposeExtensionQuery composeExtensionQuery)
        {
            string searchApiUrl = searchApiUrlFormat.Replace("[keyword]", queryParameter);

            searchApiUrl = searchApiUrl.Replace("[limit]", composeExtensionQuery.QueryOptions.Count + "");
            searchApiUrl = searchApiUrl.Replace("[offset]", composeExtensionQuery.QueryOptions.Skip + "");
            WikiResult wikiResult = null;

            // call Wikipedia API to search
            try
            {
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(searchApiUrl);
                using (HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse())
                {
                    string ResponseText;
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        ResponseText = reader.ReadToEnd();
                        wikiResult   = JsonConvert.DeserializeObject <WikiResult>(ResponseText);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return(wikiResult);
        }
        public void ComposeExtension_GetComposeExtensionData()
        {
            Activity sampleActivity     = JsonConvert.DeserializeObject <Activity>(File.ReadAllText(@"Jsons\SampleActivityComposeExtension.json"));
            ComposeExtensionQuery query = sampleActivity.GetComposeExtensionQueryData();

            Assert.AreEqual("testQuery", query.CommandId);
            Assert.IsTrue(query.Parameters != null && query.Parameters.Count == 1);
            Assert.AreEqual("selectedQueryJson", query.Parameters[0].Name);
            Assert.AreEqual("Value", query.Parameters[0].Value.ToString());
        }
 // return the value of the specified query parameter
 public static string GetQueryParameterByName(ComposeExtensionQuery query, string name)
 {
     if (query.Parameters[0].Name == name)
     {
         return(query.Parameters[0].Value.ToString());
     }
     else
     {
         return("");
     }
 }
        public async Task <WikiResult> SearchWiki(string queryParameter, ComposeExtensionQuery composeExtensionQuery)
        {
            string searchApiUrl = SearchApiUrlFormat.Replace("[keyword]", queryParameter);

            searchApiUrl = searchApiUrl.Replace("[limit]", composeExtensionQuery.QueryOptions.Count + "");
            searchApiUrl = searchApiUrl.Replace("[offset]", composeExtensionQuery.QueryOptions.Skip + "");

            Uri apiUrl = new Uri(searchApiUrl);

            return(await ProcessRequest <WikiResult>(apiUrl));
        }
        // return the value of the specified query parameter
        public string GetQueryParameterByName(ComposeExtensionQuery query, string name)
        {
            foreach (var param in query.Parameters)
            {
                if (param.Name == name)
                {
                    return(param.Value.ToString());
                }
            }

            return("");
        }
        //gavdcodeend 01

        //gavdcodebegin 02
        private async Task <ComposeExtensionResponse> CreateCard(Activity myActivity)
        {
            ComposeExtensionResponse rtnResponse = null;

            ComposeExtensionQuery queryData = myActivity.GetComposeExtensionQueryData();
            string myQuery = string.Empty;
            ComposeExtensionParameter queryParam = queryData.Parameters?.FirstOrDefault(
                par => par.Name == "wikipediaQuery");

            if (queryParam != null)
            {
                myQuery = queryParam.Value.ToString();
            }

            string myText = string.Empty;

            if (string.IsNullOrEmpty(myQuery) == true)
            {
                myText = "Get a query to create the card";
            }
            else
            {
                myText = myQuery;
            }

            string wikiResult = await GetWikipediaSnippet(myText);

            HeroCard myCard = new HeroCard
            {
                Title    = "Wikipedia Card",
                Subtitle = "Searching for: " + myText,
                Text     = wikiResult,
                Images   = new List <CardImage>(),
                Buttons  = new List <CardAction>(),
            };

            myCard.Images.Add(new CardImage
            {
                Url = "https://upload.wikimedia.org/wikipedia/commons/thumb/4/45/" +
                      "Orange_Icon_Pale_Wiki.png/120px-Orange_Icon_Pale_Wiki.png"
            });

            ComposeExtensionAttachment[] myAttachs = new ComposeExtensionAttachment[1];
            myAttachs[0] = myCard.ToAttachment().ToComposeExtensionAttachment();

            rtnResponse = new ComposeExtensionResponse(
                new ComposeExtensionResult("list", "result"));
            rtnResponse.ComposeExtension.Attachments = myAttachs.ToList();

            return(rtnResponse);
        }
        private static string GetQueryParameterByName(ComposeExtensionQuery query, string name)
        {
            if (query?.Parameters == null || query.Parameters.Count == 0)
            {
                return(string.Empty);
            }

            var parameter = query.Parameters[0];

            if (!string.Equals(parameter.Name, name, StringComparison.OrdinalIgnoreCase))
            {
                return(string.Empty);
            }

            return(parameter.Value != null?parameter.Value.ToString() : string.Empty);
        }
Beispiel #8
0
        /// <summary>
        /// Handles compose extension queries.
        /// </summary>
        /// <param name="activity">Incoming request from Bot Framework.</param>
        /// <param name="connectorClient">Connector client instance for posting to Bot Framework.</param>
        /// <returns>Task tracking operation.</returns>
        private static async Task <HttpResponseMessage> HandleComposeExtensionQuery(Activity activity, ConnectorClient connectorClient)
        {
            // Get Compose extension query data.
            ComposeExtensionQuery composeExtensionQuery = activity.GetComposeExtensionQueryData();

            // Process data and return the response.
            ComposeExtensionResponse response = new ComposeExtensionResponse
            {
                ComposeExtension = new ComposeExtensionResult
                {
                    Attachments = new List <ComposeExtensionAttachment>
                    {
                        new HeroCard
                        {
                            Buttons = new List <CardAction>
                            {
                                new CardAction
                                {
                                    Image = "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/Bing_logo_%282016%29.svg/160px-Bing_logo_%282016%29.svg.png",
                                    Type  = ActionTypes.OpenUrl,
                                    Title = "Bing",
                                    Value = "https://www.bing.com"
                                },
                            },
                            Title    = "SampleHeroCard",
                            Subtitle = "BingHeroCard",
                            Text     = "Bing.com"
                        }.ToAttachment().ToComposeExtensionAttachment()
                    },
                    Type             = "result",
                    AttachmentLayout = "list"
                }
            };

            StringContent       stringContent       = new StringContent(JsonConvert.SerializeObject(response));
            HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);

            httpResponseMessage.Content = stringContent;
            return(httpResponseMessage);
        }
        private async Task <HttpResponseMessage> ProcessQueryAction(HttpRequestMessage request, ComposeExtensionQuery extensionQueryData, CancellationToken cancellationToken)
        {
            if (extensionQueryData.Parameters == null)
            {
                return(request.CreateResponse(HttpStatusCode.NoContent));
            }

            var isInitialRun        = false;
            var initialRunParameter = GetQueryParameterByName(extensionQueryData, "initialRun");

            // situation where the incoming payload was received from the config popup
            if (extensionQueryData.State.HasValue())
            {
                initialRunParameter = "true";
            }

            if (string.Equals(initialRunParameter, "true", StringComparison.OrdinalIgnoreCase))
            {
                isInitialRun = true;
            }

            var maxResults = extensionQueryData.QueryOptions.Count ?? 25;

            if (isInitialRun)
            {
                maxResults = 5;
            }

            var attachments = new List <ComposeExtensionAttachment>();

            var searchText = GetQueryParameterByName(extensionQueryData, MessagingExtensionCommands.SearchTextParameterName);

            switch (extensionQueryData.CommandId)
            {
            case MessagingExtensionCommands.SearchPositions:
                var positions = await _positionService.Search(searchText, maxResults, cancellationToken);

                attachments = _mapper.Map <List <ComposeExtensionAttachment> >(positions);
                break;

            case MessagingExtensionCommands.SearchCandidates:
                var candidates = await _candidateService.Search(searchText, maxResults, cancellationToken);

                attachments = _mapper.Map <List <ComposeExtensionAttachment> >(candidates);
                break;
            }

            var response = new ComposeExtensionResponse
            {
                ComposeExtension = new ComposeExtensionResult
                {
                    Type             = "result",
                    Attachments      = attachments,
                    AttachmentLayout = AttachmentLayoutTypes.List
                }
            };

            return(request.CreateResponse(HttpStatusCode.OK, response));
        }
        public async Task <HttpResponseMessage> HandleQueryAction(HttpRequestMessage request, ComposeExtensionQuery extensionQueryData, CancellationToken cancellation = default)
        {
            if (extensionQueryData.Parameters == null)
            {
                return(request.CreateResponse(HttpStatusCode.NoContent));
            }

            var isInitialRun        = false;
            var initialRunParameter = GetQueryParameterByName(extensionQueryData, "initialRun");

            // situation where the incoming payload was received from the config popup
            if (!string.IsNullOrEmpty(extensionQueryData.State))
            {
                initialRunParameter = "true";
            }

            if (string.Equals(initialRunParameter, "true", StringComparison.OrdinalIgnoreCase))
            {
                isInitialRun = true;
            }

            var maxResults = extensionQueryData.QueryOptions.Count ?? 25;

            if (isInitialRun)
            {
                maxResults = 5;
            }

            var attachments = new List <ComposeExtensionAttachment>();



            //var searchText = GetQueryParameterByName(extensionQueryData, "searchText");

            var currentUser = GetQueryParameterByName(extensionQueryData, "userId");

            var graphService = RestService.For <IGraphRestAPIService>(
                new HttpClient(new AuthenticatedHttpClientHandler(request.Headers.Authorization.Parameter))
            {
                BaseAddress = new Uri("https://graph.microsoft.com")
            });

            var events = graphService.FindCurrentEvents(currentUser, DateTime.Now);

            attachments = this.mapper.Map <List <ComposeExtensionAttachment> >(events);

            var response = new ComposeExtensionResponse
            {
                ComposeExtension = new ComposeExtensionResult
                {
                    Type             = "result",
                    Attachments      = attachments,
                    AttachmentLayout = AttachmentLayoutTypes.List
                }
            };


            return(request.CreateResponse(HttpStatusCode.OK, response));
        }
Beispiel #11
0
        /// <summary>
        /// Handles compose extension queries.
        /// </summary>
        /// <param name="activity">Incoming request from Bot Framework.</param>
        /// <param name="connectorClient">Connector client instance for posting to Bot Framework.</param>
        /// <returns>Task tracking operation.</returns>
        private static HttpResponseMessage HandleComposeExtensionQuery(Activity activity, ConnectorClient connectorClient)
        {
            // Get Compose extension query data.
            ComposeExtensionQuery composeExtensionQuery = activity.GetComposeExtensionQueryData();

            var searchTerm = composeExtensionQuery.Parameters.Single(p => p.Name == "Location").Value.ToString();

            var catalog = Products.Instance;
            var results = catalog.ProductCatalog.Where(p => p.SKU.StartsWith(searchTerm)).ToList();
            ComposeExtensionResponse response;

            if (results.Count > 0)
            {
                var attachments = new List <ComposeExtensionAttachment>();
                int i           = 1;
                foreach (var item in results)
                {
                    var result = new HeroCard
                    {
                        Buttons = new List <CardAction>
                        {
                            new CardAction
                            {
                                Type  = ActionTypes.OpenUrl,
                                Title = "Show in CMS",
                                Value = "https://www.bing.com"
                            },
                        },
                        Title    = $"{item.Name} - {item.SKU}",
                        Subtitle = "Item #" + item.SKU,
                        Text     = item.NumberInStock + " in stock.",
                        Images   = new List <CardImage>()
                        {
                            new CardImage()
                            {
                                Url = "https://placekitten.com/420/320?image=" + i
                            }
                        }
                    };
                    attachments.Add(result.ToAttachment().ToComposeExtensionAttachment());
                    i++;
                }



                response = new ComposeExtensionResponse
                {
                    ComposeExtension = new ComposeExtensionResult
                    {
                        Attachments      = attachments,
                        Type             = "result",
                        AttachmentLayout = "list"
                    }
                };
            }
            else
            {
                // Process data and return the response.
                response = new ComposeExtensionResponse
                {
                    ComposeExtension = new ComposeExtensionResult
                    {
                        Attachments = new List <ComposeExtensionAttachment>
                        {
                            new HeroCard
                            {
                                Title = "No results..."
                            }.ToAttachment().ToComposeExtensionAttachment()
                        },
                        Type             = "result",
                        AttachmentLayout = "list"
                    }
                };
            }


            StringContent       stringContent       = new StringContent(JsonConvert.SerializeObject(response));
            HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);

            httpResponseMessage.Content = stringContent;
            return(httpResponseMessage);
        }
        // Query task
        private static ComposeExtensionResponse QueryData(ConnectorClient connector, Activity activity, ComposeExtensionQuery query)
        {
            var keyword    = "";
            var titleParam = query.Parameters?.FirstOrDefault(p => p.Name == "keyword");

            if (titleParam != null)
            {
                keyword = titleParam.Value.ToString();
            }

            if (string.IsNullOrEmpty(keyword))
            {
                return(null);
            }

            var filteredItems = ItemDB.SearchItems(keyword);

            if (filteredItems == null || filteredItems.Count <= 0)
            {
                return(new ComposeExtensionResponse(new ComposeExtensionResult("list", "result")));
            }

            var attachments = new List <ComposeExtensionAttachment>();

            foreach (var item in filteredItems)
            {
                attachments.Add(GetItemAttachment(item));
            }

            var response = new ComposeExtensionResponse(new ComposeExtensionResult("list", "result"));

            response.ComposeExtension.Attachments = attachments.ToList();

            return(response);
        }