示例#1
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Calling the back-end API");

            var url = "http://localhost:5000/" + "api/values";

            var customDelegatingHandler = new CustomDelegatingHandler();

            var client = HttpClientFactory.Create(customDelegatingHandler);

            HttpResponseMessage getResponse = await client.GetAsync(url);

            if (getResponse.IsSuccessStatusCode)
            {
                string responseString = await getResponse.Content.ReadAsStringAsync();

                Console.WriteLine(responseString);
                Console.WriteLine("GET - HTTP Status: {0}, Reason {1}", getResponse.StatusCode, getResponse.ReasonPhrase);
            }
            else
            {
                Console.WriteLine("Failed to call the API. HTTP Status: {0}, Reason {1}", getResponse.StatusCode, getResponse.ReasonPhrase);
            }

            //var order = new Order { OrderID = 10248, CustomerName = "Taiseer Joudeh", ShipperCity = "Amman", IsShipped = true };
            var    order   = new Foo("webhook");
            string json    = JsonConvert.SerializeObject(order);
            var    content = new StringContent(json, Encoding.UTF8, "application/json");
            HttpResponseMessage postResponse = await client.PostAsync(url, content);

            if (postResponse.IsSuccessStatusCode)
            {
                string responseString = await postResponse.Content.ReadAsStringAsync();

                Console.WriteLine("POST - HTTP Status: {0}, Reason {1}. Press ENTER to exit", postResponse.StatusCode, postResponse.ReasonPhrase);
            }
            else
            {
                Console.WriteLine("Failed to call the API. HTTP Status: {0}, Reason {1}", postResponse.StatusCode, postResponse.ReasonPhrase);
            }

            Console.ReadLine();
        }
示例#2
0
/**
 * GETs data from the provided-path relative to the base-url.
 *
 * @param path -- if null/empty, refers to the base-url
 * @return {@link FirebaseResponse}
 * @throws UnsupportedEncodingException
 * @throws {@link FirebaseException}
 */
    public FirebaseResponse Get(string path)
    {
        // make the request

        HttpClient client = HttpClientFactory.Create()

                            client.BaseAddress = new Uri(url);
        HttpClient request = new HttpGet(url);


        HttpClient

        HttpResponseMessage httpResponse = this.makeRequest(request);

        // process the response
        FirebaseResponse response = this.ProcessResponse(FirebaseRestMethod.GET, httpResponse);

        return(response);
    }
        // Request data from telemetry server handle possible exceptions
        static async Task GetData()
        {
            var httpClient = HttpClientFactory.Create();
            var url        = "http://localhost:25555/api/ets2/telemetry";

            try
            {
                data = await httpClient.GetStringAsync(url);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                ((MainWindow)Application.Current.MainWindow).textBlock.Text        = "Telemetry server is not running!\nPlease run it before hitting the 'Start' button.";
                ((MainWindow)Application.Current.MainWindow).processIndicator.Fill = new SolidColorBrush(Colors.Red);
                ((MainWindow)Application.Current.MainWindow).textBlockTwo.Text     = "Error! Telemetry server not running";
                Thread.Sleep(5000);
                Environment.Exit(Environment.ExitCode);
            }
        }
        public async Task <IActionResult> Register(RestReportsModel restReportsModel)
        {
            var client = HttpClientFactory.Create();

            var result = await client.PostAsJsonAsync(
                new Uri(connectionString + "api/Rest/Post"),
                restReportsModel);

            if (result.IsSuccessStatusCode == false)
            {
                return(BadRequest());
            }
            var loadContent = await result.Content.ReadAsStringAsync();

            var getAllContent = JsonConvert
                                .DeserializeObject <RestReportsModel>(loadContent);

            return(Ok(getAllContent));
        }
        private async Task <bool> DownloadSchemaAsync(
            UpdateCommandContext context,
            Uri serviceUri,
            string schemaFilePath,
            CancellationToken cancellationToken)
        {
            using IActivity activity = Output.WriteActivity("Download schema");

            HttpClient client = HttpClientFactory.Create(
                context.Uri ?? serviceUri,
                context.Token,
                context.Scheme,
                context.CustomHeaders);

            return(await IntrospectionHelper.DownloadSchemaAsync(
                       client, FileSystem, activity, schemaFilePath,
                       cancellationToken)
                   .ConfigureAwait(false));
        }
