public async Task <VideoIndexerSearchResult> SearchAsync(string query = "", string face = "")
        {
            if (string.IsNullOrEmpty(query) == true && string.IsNullOrEmpty(face) == true)
            {
                return(default(VideoIndexerSearchResult));
            }

            Dictionary <string, string> queryParams = new Dictionary <string, string>()
            {
                { "query", WebUtility.UrlEncode(query) },
                { "face", WebUtility.UrlEncode(face) },
            };

            IEnumerable <string> queryString = queryParams
                                               .Where(p => string.IsNullOrEmpty(p.Value) == false)
                                               .Select(p => p.Key + "=" + p.Value);

            string searchQuery = queryString.Count() == 1 ? queryString.FirstOrDefault() : string.Join("&", queryString);

            // Get request uri
            string searchUrl  = this.BaseServiceUrl + "?" + searchQuery;
            Uri    requestUri = new Uri(searchUrl);

            // Get response
            VideoIndexerSearchResult result = await HttpClientUtility.GetAsync <VideoIndexerSearchResult>(requestUri, this.RequestHeaders);

            return(result);
        }
        /// <summary>
        /// Analyze key phrases with text
        /// </summary>
        public async Task <TextAnalyticsResult <TextAnalyticsKeyPhrasesResult> > AnalyzeKeyPhrasesAsync(string fullText)
        {
            if (string.IsNullOrEmpty(fullText) == true)
            {
                return(default(TextAnalyticsResult <TextAnalyticsKeyPhrasesResult>));
            }

            // Get request uri
            Uri requestUri = new Uri(this.BaseServiceUrl + "keyPhrases");

            var document = new
            {
                id   = Guid.NewGuid().ToString(),
                text = fullText
            };

            // Create content of the request
            var content = new
            {
                documents = new object[] { document }
            };

            // Get response
            return(await HttpClientUtility.PostAsJsonAsync <TextAnalyticsResult <TextAnalyticsKeyPhrasesResult> >(requestUri, this.RequestHeaders, content));
        }
Esempio n. 3
0
        public async Task <SpeakerProfilesResponse> GetProfilesAsync(VoiceProfileType profileType)
        {
            string speakerUrl = profileType == VoiceProfileType.TextIndependentVerification ? this.SPEAKER_VERIFICATION_URL : this.SPEAKER_IDENTIFICATION_URL;
            Uri    requestUri = new Uri($"{this.BaseServiceUrl}{speakerUrl}");

            return(await HttpClientUtility.GetAsync <SpeakerProfilesResponse>(requestUri, this.RequestHeaders));
        }
Esempio n. 4
0
        public void Static_DirectoryBrowserDefaults(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                string applicationUrl = deployer.Deploy(hostType, DirectoryBrowserDefaultsConfiguration);

                HttpResponseMessage response = null;

                //1. Check directory browsing enabled at application level
                var responseText = HttpClientUtility.GetResponseTextFromUrl(applicationUrl, out response);
                Assert.True(!string.IsNullOrWhiteSpace(responseText), "Received empty response");
                Assert.True((response.Content).Headers.ContentType.ToString() == "text/html; charset=utf-8");
                Assert.Contains("RequirementFiles/", responseText);

                //2. Check directory browsing @RequirementFiles with a ending '/'
                responseText = HttpClientUtility.GetResponseTextFromUrl(applicationUrl + "RequirementFiles/", out response);
                Assert.True(!string.IsNullOrWhiteSpace(responseText), "Received empty response");
                Assert.True((response.Content).Headers.ContentType.ToString() == "text/html; charset=utf-8");
                Assert.True(responseText.Contains("Dir1/") && responseText.Contains("Dir2/") && responseText.Contains("Dir3/"), "Directories Dir1, Dir2, Dir3 not found");

                //2. Check directory browsing @RequirementFiles with request path not ending '/'
                responseText = HttpClientUtility.GetResponseTextFromUrl(applicationUrl + "RequirementFiles", out response);
                Assert.True(!string.IsNullOrWhiteSpace(responseText), "Received empty response");
                Assert.True((response.Content).Headers.ContentType.ToString() == "text/html; charset=utf-8");
                Assert.True(responseText.Contains("Dir1/") && responseText.Contains("Dir2/") && responseText.Contains("Dir3/"), "Directories Dir1, Dir2, Dir3 not found");
            }
        }