示例#6
0
        private static async Task <string> UploadData(string uri, HttpContent formData, CancellationToken token, Dictionary <string, string> extraHeaders = null)
        {
            ProgressMessageHandler progress = new ProgressMessageHandler();

            progress.HttpSendProgress += HttpSendProgress;

            HttpRequestMessage message = new HttpRequestMessage();

            message.Method     = HttpMethod.Post;
            message.Content    = formData;
            message.RequestUri = new Uri(uri);

            using (var client = HttpClientFactory.Create(progress))
            {
                client.DefaultRequestHeaders.Add("User-Agent", "LXtory/1.0");
                client.DefaultRequestHeaders.Add("Connection", "Close");
                client.Timeout = Timeout.InfiniteTimeSpan;

                if (extraHeaders != null)
                {
                    foreach (KeyValuePair <string, string> header in extraHeaders)
                    {
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }
                var response = await client.SendAsync(message, token);

                if (response.IsSuccessStatusCode)
                {
                    return(await response.Content.ReadAsStringAsync());
                }
                else
                {
                    var error = await response.Content.ReadAsStringAsync();

                    if (error.Length > 512)
                    {
                        error = "";
                    }
                    throw new Exception($"Upload error.\r\n{response.ReasonPhrase}\r\n{error}");
                }
            }
        }
示例#7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="appKey"></param>
        /// <param name="isDevelopment"></param>
        public CoinyProClient(string appId, string appKey, bool isDevelopment = true)
        {
            if (string.IsNullOrEmpty(appId))
            {
                throw new ArgumentNullException(nameof(appId));
            }
            if (string.IsNullOrEmpty(appKey))
            {
                throw new ArgumentNullException(nameof(appKey));
            }

            var client = HttpClientFactory.Create(new ClientHandler(appId, appKey));

            client.BaseAddress = isDevelopment ? new Uri("https://api-coiny-pro-dev.azurewebsites.net/") : new Uri("https://api-pro.coiny.io/");

            WalletService    = new WalletService(client);
            OrderService     = new OrderService(client);
            TradePairService = new TradePairService(client);
        }
示例#8
0
        public ZohoApiService()
        {
            _apiTokenUrl  = ConfigurationManager.AppSettings["zoho:ApiTokenUrl"];
            _apiUploadUrl = ConfigurationManager.AppSettings["zoho:ApiUploadUrl"];

            if (string.IsNullOrEmpty(_apiTokenUrl))
            {
                throw new ConfigurationErrorsException("Please add 'zohoApiTokenUrl' settigns to .config file.");
            }

            if (string.IsNullOrEmpty(_apiUploadUrl))
            {
                throw new ConfigurationErrorsException("Please add 'zohoApiUploadUrl' settigns to .config file.");
            }

            _httpClient = HttpClientFactory.Create();
            _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));
            _httpClient.DefaultRequestHeaders.Add("Authorization", $"Zoho-oauthtoken {AccessToken}");
        }
示例#9
0
        /// <summary>
        /// POST 请求 地址
        /// </summary>
        /// <param name="url">请求 地址</param>
        /// <param name="postJson">post 的 json 字符串</param>
        /// <returns></returns>
        public static async Task <string> HttpPostAsync(string url, string postJson)
        {
            string html = string.Empty;

            using (var httpClient = HttpClientFactory.Create())
            {
                using (var httpContent = new StringContent(postJson))
                {
                    httpContent.Headers.ContentType = new MediaTypeHeaderValue(HttpContentTypeKeys.APPLICATION_JSON);

                    var httpResponseMessage = await httpClient.PostAsync(url, httpContent);

                    //data = await GetResponseContentDataAsync<TReturnDataModel>(httpResponseMessage);
                    html = await GetResponseContentStringAsync(httpResponseMessage);
                }
            }

            return(html);
        }
示例#10
0
        public HttpResponseMessage PostCreateTimeSeries(string tokenValue, TestTimeSeriesMetadataModel model)
        {
            using (HttpClient client = HttpClientFactory.Create())
            {
                client.DefaultRequestHeaders
                .Accept
                .Add(new MediaTypeWithQualityHeaderValue(CommonHttpConstants.ApplicationJsonMedia));

                if (tokenValue != null)
                {
                    client.DefaultRequestHeaders.Authorization =
                        new AuthenticationHeaderValue(CommonHttpConstants.AuthorizationHeader, tokenValue);
                }

                return(client.LogAndPost($"{BaseApiRoute}",
                                         new StringContent(model.ToString(), Encoding.UTF8, CommonHttpConstants.ApplicationJsonMedia),
                                         Logger));
            }
        }
        public async Task Retry_policy_should_work()
        {
            var clientWithRetry = HttpClientFactory.Create()
                                  .WithPolicy(
                Policy <HttpResponseMessage>
                .Handle <HttpRequestException>()
                .OrResult(result => result.StatusCode >= HttpStatusCode.InternalServerError || result.StatusCode == HttpStatusCode.RequestTimeout)
                .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(1)))
                                  .Build();

            var response = await clientWithRetry.GetAsync($"{_server.Urls[0]}{_endpointUri}");

            Assert.Equal(2, _server.LogEntries.Count());
            Assert.Single(_server.LogEntries, le => (HttpStatusCode)le.ResponseMessage.StatusCode == HttpStatusCode.OK);
            Assert.Single(_server.LogEntries, le => (HttpStatusCode)le.ResponseMessage.StatusCode == HttpStatusCode.RequestTimeout);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal("Hello world!", await response.Content.ReadAsStringAsync());
        }
        private static async Task HandleAsync(string serverUrl, string accessToken, string username, string password, string timelineKey, DateTime fromTime, DateTime toTime)
        {
            using var client = HttpClientFactory.Create(username, password, accessToken);
            serverUrl ??= await client.GetCloudServerUrlAsync();

            JsonElement home = await client.GetAsJsonAsync(serverUrl, ManicTimeMediaType.V3);

            JsonElement timelines = await client.GetAsJsonAsync(Urls.Timelines(home.GetLinkHref("manictime/timelines"), timelineKey), ManicTimeMediaType.V3);

            JsonElement timeline = timelines.GetProperty("timelines").EnumerateArray().SingleOrDefault();

            if (timeline.ValueKind == JsonValueKind.Undefined)
            {
                throw new InvalidOperationException("Timeline not found.");
            }
            JsonElement activities = await client.GetAsJsonAsync(Urls.Activities(timeline.GetLinkHref("manictime/activities"), fromTime, toTime), ManicTimeMediaType.V3);

            Console.WriteLine(activities.FormatForDisplay());
        }