Esempio n. 5
0
        public ActionResult LostCoffee(CoffeeInit req)
        {
            var    clientInfo = this.TempData["ClientInfo"] as ClientInfo;
            string EtmID      = clientInfo.EtmCode;
            //string EtmID = "ETM0027";
            var list = ObjectXmlSerializer.LoadFromXml <List <CoffeeInit> >(Server.MapPath("~/cache/Coffee.xml"));

            if (list.Find(o => o.EtmID == EtmID).CupNumber < req.CupNumber)
            {
                return(this.Json(new { retCode = 1, Message = "提交失败,饮品剩余数量不足!" }));
            }
            list.Find(o => o.EtmID == EtmID).CupNumber -= req.CupNumber;
            //检测剩余杯数,发短信
            try
            {
                if (list.Find(o => o.EtmID == EtmID).CupNumber <= int.Parse(ConfigurationManager.AppSettings["EnableSmsCupNumber"]) && list.Find(o => o.EtmID == EtmID).SendSMS == "0" && ConfigurationManager.AppSettings["EnableSms"] == "true")
                {
                    list.Find(o => o.EtmID == EtmID).CupNumber = 1;
                    const string takedateUrl = "api/Coffee/SendSms";
                    var          fullPath    = ETong.Coffee.Web.Models.Config.GetApiFullPath(takedateUrl);
                    var          client      = new HttpClientUtility(new Uri(fullPath));
                    Logger.Write(Log.Log_Type.Info, string.Format("调用{0}", fullPath));
                    var resultT = SecurityHttpClient.Post <string, ResponseData <string> >(fullPath, EtmID);
                    Logger.Write(Log.Log_Type.Info, string.Format("{0}结束,result={1}", fullPath, Json(resultT.dataMap)));
                }
            }
            catch (Exception ex)
            {
                Logger.Write(Log.Log_Type.Info, string.Format("短信发送失败etmid={0},err={1}", EtmID, ex.ToString()));
            }
            Logger.Write(Log.Log_Type.Info, string.Format("减库存etmid={0},CupNumber={1}", EtmID, req.CupNumber));
            ObjectXmlSerializer.SaveToXml <List <CoffeeInit> >(Server.MapPath("~/cache/Coffee.xml"), list);
            return(this.Json(new { retCode = 0, Message = "成功" }));
        }
Esempio n. 6
0
        public static string GetSimpleImageFromUrl(string url)
        {
            try
            {
                var uri = new Uri(url);

                string filename = Path.GetFileName(uri.LocalPath);

                if (filename.EndsWith(".jpg") || filename.EndsWith(".png") || filename.EndsWith(".jpeg") || filename.EndsWith(".gif"))
                {
                    return(url);
                }
                else
                {
                    var             domain    = HttpClientUtility.GetDomainFromUrl(url).ToLower();
                    IAcquisitionAPI simpleApi = null;
                    if (_simpleAPIs.TryGetValue(domain, out simpleApi))
                    {
                        return(simpleApi.GetImageFromUri(uri));
                    }
                    else
                    {
                        return(string.Empty);
                    }
                }
            }
            catch
            {
                return(string.Empty);
            }
        }
Esempio n. 7
0
        public async Task <HttpResponseMessage> RecognizeAsync(JObject json)
        {
            Uri requestUri = new Uri($"{this.BaseServiceUrl}{inkRecognitionUrl}");
            HttpResponseMessage httpResponse = await HttpClientUtility.PutAsJsonAsync(requestUri, this.RequestHeaders, json);

            return(httpResponse);
        }
Esempio n. 8
0
        public void ExplicitlyRegisterOwinHttpHandler()
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                deployer.AutomaticAppStartupInWebHost = false;
                string url           = deployer.Deploy(HostType.IIS);
                var    webConfigPath = deployer.GetWebConfigPath();

                var addHandler = "<system.webServer>" +
                                 "<handlers>" +
                                 "<add name=\"Owin\" verb=\"*\" type=\"Microsoft.Owin.Host.SystemWeb.OwinHttpHandler, Microsoft.Owin.Host.SystemWeb\" path=\"*\" />" +
                                 "</handlers>" +
                                 "</system.webServer>";

                var configuration = new XmlDocument()
                {
                    InnerXml = File.ReadAllText(webConfigPath)
                };
                var configurationNode = configuration.SelectSingleNode("/configuration");
                configurationNode.InnerXml += addHandler;
                File.WriteAllText(webConfigPath, configuration.InnerXml);

                ((WebDeployer)deployer.Application).Application.Deploy("Default.aspx", File.ReadAllText("RequirementFiles\\Default.aspx"));

                Assert.Equal(Startup.RESULT, HttpClientUtility.GetResponseTextFromUrl(url + "/Default.aspx"));
                Assert.Equal(Startup.RESULT, HttpClientUtility.GetResponseTextFromUrl(url));
            }
        }