示例#13
0
        static void Main(string[] args)
        {
            string uri        = "http://localhost:12345/api/values";
            string headerName = "X-Response-Header-To-Protect";

            var credential = new Credential()
            {
                Id        = "dh37fgj492je",
                Algorithm = SupportedAlgorithms.SHA256,
                User      = "******",
                Key       = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn"
            };

            // GET and POST using the Authorization header
            var handler = new HawkValidationHandler(credentialsCallback: () => credential,
                                                    verificationCallback: (r, ext) =>
                                                    ext.Equals(headerName + ":" + r.Headers.GetValues(headerName).First()));
            HttpClient client = HttpClientFactory.Create(handler);

            var response = client.GetAsync(uri).Result;

            Console.WriteLine(response.Content.ReadAsStringAsync().Result);

            response = client.PostAsJsonAsync(uri, credential.User).Result;
            Console.WriteLine(response.Content.ReadAsStringAsync().Result);

            // GET using Bewit
            var    hawkClient = new HawkClient(() => credential);
            string bewit      = hawkClient.CreateBewitAsync(new HttpRequestMessage()
            {
                RequestUri = new Uri(uri)
            },
                                                            lifeSeconds: 60).Result;

            // Bewit is handed off to a client needing temporary access to the resource.
            var clientNeedingTempAccess = new WebClient();
            var resource = clientNeedingTempAccess.DownloadString(uri + "?bewit=" + bewit);

            Console.WriteLine(resource);

            Console.Read();
        }
        public async override Task Upload(string filename, Model.UserConfiguration uc, EventHandler <HttpProgressEventArgs> progressHandler, CancellationToken cancelToken)
        {
            Dictionary <string, string> values = new Dictionary <string, string>();

            values.Add("notes", _appInfo.Notes);
            values.Add("notes_type", "0");
            values.Add("status", _appInfo.Status.ToString());
            values.Add("notify", _appInfo.Notify.ToString());
            values.Add("release_type", _appInfo.ReleaseType.ToString());
            values.Add("mandatory", _appInfo.Mandatory.ToString());


            FileStream fs = new FileStream(filename, FileMode.Open);

            HttpContent formContent = new FormUrlEncodedContent(values);
            HttpContent fileContent = new StreamContent(fs);


            MultipartFormDataContent multipartContent = new MultipartFormDataContent();

            multipartContent.Add(formContent);
            multipartContent.Add(fileContent, "ipa", Path.GetFileName(filename));


            ProgressMessageHandler progress = new ProgressMessageHandler();

            progress.HttpSendProgress += progressHandler;

            HttpClient client = HttpClientFactory.Create(progress);

            client.Timeout = TimeSpan.FromMinutes(10);
            client.DefaultRequestHeaders.Add("X-HockeyAppToken", uc.UserToken);
            HttpResponseMessage response = null;

            response = await client.PostAsync(uc.ApiBase + "apps", multipartContent, cancelToken);

            if (response != null && !response.IsSuccessStatusCode)
            {
                throw new Exception(response.ReasonPhrase);
            }
            fs.Close();
        }
示例#15
0
        public async Task Test()
        {
            if (RpsTest == 0)
            {
                return;
            }

            var token = await CreateUserAndObtainToken(GenerateUsername());

            var step = Step.Create(GetTestName(),
                                   HttpClientFactory.Create(),
                                   context =>
            {
                var request = Http.CreateRequest("POST", $"{Url}/web/api/tasks")
                              .WithHeader("accept", "application/json")
                              .WithHeader("authorization", $"Bearer {token}")
                              .WithBody(JsonContent.Create(new object[]
                {
                    new
                    {
                        title = "create_task_test",
                        uid   = Guid.NewGuid(),
                    }
                }));

                return(Http.Send(request, context));
            }, timeout: TimeSpan.FromSeconds(Timeout));

            var scenario = ScenarioBuilder
                           .CreateScenario(GetTestName(), step)
                           .WithWarmUpDuration(TimeSpan.FromSeconds(5))
                           .WithLoadSimulations(
                Simulation.KeepConstant(RpsTest, TimeSpan.FromSeconds(TimeTest))
                );

            var result = await RunScenario(scenario);

            VerifyResults(result, () =>
            {
                Assert.NotInRange(result.ScenarioStats[0].StepStats[0].Ok.Request.RPS, 0, 13 * RpsTest);
            });
        }
示例#16
0
        public async Task FillPipeAsync(DiscordAttachment attachment, PipeWriter writer)
        {
            try
            {
                using (var fileStream = new FileStream(Path.GetTempFileName(), FileMode.Create, FileAccess.ReadWrite, FileShare.Read, 16384, FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose))
                {
                    using (var client = HttpClientFactory.Create())
                        using (var downloadStream = await client.GetStreamAsync(attachment.Url).ConfigureAwait(false))
                            await downloadStream.CopyToAsync(fileStream, 16384, Config.Cts.Token).ConfigureAwait(false);
                    fileStream.Seek(0, SeekOrigin.Begin);
                    using (var zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Read))
                    {
                        var logEntry = zipArchive.Entries.FirstOrDefault(e => e.Name.EndsWith(".log", StringComparison.InvariantCultureIgnoreCase));
                        if (logEntry == null)
                        {
                            throw new InvalidOperationException("No zip entries that match the log criteria");
                        }

                        using (var zipStream = logEntry.Open())
                        {
                            int         read;
                            FlushResult flushed;
                            do
                            {
                                var memory = writer.GetMemory(Config.MinimumBufferSize);
                                read = await zipStream.ReadAsync(memory, Config.Cts.Token);

                                writer.Advance(read);
                                flushed = await writer.FlushAsync(Config.Cts.Token).ConfigureAwait(false);
                            } while (read > 0 && !(flushed.IsCompleted || flushed.IsCanceled || Config.Cts.IsCancellationRequested));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Config.Log.Error(e, "Error filling the log pipe");
                writer.Complete(e);
                return;
            }
            writer.Complete();
        }
示例#17
0
        public async Task FillPipeAsync(DiscordAttachment attachment, PipeWriter writer)
        {
            try
            {
                using (var fileStream = new FileStream(Path.GetTempFileName(), FileMode.Create, FileAccess.ReadWrite, FileShare.Read, 16384, FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose))
                {
                    using (var client = HttpClientFactory.Create())
                        using (var downloadStream = await client.GetStreamAsync(attachment.Url).ConfigureAwait(false))
                            await downloadStream.CopyToAsync(fileStream, 16384, Config.Cts.Token).ConfigureAwait(false);
                    fileStream.Seek(0, SeekOrigin.Begin);
                    using (var zipArchive = SevenZipArchive.Open(fileStream))
                        using (var zipReader = zipArchive.ExtractAllEntries())
                            while (zipReader.MoveToNextEntry())
                            {
                                if (!zipReader.Entry.IsDirectory && zipReader.Entry.Key.EndsWith(".log", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    using (var rarStream = zipReader.OpenEntryStream())
                                    {
                                        int         read;
                                        FlushResult flushed;
                                        do
                                        {
                                            var memory = writer.GetMemory(Config.MinimumBufferSize);
                                            read = await rarStream.ReadAsync(memory, Config.Cts.Token);

                                            writer.Advance(read);
                                            flushed = await writer.FlushAsync(Config.Cts.Token).ConfigureAwait(false);
                                        } while (read > 0 && !(flushed.IsCompleted || flushed.IsCanceled || Config.Cts.IsCancellationRequested));
                                    }
                                    writer.Complete();
                                    return;
                                }
                            }
                    Config.Log.Warn("No 7z entries that match the log criteria");
                }
            }
            catch (Exception e)
            {
                Config.Log.Error(e, "Error filling the log pipe");
            }
            writer.Complete();
        }
示例#18
0
        private async Task <string> FetchPageTitle(string url)
        {
            string title = null;

            var client = HttpClientFactory.Create();

            using (var response = await client.GetAsync(new Uri(url, UriKind.Absolute)))
            {
                using (var stream = await response.Content.ReadAsStreamAsync())
                {
                    // compiled regex to check for <title></title> block
                    var pattern = new Regex(@"<title>\s*(.+?)\s*</title>",
                                            RegexOptions.Compiled | RegexOptions.IgnoreCase);

                    var chunkSize = 512;
                    var buffer    = new byte[chunkSize];
                    var contents  = "";
                    var length    = 0;

                    while ((title == null) && (length = stream.Read(buffer, 0, chunkSize)) > 0)
                    {
                        // convert the byte-array to a string and add it to the rest of the
                        // contents that have been downloaded so far
                        contents += Encoding.UTF8.GetString(buffer, 0, length);

                        var match = pattern.Match(contents);
                        if (match.Success)
                        {
                            // we found a <title></title> match
                            title = match.Groups[1].Value;
                        }
                        else if (contents.Contains("</head>"))
                        {
                            // reached end of head-block; no title found
                            title = string.Empty;
                        }
                    }
                }
            }

            return(title);
        }
示例#19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="uriAuthority">请求的根URL</param>
        /// <returns></returns>
        public static HttpClient GetOrAddClient(string uriAuthority)
        {
            uriAuthority = uriAuthority.TrimEnd('/');
            var        hostUpper = uriAuthority.ToUpper();
            HttpClient client    = null;

            if (!Dict.ContainsKey(hostUpper))
            {
                client = HttpClientFactory.Create(innerHandler: new HttpClientHandler
                {
                    AutomaticDecompression = DecompressionMethods.GZip
                                             //, UseCookies = true,
                                             //CookieContainer = new CookieContainer()
                });

                try
                {
                    client.BaseAddress = new Uri(uriAuthority);
                }
                catch (Exception ex)
                {
                    Log.Error("设置HttpClient的Uri出错:" + uriAuthority, ex);
                    return(null);
                }

                //client.DefaultRequestHeaders.Accept.Add(
                //    new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.AcceptEncoding.Add(
                    new StringWithQualityHeaderValue("gzip"));
                var ok = Dict.TryAdd(hostUpper, client);
                client = !ok?Dict.GetOrAdd(hostUpper, client) : Dict[hostUpper];
            }
            else
            {
                client = Dict[hostUpper];
            }
            if (client == null)
            {
                Log.ErrorFormat("HttpClient为空:{0}", uriAuthority);
            }
            return(client);
        }
        private static async Task <HttpClient> CouchDbClientAsync()
        {
            if (httpClient == null)
            {
                foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
                {
                    Console.WriteLine("  {0} = {1}", de.Key, de.Value);
                }

                string env = Environment.GetEnvironmentVariable(CLOUDANT_SECRET);
                env = env.Replace("\\", string.Empty);
                env = env.Replace("'", string.Empty);
                JObject o        = JObject.Parse(env);
                string  host     = o.GetValue("host").ToString();
                string  username = o.GetValue("username").ToString();
                string  password = o.GetValue("password").ToString();
                if (host == null || username == null || password == null)
                {
                    throw new Exception("Missing Cloudant NoSQL DB service credentials");
                }
                string url       = "https://" + host;
                var    authValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + password));
                httpClient             = HttpClientFactory.Create();
                httpClient.BaseAddress = new Uri(url);
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authValue);

                // create Database if not exists
                var response = await httpClient.PutAsync(dbname, null);

                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("Database todos created");
                }
                else if (response.StatusCode == HttpStatusCode.PreconditionFailed) //412 database exists
                {
                    Console.WriteLine("Database todos exists");
                }
            }
            return(httpClient);
        }