Esempio n. 9
0
        public IHttpActionResult Register(RegisterRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                var response = RequestServiceFactory.Instance.Resolve <RegisterService>().ProcessRequest(request);

                var    AuthEndPoint = ConfigurationManager.AppSettings.Get("AuthEndPoint").ToString();
                string path         = String.Format("{0}Token", AuthEndPoint);

                FormUrlEncodedContent content = new FormUrlEncodedContent(new List <KeyValuePair <String, String> >
                {
                    new KeyValuePair <String, String>("grant_type", "password"),
                    new KeyValuePair <String, String>("userName", request.Email),
                    new KeyValuePair <String, String>("password", request.Password)
                });

                return(Ok(HttpClientUtility.Post <TokenResponse, ErrorResult>(path, content)));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Esempio n. 10
0
        public async Task <T> ExecuteAsync <T>(IWeChatPayRequest <T> request) where T : WeChatPayResponse
        {
            // 字典排序
            var sortedTxtParams = new WeChatPayDictionary(request.GetParameters())
            {
                { mch_id, Options.MchId },
                { nonce_str, Guid.NewGuid().ToString("N") }
            };

            if (string.IsNullOrEmpty(sortedTxtParams.GetValue(appid)))
            {
                sortedTxtParams.Add(appid, Options.AppId);
            }

            sortedTxtParams.Add(sign, WeChatPaySignature.SignWithKey(sortedTxtParams, Options.Key));
            var content = WeChatPayUtility.BuildContent(sortedTxtParams);

            Logger?.LogTrace(0, "Request:{content}", content);

            using (var client = ClientFactory.CreateClient())
            {
                var body = await HttpClientUtility.DoPostAsync(client, request.GetRequestUrl(), content);

                Logger?.LogTrace(1, "Response:{body}", body);

                var parser = new WeChatPayXmlParser <T>();
                var rsp    = parser.Parse(body);
                CheckResponseSign(rsp);
                return(rsp);
            }
        }
Esempio n. 11
0
        public async Task <ActionResult> Edit(int id, Post post)
        {
            try
            {
                var file = Request.Files["ImageFile"];
                if (file != null)
                {
                    MemoryStream ms = new MemoryStream();

                    file.InputStream.CopyTo(ms);
                    byte[] bytes = ms.ToArray();
                    string b64   = Convert.ToBase64String(bytes);
                    post.Image = b64;
                }

                string json = HttpClientUtility.JsonConverterClass <Post> .ObjectToJsonString(post);

                string response = await HttpClientUtility.Post(ApiUrls.EDIT_POST_URL, json, Login.AuthorizationHeader(), false);

                // return RedirectToAction("Index");
                return(View(post));
            }
            catch
            {
                return(View(post));
            }
        }
        public void ApplicationPoolStop(HostType hostType)
        {
            var serverInstance = new NotificationServer();

            serverInstance.StartNotificationService();
            try
            {
                using (ApplicationDeployer deployer = new ApplicationDeployer())
                {
                    string applicationUrl = deployer.Deploy(hostType, Configuration);
                    Assert.True(HttpClientUtility.GetResponseTextFromUrl(applicationUrl) == "SUCCESS");

                    if (hostType == HostType.IIS)
                    {
                        string webConfig        = deployer.GetWebConfigPath();
                        string webConfigContent = File.ReadAllText(webConfig);
                        File.WriteAllText(webConfig, webConfigContent);
                    }
                }

                bool receivedNotification = serverInstance.NotificationReceived.WaitOne(20 * 1000);
                Assert.True(receivedNotification, "Cancellation token was not issued on closing host");
            }
            finally
            {
                serverInstance.Dispose();
            }
        }
        public void GetNoEndpointUrlPassedShouldThrowException()
        {
            var httpClientUtility = new HttpClientUtility();

            Assert.ThrowsAnyAsync <NullReferenceException>(() => httpClientUtility.Get <object>(null));
            Assert.ThrowsAnyAsync <NullReferenceException>(() => httpClientUtility.Get <object>(string.Empty));
        }
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            //Request headers
            var subscriptionKey = request.DataStore.GetValue("CognitiveServiceKey");
            Dictionary <string, string> customHeader = new Dictionary <string, string>();

            customHeader.Add("Ocp-Apim-Subscription-Key", subscriptionKey);

            HttpClientUtility client = new HttpClientUtility();
            //Request body
            var result = await client.ExecuteGenericAsync(HttpMethod.Post, $"https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment", "", "", customHeader);

            var responseString = await result.Content.ReadAsStringAsync();

            if (result.StatusCode == HttpStatusCode.BadRequest)
            {
                var obj = JsonUtility.GetJObjectFromJsonString(responseString);
                return(new ActionResponse(ActionStatus.Success));
            }

            if (result.StatusCode == HttpStatusCode.Unauthorized)
            {
                var obj = JsonUtility.GetJObjectFromJsonString(responseString);
                return(new ActionResponse(ActionStatus.FailureExpected));
            }

            return(new ActionResponse(ActionStatus.Failure));
        }
Esempio n. 15
0
        public void InstanceContext(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                string   applicationUrl = deployer.Deploy <InstanceContextStartup>(hostType);
                string[] urls           = new string[] { applicationUrl, applicationUrl + "/one", applicationUrl + "/two" };

                bool failed = false;

                foreach (string url in urls)
                {
                    string previousResponse = null;
                    for (int count = 0; count < 3; count++)
                    {
                        string currentResponse = HttpClientUtility.GetResponseTextFromUrl(url);

                        if (!currentResponse.Contains("SUCCESS") || (previousResponse != null && currentResponse != previousResponse))
                        {
                            failed = true;
                        }

                        previousResponse = currentResponse;
                    }
                }

                Assert.True(!failed, "At least one of the instance contexts is not correct");
            }
        }