示例#21
0
        public async Task <DakiItemHistoryEntry> ObtainItemState(Hunt hunt)
        {
            var client = HttpClientFactory.Create();

            try
            {
                var rawHtml = await client.GetStreamAsync(hunt.HuntedItem.Url);

                var doc = new HtmlDocument();
                doc.Load(rawHtml);


                var infoSection = doc.DocumentNode.Descendants("div")
                                  .First(node => node.HasAttribute("id", "sellInfo_left"));

                var output = new DakiItemHistoryEntry
                {
                    DateTime = DateTime.UtcNow,
                };

                if (infoSection.InnerText.Contains("品切れ中です"))
                {
                    output.IsAvailable = false;
                    output.Price       = -1;
                }
                else
                {
                    output.IsAvailable = true;
                    var priceSectionText = infoSection.Descendants("p").First(node => node.HasAttribute("id", "price")).InnerText;
                    var parts            = priceSectionText.Split('円');
                    output.Price = int.Parse(parts[0].Replace(",", ""));
                }

                return(output);
            }
            catch (Exception e)
            {
                _logger.LogError(e,
                                 $"Error parsing single surugaya item. Hunt {hunt.Id}, item {hunt.HuntedItem.Id}");
                return(null);
            }
        }
示例#22
0
        public static async Task Run([ServiceBusTrigger("khsvrlessohsbtopic", "khsvrlessohsbtopicsub", Connection = "PUBSUBConnection")] string mySbMsg,
                                     [Blob("receipts-high-value/{rand-guid}.json", FileAccess.Write, Connection = "AzureWebJobsStorage")] Stream receipt,
                                     ILogger log)
        {
            log.LogInformation($"C# ServiceBus topic trigger function processed message: {mySbMsg}");
            log.LogInformation($"Total Cost is greater than or equal to $100.00 starting...");
            dynamic data = JObject.Parse(mySbMsg);

            try
            {
                // Get Receipt in PDF Format
                log.LogInformation($"PDF Receipt starting...");
                HttpClient          httpClient      = HttpClientFactory.Create();
                string              responseMessage = String.Empty;
                HttpResponseMessage pdfResponse     = await httpClient.GetAsync((string)data.receiptUrl);

                byte[] pdfData = null;
                pdfData = await pdfResponse.Content.ReadAsByteArrayAsync();

                string base64PDF = Convert.ToBase64String(pdfData);
                log.LogInformation($"PDF Receipt completed.");

                Greater100 greater100 = new Greater100();
                greater100.Store        = data.storeLocation;
                greater100.SalesNumber  = data.salesNumber;
                greater100.TotalCost    = (double)data.totalCost;
                greater100.Items        = (long)data.totalItems;
                greater100.SalesDate    = data.salesDate;
                greater100.ReceiptImage = base64PDF;

                string g100Content = JsonConvert.SerializeObject(greater100);
                using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(g100Content)))
                {
                    await stream.CopyToAsync(receipt);
                }
            }
            catch (Exception exc)
            {
                log.LogError($"Total Cost is greater than $100.00 failed with exception type {exc.GetType().ToString()} and error message: {exc.Message}");
            }
            log.LogInformation($"Total Cost is greater than $100.00 completed.");
        }
示例#23
0
            public IHttpClient Create()
            {
                var webRequestHandler = new WebRequestHandler();

                if (webRequestHandler.SupportsAutomaticDecompression)
                {
                    webRequestHandler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                }
#if DEBUG
                webRequestHandler.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
#endif
                _requestHandlerConfigurators.ForEach((configurator) => configurator(webRequestHandler));

                var client = _cacheHandler == null
                    ? HttpClientFactory.Create(webRequestHandler, _handlers.ToArray())
                    : HttpClientFactory.Create(_cacheHandler, _handlers.ToArray());

                client.BaseAddress = _baseUrl;

                if (_connectionLeaseTimeout != 0)
                {
                    var servicePoint = ServicePointManager.FindServicePoint(_baseUrl);
                    servicePoint.ConnectionLeaseTimeout = _connectionLeaseTimeout;
                }

                if (_timeout.HasValue)
                {
                    client.Timeout = _timeout.Value;
                }

                if (_defaultHeaders == null)
                {
                    return(new HttpClientWrapper(client));
                }

                foreach (var header in _defaultHeaders)
                {
                    client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }

                return(new HttpClientWrapper(client));
            }
示例#24
0
        public async Task Test()
        {
            if (RpsTest == 0)
            {
                return;
            }

            var token = await CreateUserAndObtainToken(GenerateUsername());

            var step = Step.Create(GetTestName(),
                                   HttpClientFactory.Create(),
                                   context =>
            {
                var request = Http.CreateRequest("POST", $"{Url}/web/api/tasks")
                              .WithHeader("accept", "application/json")
                              .WithHeader("authorization", $"Bearer {token}")
                              .WithBody(JsonContent.Create(new object[]
                {
                    new
                    {
                        title = "create_task_test",
                        uid   = Guid.NewGuid(),
                    }
                }));

                return(Http.Send(request, context));
            }, timeout: TimeSpan.FromSeconds(Timeout));

            var scenario = ScenarioBuilder
                           .CreateScenario(GetTestName(), step)
                           .WithWarmUpDuration(TimeSpan.FromSeconds(5))
                           .WithLoadSimulations(
                Simulation.RampPerSec(RpsWarmUp, TimeSpan.FromSeconds(TimeWarmUp)),
                Simulation.RampPerSec(RpsTest, TimeSpan.FromSeconds(TimeRamp)),
                Simulation.InjectPerSec(RpsTest, TimeSpan.FromSeconds(TimeTest))
                // Simulation.InjectPerSecRandom(RpsMin, RpsMax, TimeSpan.FromSeconds(Time))
                );

            var result = await RunScenario(scenario);

            VerifyResults(result);
        }