Esempio n. 16
0
        public async Task <T> ExecuteAsync <T>(IQPayCertificateRequest <T> request, string certificateName = "Default") where T : QPayResponse
        {
            // 字典排序
            var sortedTxtParams = new QPayDictionary(request.GetParameters())
            {
                { MCHID, Options.MchId },
                { NONCE_STR, Guid.NewGuid().ToString("N") }
            };

            if (string.IsNullOrEmpty(sortedTxtParams.GetValue(APPID)))
            {
                sortedTxtParams.Add(APPID, Options.AppId);
            }

            sortedTxtParams.Add(SIGN, QPaySignature.SignWithKey(sortedTxtParams, Options.Key));
            var content = QPayUtility.BuildContent(sortedTxtParams);

            Logger?.LogTrace(0, "Request:{content}", content);

            using (var client = ClientFactory.CreateClient(QPayOptions.CertificateClientName + "." + certificateName))
            {
                var body = await HttpClientUtility.DoPostAsync(client, request.GetRequestUrl(), content);

                Logger?.LogTrace(1, "Response:{body}", body);

                var parser = new QPayXmlParser <T>();
                var rsp    = parser.Parse(body);
                CheckResponseSign(rsp);
                return(rsp);
            }
        }
Esempio n. 17
0
        public async Task <ActionResult> Login(string username, string password)
        {
            try
            {
                Dictionary <string, string> loginParams = FriendZoneWeb.Models.Login.getTokenRequestParams(username, password);
                string json = HttpClientUtility.JsonConverterClass <Dictionary <string, string> > .ObjectToJsonString(loginParams);

                string response = await HttpClientUtility.Post(ApiUrls.LOGIN_TOKEN_URL, json);

                Login res = HttpClientUtility.JsonConverterClass <Login> .JsonToObject(response);

                System.Diagnostics.Debug.WriteLine(res.roles);
                if (ADMIN_ROLE == res.roles)
                {
                    this.Session["AccessToken"] = res.access_token;
                    this.Session.Timeout        = 120;
                    return(RedirectToAction("index", "dashboard"));
                }
                else
                {
                    if (Models.Login.INVALID_GRANT == res.error)
                    {
                        return(View(model: Models.Login.INVALID_CREDIDENTIAL));
                    }
                    else
                    {
                        return(View(model: Models.Login.UNKNOWN_ERROR));
                    }
                }
            }
            catch (HttpRequestException e)
            {
                return(View(model: Models.Login.UNKNOWN_ERROR));
            }
        }
Esempio n. 18
0
        // GET: Post
        public async Task <ActionResult> Index()
        {
            var response = await HttpClientUtility.Get(ApiUrls.ALL_POSTS_URL);

            List <Post> model = HttpClientUtility.JsonConverterClass <List <Post> > .JsonToObject(response);

            return(View(model));
        }
Esempio n. 19
0
        // GET: User/Edit/5
        public async Task <ActionResult> Edit(int id)
        {
            var response = await HttpClientUtility.Get($"{ApiUrls.GET_USER_URL}{id}", Login.AuthorizationHeader());

            User model = HttpClientUtility.JsonConverterClass <User> .JsonToObject(response);

            return(View(model));
        }
Esempio n. 20
0
        // GET: User
        public async Task <ActionResult> Index()
        {
            var response = await HttpClientUtility.Get(ApiUrls.ALL_USERS_URL, Login.AuthorizationHeader());

            IEnumerable <User> model = HttpClientUtility.JsonConverterClass <List <User> > .JsonToObject(response);

            return(View(model));
        }
Esempio n. 21
0
 public void ConvertibleMiddlewareTest(HostType hostType)
 {
     using (ApplicationDeployer deployer = new ApplicationDeployer())
     {
         string applicationUrl = deployer.Deploy <ConvertibleMiddleWarePatternStartup>(hostType);
         Assert.Equal("SUCCESS", HttpClientUtility.GetResponseTextFromUrl(applicationUrl));
     }
 }
Esempio n. 22
0
        // GET: Post/Edit/5
        public async Task <ActionResult> Edit(int id)
        {
            var response = await HttpClientUtility.Get($"{ApiUrls.GET_POST_URL}{id}");

            Post model = HttpClientUtility.JsonConverterClass <Post> .JsonToObject(response);

            return(View(model));
        }