示例#25
0
        public async void API_GetChartsData_Test(string url)
        {
            var config = new HttpConfiguration();

            RouteConfig.RegisterRoutes(config);
            AutofacWebApi.Setup(config);
            var httpServer = new HttpServer(config);

            var client   = HttpClientFactory.Create(innerHandler: httpServer);
            var response = client.GetAsync(new Uri(url)).Result;

            //HttpResponseMessage response = await client.GetAsync(new Uri(url));


            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            var json      = JObject.Parse(response.Content.ReadAsStringAsync().Result);
            var viewModel = json.ToObject <ChartsData>();

            Assert.IsType(typeof(ChartsData), viewModel);
        }
示例#26
0
        /// <summary>
        /// Wire up three sample HttpMessageHandler instances to the client which means
        /// that each request and response will go through these three before hitting the
        /// network.
        /// </summary>
        static async Task RunHttpClientWithHttpClientHandlerAndMultipleDelegatingHandlersAsync()
        {
            Console.WriteLine("Issue request using an HttpClient with HttpClientHandler and multiple delegating handlers in the pipeline.");

            // Create HttpClientHandler and set UseDefaultCredentials property
            HttpClientHandler clientHandler = new HttpClientHandler();

            clientHandler.UseDefaultCredentials = true;

            // Create an HttpClient and add message handlers for the client
            HttpClient client = HttpClientFactory.Create(
                clientHandler,
                new SampleHandler("Client A", 2),
                new SampleHandler("Client B", 4),
                new SampleHandler("Client C", 6));

            HttpResponseMessage response = await client.GetAsync(_address);

            Console.WriteLine("Request completed with status code {0}", response.StatusCode);
        }
示例#27
0
        public MuzlanClient(MuzlanClientConfig config)
        {
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            BaseUri = new Uri(config.Host, UriKind.Absolute);

            _client = HttpClientFactory.Create(config);

            _parser = new HtmlParser();

            Albums   = new AlbumsEndpoint(BaseUri, _client, _parser);
            Auth     = new AuthEndpoint(BaseUri, _client, _parser);
            Download = new DownloadEndpoint(BaseUri, _client, _parser);
            Meta     = new MetaEndpoint(BaseUri, _client, _parser);
            Search   = new SearchEndpoint(BaseUri, _client, _parser);
            Sitemap  = new SitemapEndpoint(BaseUri, _client, _parser);
        }
示例#28
0
        /// <summary>
        /// 获取自定义菜单
        /// </summary>
        /// <param name="wx"></param>
        /// <returns></returns>
        public async Task <string> GetMenu(PublicWX wx)
        {
            if (string.IsNullOrEmpty(wx.AccessToken))
            {
                throw new InvalidOperationException("公众号还没有获取Access_Key");
            }
            using (var client = HttpClientFactory.Create())
            {
                string uri = string.Format("https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}", wx.AccessToken);
                HttpResponseMessage response = await client.GetAsync(uri);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var ret = await response.Content.ReadAsStringAsync();

                    return(ret);
                }
                return(null);
            }
        }
示例#29
0
        static async Task Main(string[] args)
        {
            var httpClient = HttpClientFactory.Create();

            var url = "https://jsonplaceholder.typicode.com/todos/1";
            //var data = await httpClient.GetStringAsync(url);

            HttpResponseMessage httpResponseMessage = await httpClient.GetAsync(url);

            if (httpResponseMessage.StatusCode == HttpStatusCode.OK)
            {
                var content = httpResponseMessage.Content;
                var data    = await content.ReadAsStringAsync();

                Console.WriteLine(data);
            }


            Console.WriteLine("Hello World!");
        }
        public void DoSimulation(object state)
        {
            var httpClient = HttpClientFactory.Create();

            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var random = new Random();

            foreach (var vin in Vins)
            {
                if (random.Next(5) == 4)
                {
                    continue;
                }

                var request = new HttpRequestMessage(HttpMethod.Post, url);
                request.Content = new StringContent(JsonConvert.SerializeObject(vin), Encoding.UTF8, "application/json");
                var result    = httpClient.SendAsync(request);
                var endResult = result.Result;
            }
        }