Esempio n. 23
0
 public void OwinAbstractMiddleware(HostType hostType)
 {
     using (ApplicationDeployer deployer = new ApplicationDeployer())
     {
         string applicationUrl = deployer.Deploy(hostType, OwinAbstractMiddlewareConfiguration);
         Assert.Equal("SUCCESS", HttpClientUtility.GetResponseTextFromUrl(applicationUrl));
     }
 }
Esempio n. 24
0
 public void AllowedConfigurationSignature1(HostType hostType)
 {
     using (ApplicationDeployer deployer = new ApplicationDeployer())
     {
         string applicationUrl = deployer.Deploy <AllowedNonDefaultConfigurationSignatures1>(hostType);
         Assert.Equal("SUCCESS", HttpClientUtility.GetResponseTextFromUrl(applicationUrl));
     }
 }
Esempio n. 25
0
        /// <summary>
        /// 更改组织
        /// </summary>
        /// <param name="organizationId"></param>
        /// <returns></returns>
        public OperationResult ChangeOrganization(string organizationId)
        {
            OperationResult result = new OperationResult();

            var token = GetToken();

            if (string.IsNullOrWhiteSpace(token))
            {
                result.Success = false;
                result.Messages.Add("token 为空,请重新登录");
                return(result);
            }

            var tokenDTO = _cacheClient.Query <TokenDTO>(new CacheFilter()
            {
                Key = token
            });

            if (tokenDTO == null)
            {
                result.Success = false;
                result.Messages.Add("token 为空,请重新登录");
                return(result);
            }

            //查找组织信息
            HttpClientUtility httpClient = new HttpClientUtility();

            httpClient.SetRequestHeaders("token", token);
            var organization = httpClient.Get <List <OrganizationViewModel> >(_requestOrganizationUrl + "?id=" + organizationId).FirstOrDefault();

            if (organization == null)
            {
                result.Success = false;
                result.Messages.Add($"id为{organizationId}的组织不存在");
                return(result);
            }

            if (!organization.IsActive)
            {
                result.Success = false;
                result.Messages.Add($"id为{organizationId}的组织不存在或者已经禁用");
                return(result);
            }

            tokenDTO.OrganizationId = organizationId;

            _cacheClient.Update(new CacheModel()
            {
                Key = token, Data = tokenDTO
            });

            result.Success = true;

            result.Data = organization;

            return(result);
        }
Esempio n. 26
0
        public async Task <T> ExecuteAsync <T>(IJDPayRequest <T> request) where T : JDPayResponse
        {
            // 字典排序
            var sortedTxtParams = new JDPayDictionary(request.GetParameters());

            var content = BuildEncryptXml(request, sortedTxtParams);

            Logger?.LogTrace(0, "Request:{content}", content);

            using (var client = ClientFactory.CreateClient(JDPayOptions.DefaultClientName))
            {
                var body = await HttpClientUtility.DoPostAsync(client, request.GetRequestUrl(), content);

                Logger?.LogTrace(1, "Response:{content}", body);

                var parser = new JDPayXmlParser <T>();
                var rsp    = parser.Parse(JDPayUtility.FotmatXmlString(body));
                if (!string.IsNullOrEmpty(rsp.Encrypt))
                {
                    var encrypt          = rsp.Encrypt;
                    var base64EncryptStr = Encoding.UTF8.GetString(Convert.FromBase64String(encrypt));
                    var reqBody          = JDPaySecurity.DecryptECB(base64EncryptStr, Options.DesKeyBase64);
                    Logger?.LogTrace(2, "Encrypt Content:{body}", reqBody);

                    var reqBodyDoc = new XmlDocument()
                    {
                        XmlResolver = null
                    };
                    reqBodyDoc.LoadXml(reqBody);

                    var sign     = JDPayUtility.GetValue(reqBodyDoc, "sign");
                    var rootNode = reqBodyDoc.SelectSingleNode("jdpay");
                    var signNode = rootNode.SelectSingleNode("sign");
                    rootNode.RemoveChild(signNode);

                    var reqBodyStr = JDPayUtility.ConvertXmlToString(reqBodyDoc);
                    var xmlh       = rsp.Body.Substring(0, rsp.Body.IndexOf("<jdpay>"));
                    if (!string.IsNullOrEmpty(xmlh))
                    {
                        reqBodyStr = reqBodyStr.Replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", xmlh);
                    }
                    var sha256SourceSignString = SHA256.Compute(reqBodyStr);
                    var decryptByte            = RSA_ECB_PKCS1Padding.Decrypt(Convert.FromBase64String(sign), Options.PublicKey);
                    var decryptStr             = JDPaySecurity.BytesToString(decryptByte);
                    if (sha256SourceSignString == decryptStr)
                    {
                        rsp         = parser.Parse(reqBody);
                        rsp.Encrypt = encrypt;
                    }
                    else
                    {
                        throw new Exception("sign check fail: check Sign and Data Fail!");
                    }
                }
                return(rsp);
            }
        }
Esempio n. 27
0
 public void DefaultDiscoveryTest(HostType hostType)
 {
     using (ApplicationDeployer deployer = new ApplicationDeployer())
     {
         string applicationUrl = deployer.Deploy(hostType);
         string responseText   = HttpClientUtility.GetResponseTextFromUrl(applicationUrl);
         Assert.Equal(Startup.RESULT, responseText);
     }
 }
Esempio n. 28
0
        private void GetIcuLayout()
        {
            string icuId = Properties.Settings.Default.currentIcuId;

            if (icuId != null)
            {
                IcuLayout = HttpClientUtility.GetData("api/IcuData/GetLayout/" + icuId).Result;
            }
        }
Esempio n. 29
0
        private HttpClient ProvideHttpClient()
        {
            if (this._httpClient != null)
            {
                return(this._httpClient);
            }

            return(HttpClientUtility.CreateHttpClient(this._config.ProxyAddress, this._config.ProxyUsername, this._config.ProxyPassword));
        }
Esempio n. 30
0
        private static async Task <string> ProcessQueryIntent(IDialogContext context, Activity activity, BotTask task, string query, string[] topics)
        {
            // Prepare the request to invoke a bot task within the bot brain
            AskQuestionRequest request = new AskQuestionRequest()
            {
                ConversationId                   = activity.Conversation.Id,
                Question                         = query,
                SessionId                        = DefaultSessionId,
                Topics                           = topics != null?topics.ToArray() : new string[0],
                                          UserId = string.IsNullOrEmpty(activity.From.Name) == false ? activity.From.Name : activity.From.Id
            };

            // Invoke the bot task to process the request
            AskQuestionResponse askQuestionResponse =
                await HttpClientUtility.PostAsJsonAsync <AskQuestionResponse>(new Uri(BotBrainUrl + task.ToString()), RequestHeaders, request);

            // Handle the response returned from the bot task to be shown as cards depending on channel
            if (askQuestionResponse.Results?.Count() > 0 == true)
            {
                IMessageActivity foundMsg = context.MakeMessage();

                AskQuestionResult result = askQuestionResponse.Results[0];

                if (string.IsNullOrEmpty(result.Source) == false)
                {
                    foundMsg.Text = string.Format("Got it. Meanwhile, from {0}:", result.Source);
                }
                else
                {
                    foundMsg.Text = "Got it. Meanwhile, here's what I found:";
                }

                await context.PostAsync(foundMsg);

                IMessageActivity cardMessage;

                string channelId = GetChannelId(activity);

                if (channelId == "directline" || channelId == "emulator")
                {
                    cardMessage = GetAdaptiveCardMessage(context, request, result);
                }
                else
                {
                    cardMessage = GetHeroCardMessage(context, request, result);
                }

                await context.PostAsync(cardMessage);
            }
            else
            {
                await PostAsync(context, activity, DoNotUnderstandPreMsg + " " + DoNotUnderstandMsg);
            }

            return("success");
        }