Пример #1
11
        public async Task<bool> TelemetryIngest(Telemetry telemetry)
        {

            string serviceBusNamespace = "iotmc-ns";
            string serviceBusUri = string.Format("{0}.servicebus.windows.net", serviceBusNamespace);
            string eventHubName = "IoTMC";
            string eventHubSASKeyName = "Device01";
            string eventHubSASKey = "<< Your SAS Key here >>";

            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(String.Format("https://{0}", serviceBusUri));
                httpClient.DefaultRequestHeaders.Accept.Clear();

                string sBToken = CreateServiceBusSASToken(eventHubSASKeyName, eventHubSASKey, serviceBusUri);
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SharedAccessSignature", sBToken);
                HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(telemetry), Encoding.UTF8);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
              
                string ingestPath = String.Format("/{0}/publishers/device01/messages", eventHubName);
                var response = await httpClient.PostAsync(ingestPath, httpContent);
                if (response.IsSuccessStatusCode)
                {
                    return true;
                }

                return false;
            }
        }
Пример #2
2
 public async Task Ctor_EmptyString_Accept()
 {
     // Consider empty strings like null strings (null and empty strings should be treated equally).
     var content = new StringContent(string.Empty);
     Stream result = await content.ReadAsStreamAsync();
     Assert.Equal(0, result.Length);
 }
        public void ReadDeeplyNestedObjectThrows()
        {
            FormUrlEncodedMediaTypeFormatter formatter = new FormUrlEncodedMediaTypeFormatter() { MaxDepth = 100 };

            StringContent content = new StringContent(GetDeeplyNestedObject(125));

            content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            Assert.ThrowsArgument(
                () => formatter.ReadFromStreamAsync(typeof(JToken), content.ReadAsStreamAsync().Result, content.Headers, null).Result,
                null);
        }
Пример #4
0
        public static async Task<string> PostCallAsync(string url, string parameters)
        {
            var content = new StringContent(parameters);
            string output = string.Empty;
            using (var client = new HttpClient())
            {   
                HttpResponseMessage response = await client.PostAsync(url, content);
                output = await response.Content.ReadAsStringAsync();
            }

            return output;
        }
            public void GivenSomeContentWithNoBadPhrases_PhrasesThatExist_ReturnsANullList()
            {
                // Arrange.
                const string content =
                    "foo  1 12l3j1kl;j434;5 3klkrj 987*&^897^DF hsfd l;ajf;o2u3r8fjdasf jdsajf ;aljsfj asf jas;df 8asuf 80sdf 9d (& 8H ";

                var stringContent = new StringContent(PhraseList);

                // Act.
                var results = stringContent.PhrasesThatExist(content);

                // Assert.
                Assert.Null(results);
            }
Пример #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PapRequestMessage"/>
        /// class with both control and content parts.
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="content">The content.</param>
        public PapRequestMessage(PushMessageControl control, StringContent content)
        {
            _control = control;
            _content = content;

            BoundaryGenerator bg = new BoundaryGenerator();

            Boundary = bg.MakeBoundary();

            if (content != null && control != null)
            {
                content.PushId = control.PushId;
            }
        }
        public void Dispose_DisposesInnerContent()
        {
            // Arrange
            StringContent innerContent = new StringContent("HelloWorld!");
            HttpRequestMessage request = new HttpRequestMessage();
            ProgressMessageHandler progressHandler = new ProgressMessageHandler();
            ProgressContent progressContent = new ProgressContent(innerContent, progressHandler, request);

            // Act
            progressContent.Dispose();

            // Assert
            Assert.ThrowsObjectDisposed(() => innerContent.LoadIntoBufferAsync(), typeof(StringContent).FullName);
        }
Пример #8
0
 public async Task<CompositeType> GetDataUsingDataContract(CompositeType composite)
 {
     var soapString = this.CreateGetDataUsingDataContractRequest(composite);
     using (var client = new HttpClient())
     {
         client.DefaultRequestHeaders.Add("SOAPAction", "http://tempuri.org/IService1/GetDataUsingDataContract");
         var content = new StringContent(soapString, Encoding.UTF8, "text/xml");
         using (var response = await client.PostAsync(this.uri, content))
         {
             string soapResponse = await response.Content.ReadAsStringAsync();
             CompositeType result = this.ParseGetDataUsingDataContractResponse(soapResponse);
             return result;
         }
     }
 }
            public void GivenSomeContentWithBadPhrases_PhrasesThatExist_ReturnsAListOfBadPhrasesFound()
            {
                // Arrange.
                const string content =
                    "This is a bad review. I noticed that there were a lot of white people living in Ivanhoe. This doesn't mean this is a racist suburb, though.";

                var stringContent = new StringContent(PhraseList);

                // Act.
                var results = stringContent.PhrasesThatExist(content);

                // Assert.
                Assert.NotNull(results);
                Assert.NotEmpty(results);
                Assert.Equal(2, results.Count);
            }
Пример #10
0
        public void Constructor_CopyHeadersFromInnerContent()
        {
            // Arrange
            StringContent innerContent = new StringContent("HelloWorld!");
            innerContent.Headers.Add(TestHeader, TestValue);
            HttpRequestMessage request = new HttpRequestMessage();
            ProgressMessageHandler progressHandler = new ProgressMessageHandler();

            // Act
            ProgressContent progressContent = new ProgressContent(innerContent, progressHandler, request);

            // Assert
            ValidateContentHeader(progressContent);
            Assert.Equal(innerContent.Headers.ContentType, progressContent.Headers.ContentType);
            Assert.Equal(innerContent.Headers.ContentLength, progressContent.Headers.ContentLength);
        }
Пример #11
0
        public async Task Ctor_UseCustomEncodingAndMediaType_EncodingUsedAndContentTypeHeaderUpdated()
        {
            // Use UTF-8 encoding to serialize a chinese string.
            string sourceString = "\u4f1a\u5458\u670d\u52a1";

            var content = new StringContent(sourceString, Encoding.UTF8, "application/custom");

            Assert.Equal("application/custom", content.Headers.ContentType.MediaType);
            Assert.Equal("utf-8", content.Headers.ContentType.CharSet);

            var destination = new MemoryStream(12);
            await content.CopyToAsync(destination);

            string destinationString = Encoding.UTF8.GetString(destination.ToArray(), 0, (int)destination.Length);

            Assert.Equal(sourceString, destinationString);
        }
            public void GivenSomeContentWithBadPhrasesSuppliedSeparately_PhrasesThatExist_ReturnsAListOfBadPhrasesFound()
            {
                // Arrange.
                const string content =
                    "This is a bad review. &^*(sd79ad hskah sad (*&(&97s a9 I noticed adult living that there were a lot of white people living in Ivanhoe. This doesn't mean this is a racist suburb, though.";

                var stringContent = new StringContent();

                // Act.
                var results = stringContent.PhrasesThatExist(content, PhraseList);

                // Assert.
                Assert.NotNull(results);
                Assert.NotEmpty(results);
                Assert.Equal(3, results.Count);
                Assert.Equal("adult living", results.First().Phrase);
                Assert.Equal(65, results.First().IndexOn);
            }
Пример #13
0
        public async Task Ctor_DefineNoEncoding_DefaultEncodingUsed()
        {
            string sourceString = "\u00C4\u00E4\u00FC\u00DC";
            var content = new StringContent(sourceString);
            Encoding defaultStringEncoding = Encoding.GetEncoding("utf-8");

            // If no encoding is defined, the default encoding is used: utf-8
            Assert.Equal("text/plain", content.Headers.ContentType.MediaType);
            Assert.Equal(defaultStringEncoding.WebName, content.Headers.ContentType.CharSet);

            // Make sure the default encoding is also used when serializing the content.
            var destination = new MemoryStream();
            await content.CopyToAsync(destination);

            Assert.Equal(8, destination.Length);

            destination.Seek(0, SeekOrigin.Begin);
            string roundTrip = new StreamReader(destination, defaultStringEncoding).ReadToEnd();
            Assert.Equal(sourceString, roundTrip);
        }
        public Task SendAsync_DoesNotInsertSendProgressWithoutEntityOrHandlerPresent(bool insertRequestEntity, bool addSendProgressHandler)
        {
            // Arrange
            HttpMessageInvoker invoker = CreateMessageInvoker(includeResponseEntity: false, addReceiveProgressHandler: false, addSendProgressHandler: addSendProgressHandler);
            HttpRequestMessage request = new HttpRequestMessage();
            HttpContent content = null;
            if (insertRequestEntity)
            {
                content = new StringContent("Request Entity!");
                content.Headers.Add(TestHeader, TestValue);
                request.Content = content;
            }

            // Act
            return invoker.SendAsync(request, CancellationToken.None).ContinueWith(
                task =>
                {
                    // Assert
                    Assert.Equal(TaskStatus.RanToCompletion, task.Status);
                    if (insertRequestEntity && addSendProgressHandler)
                    {
                        ValidateContentHeader(request.Content);
                        Assert.NotSame(content, request.Content);
                        Assert.IsType<ProgressContent>(request.Content);
                    }
                    else
                    {
                        if (insertRequestEntity)
                        {
                            Assert.IsType<StringContent>(request.Content);
                        }
                        else
                        {
                            Assert.Null(request.Content);
                        }
                    }
                });
        }
Пример #15
0
        internal static async Task <string> ExecutePost(this Web web, string endpoint, string payload)
        {
            string returnObject = null;
            var    accessToken  = web.Context.GetAccessToken();

            using (var handler = new HttpClientHandler())
            {
                web.EnsureProperty(w => w.Url);

                // we're not in app-only or user + app context, so let's fall back to cookie based auth
                if (String.IsNullOrEmpty(accessToken))
                {
                    handler.SetAuthenticationCookies(web.Context as ClientContext);
                }


                using (var httpClient = new PnPHttpProvider(handler))
                {
                    var requestUrl = $"{web.Url}{endpoint}";

                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUrl);
                    request.Headers.Add("accept", "application/json;odata=nometadata");
                    if (!string.IsNullOrEmpty(accessToken))
                    {
                        request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
                    }
                    else
                    {
                        if (web.Context.Credentials is NetworkCredential networkCredential)
                        {
                            handler.Credentials = networkCredential;
                        }
                    }
                    request.Headers.Add("X-RequestDigest", await(web.Context as ClientContext).GetRequestDigest());

                    if (!string.IsNullOrEmpty(payload))
                    {
                        ////var jsonBody = JsonConvert.SerializeObject(postObject);
                        var requestBody = new StringContent(payload);
                        MediaTypeHeaderValue sharePointJsonMediaType;
                        MediaTypeHeaderValue.TryParse("application/json;odata=nometadata;charset=utf-8", out sharePointJsonMediaType);
                        requestBody.Headers.ContentType = sharePointJsonMediaType;
                        request.Content = requestBody;
                    }
                    // Perform actual post operation
                    HttpResponseMessage response = await httpClient.SendAsync(request, new System.Threading.CancellationToken());

                    if (response.IsSuccessStatusCode)
                    {
                        // If value empty, URL is taken
                        var responseString = await response.Content.ReadAsStringAsync();

                        if (responseString != null)
                        {
                            try
                            {
                                returnObject = responseString;
                            }
                            catch { }
                        }
                    }
                    else
                    {
                        // Something went wrong...
                        throw new Exception(await response.Content.ReadAsStringAsync());
                    }
                }
            }
            return(await Task.Run(() => returnObject));
        }
Пример #16
0
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        public async Task <Person> ThrowAsync(Guid id, CancellationToken cancellationToken)
        {
            var url_ = string.Format("{0}/{1}?", BaseUrl, "api/Persons/Throw");

            if (id == null)
            {
                throw new ArgumentNullException("id");
            }
            else
            {
                url_ += string.Format("id={0}&", Uri.EscapeDataString(id.ToString()));
            }

            var client_  = new HttpClient();
            var request_ = new HttpRequestMessage();

            PrepareRequest(client_, ref url_);
            var content_ = new StringContent(string.Empty);

            request_.Content    = content_;
            request_.Method     = new HttpMethod("POST");
            request_.RequestUri = new Uri(url_, UriKind.RelativeOrAbsolute);
            var response_ = await client_.SendAsync(request_, HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);

            ProcessResponse(client_, response_);

            var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

            var status_ = ((int)response_.StatusCode).ToString();

            if (status_ == "200")
            {
                var result_ = default(Person);
                try
                {
                    if (responseData_.Length > 0)
                    {
                        result_ = JsonConvert.DeserializeObject <Person>(Encoding.UTF8.GetString(responseData_, 0, responseData_.Length), new JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter(), new JsonExceptionConverter() });
                    }
                    return(result_);
                }
                catch (Exception exception)
                {
                    throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, exception);
                }
            }
            else
            if (status_ == "500")
            {
                var result_ = default(PersonNotFoundException);
                try
                {
                    if (responseData_.Length > 0)
                    {
                        result_ = JsonConvert.DeserializeObject <PersonNotFoundException>(Encoding.UTF8.GetString(responseData_, 0, responseData_.Length), new JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter(), new JsonExceptionConverter() });
                    }
                }
                catch (Exception exception)
                {
                    throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, exception);
                }
                if (result_ == null)
                {
                    result_ = new PersonNotFoundException();
                }
                result_.Data.Add("HttpStatus", status_);
                result_.Data.Add("ResponseData", Encoding.UTF8.GetString(responseData_, 0, responseData_.Length));
                throw new SwaggerException <PersonNotFoundException>("A server side error occurred.", status_, responseData_, result_, result_);
            }
            else
            {
            }

            throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null);
        }
Пример #17
0
        public async Task <HttpResponseMessage> Request(HttpMethod httpMethod, string endpoint,
                                                        object content = null, object queryParams = null, RestRequestConfig restRequestConfig = null)
        {
            HttpContent httpContent = null;

            if (content is HttpContent)
            {
                httpContent = (HttpContent)content;
            }
            else if (content is string s)
            {
                httpContent = new StringContent(s);
            }
            else if (content != null)
            {
                httpContent = new StringContent(
                    JsonConvert.SerializeObject(content, Formatting.None, jsonSerializerSettings), Encoding.UTF8,
                    "application/json"
                    );
            }

            UriBuilder uriBuilder = null;

            if (endpoint.StartsWith("https://"))
            {
                uriBuilder = new UriBuilder(endpoint);
            }
            else
            {
                uriBuilder = new UriBuilder(server)
                {
                    Path = endpoint
                };
            }

            if (queryParams != null)
            {
                var fields = Utils.GetPairs(queryParams).Select(t =>
                {
                    if (t.value.GetType().IsArray)
                    {
                        return(string.Join("&",
                                           (t.value as object[]).Select(o => $"{t.name}={Uri.EscapeUriString(o.ToString())}")
                                           .ToArray()));
                    }
                    else
                    {
                        return($"{t.name}={Uri.EscapeUriString(t.value.ToString())}");
                    }
                });
                uriBuilder.Query = string.Join("&", fields);
            }

            var httpRequestMessage = new HttpRequestMessage
            {
                Method     = httpMethod,
                RequestUri = uriBuilder.Uri,
                Content    = httpContent
            };

            return(await extensibleRequest(httpRequestMessage, restRequestConfig ?? RestRequestConfig.DefaultInstance));
        }
Пример #18
0
 public async Task UpdateAsync(T item)
 {
     var tmpj = JsonConvert.SerializeObject(item);
     var content = new StringContent(tmpj.ToString(), Encoding.UTF8, "application/json");
     await client.PutAsync(UrlAPI, content);
 }
Пример #19
0
 public abstract Content/*!*/ ConcatTo(StringContent/*!*/ content);
        public void ReadDeeplyNestedObjectWithBigDepthQuotaWorks()
        {
            FormUrlEncodedMediaTypeFormatter formatter = new FormUrlEncodedMediaTypeFormatter() { MaxDepth = 150 };

            StringContent content = new StringContent(GetDeeplyNestedObject(125));

            content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

            JToken result = (JToken)formatter.ReadFromStreamAsync(typeof(JToken), content.ReadAsStreamAsync().Result, content, null).Result;
            Assert.NotNull(result);
        }
Пример #21
0
        public async Task <JObject> PostWebApiAndProcessResultASync(string webApiUrl, string accessToken, Action <JObject> processResult, StringContent data)
        {
            JObject jsonObject = null;

            if (!string.IsNullOrEmpty(accessToken))
            {
                var defaultRequestHeaders = HttpClient.DefaultRequestHeaders;
                if (defaultRequestHeaders.Accept == null || !defaultRequestHeaders.Accept.Any(m => m.MediaType == "application/json"))
                {
                    HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                }
                defaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                HttpResponseMessage response = await HttpClient.PostAsync(webApiUrl, data);


                string json = await response.Content.ReadAsStringAsync();

                jsonObject = JsonConvert.DeserializeObject(json) as JObject;
            }
            return(jsonObject);
        }
Пример #22
0
 public static async Task Update(object data, Uri uri)
 {
     var json    = JsonConvert.SerializeObject(data);
     var content = new StringContent(json, Encoding.UTF8, "application/json");
     await client.PutAsync(uri, content);
 }
Пример #23
0
        public Task StartAsync(CancellationToken cancellationToken)
        {
            string apiUrl = "http://dockerapi:80/api";
            //string apiUrl = "http://xplatform.net/api";
            //string apiUrl = "http://localhost:5000/api";

            var apiClient = new CommonLib.WebApiClient();

            apiClient.addHeader("Authorization", "Bearer t.FwRjwQy5LHo3uXE0iQ6D4VGVFRvccr1_PItEHgLIOt4sc7QkQkBzd_eDACB0TTfnBBOWi_mtg84cPbvKwD4gpQ");
            CommonLib.Tinkoff.TinkoffClient _tinkoffClient = new CommonLib.Tinkoff.TinkoffClient(apiClient);

            MicexISSClient micexClient = new MicexISSClient(new CommonLib.WebApiClient());

            var xClient = new CommonLib.WebApiClient();

            Func <string, Quote> GetQuoteFromCandles = new Func <string, Quote>(data =>
            {
                JObject obj = JObject.Parse(data);

                JToken[] candles = null;

                if (obj["payload"]["candles"].Count() < 2)
                {
                    return(null);
                }

                candles = obj["payload"]["candles"]
                          .OrderByDescending(t => (DateTime)t["time"])
                          .Take(2).ToArray();


                return(new Quote()
                {
                    figi = (string)candles[0]["figi"],
                    open = decimal.Parse((string)candles[0]["o"], CultureInfo.InvariantCulture),
                    price = decimal.Parse((string)candles[0]["c"], CultureInfo.InvariantCulture),
                    previousClose = decimal.Parse((string)candles[1]["c"], CultureInfo.InvariantCulture)
                });
            });



            Action <string> activate = new Action <string>((arg) =>
            {
                _logger.Information($"Activation: {arg}");

                if (arg == "usaPriceUpdater")
                {
                    usaSubscription = usaQuoteSeq.Subscribe(q =>
                    {
                        Log.Information($"update price {q.symbol}");
                    },
                                                            ex =>
                    {
                        _logger.Error(ex, "usaPriceUpdater error");
                        restartStream.OnNext("usaPriceUpdater");
                    });
                }

                if (arg == "moscowPriceUpdater")
                {
                    moscowSubscription = moscowQuoteSeq.Subscribe(q =>
                    {
                        Log.Information($"update price {q.symbol}");
                    },
                                                                  ex =>
                    {
                        _logger.Error(ex, "moscowPriceUpdater error");
                        restartStream.OnNext("moscowPriceUpdater");
                    });
                }
            });



            usaQuoteSeq = Observable.Create <Quote>(async observer =>
            {
                string securities    = await xClient.GetData($"{apiUrl}/security");
                string currentQuotes = await xClient.GetData($"{apiUrl}/Quote");

                var securityCodes = JsonConvert.DeserializeObject <List <Security> >(securities).Where(s => s.Market == "shares" && s.Region == "United States").Select(s => s.Code);

                var quoteList = JsonConvert.DeserializeObject <List <Quote> >(currentQuotes)
                                .Where(q => securityCodes.Contains(q.symbol))
                                .OrderBy(q => q.symbol);
                //.OrderBy(q => q.lastUpdate);

                foreach (Quote quote in quoteList)
                {
                    observer.OnNext(quote);
                }

                observer.OnCompleted();
                return(Disposable.Empty);
            })
                          .Select(q => Observable.FromAsync(async() =>
            {
                //throw new Exception();
                string candles = await _tinkoffClient.GetCandles(q.figi, "day", DateTime.UtcNow.AddDays(-20), DateTime.UtcNow);

                Quote result = GetQuoteFromCandles(candles);

                if (result != null)
                {
                    result.Id     = q.Id;
                    result.symbol = q.symbol;
                    result.Board  = q.Board;

                    //post quote to server
                    string content            = JObject.FromObject(result).ToString();
                    HttpContent stringContent = new StringContent(content, Encoding.UTF8, "application/json");
                    await xClient.PostDataAsync($"{apiUrl}/Quote", stringContent);
                }

                if (result == null)
                {
                    result = new Quote()
                    {
                        symbol = q.symbol
                    };
                }

                return(result);
            }).Delay(TimeSpan.FromSeconds(5)))
                          .Concat()
                          .Repeat();

            moscowQuoteSeq = Observable.Create <MarketData>(async observer =>
            {
                string securities    = await xClient.GetData($"{apiUrl}/security");
                string currentQuotes = await xClient.GetData($"{apiUrl}/Quote");

                var securityObj = JsonConvert.DeserializeObject <List <Security> >(securities).Where(s => s.Region == "Moscow");

                var securityCodes = securityObj.Select(s => s.Code);
                var quoteList     = JsonConvert.DeserializeObject <List <Quote> >(currentQuotes)
                                    .Where(q => securityCodes.Contains(q.symbol))
                                    .OrderBy(q => q.symbol);

                foreach (Quote quote in quoteList)
                {
                    MarketData md = null;

                    md = new MarketData()
                    {
                        quote  = quote,
                        board  = quote.Board,
                        market = securityObj.First(s => s.Code == quote.symbol).Market,
                        ticker = quote.symbol
                    };

                    observer.OnNext(md);
                }

                observer.OnCompleted();
                return(Disposable.Empty);
            }).Select(md => Observable.FromAsync(async() =>
            {
                ISSResponse issResp = await micexClient.GetSecurityInfo(md.market, md.board, md.ticker);

                var result = new Quote()
                {
                    Id            = md.quote.Id,
                    symbol        = md.quote.symbol,
                    figi          = md.quote.figi,
                    open          = issResp.MarketData.First().OPEN,
                    price         = issResp.MarketData.First().LAST,
                    NKD           = issResp.SecurityInfo.First().NKD,
                    previousClose = issResp.SecurityInfo.First().PREVPRICE,
                    Board         = md.quote.Board
                };

                //post quote to server
                string content            = JObject.FromObject(result).ToString();
                HttpContent stringContent = new StringContent(content, Encoding.UTF8, "application/json");
                await xClient.PostDataAsync($"{apiUrl}/Quote", stringContent);

                return(result);
            }).Delay(TimeSpan.FromSeconds(10)))
                             .Concat()
                             .Repeat();

            restartStream
            .Delay(TimeSpan.FromMinutes(10))
            .Subscribe(proc =>
            {
                if (proc == "usaPriceUpdater")
                {
                    usaSubscription.Dispose();
                    usaSubscription = null;
                }

                if (proc == "moscowPriceUpdater")
                {
                    moscowSubscription.Dispose();
                    moscowSubscription = null;
                }

                activate(proc);
            });

            activate("usaPriceUpdater");
            activate("moscowPriceUpdater");

            return(Task.CompletedTask);
        }
        public HttpRequestMessage Build()
        {
            var httpMessage = new HttpRequestMessage(HttpMethod, UriBuilder.Uri);

            httpMessage.Version = HttpVersion;

            if (this.PathParams.Any())
            {
                var path = HttpUtility.UrlDecode(UriBuilder.Path);
                foreach (var p in this.PathParams)
                {
                    path = path.Replace("{" + p.Key + "}", p.Value, StringComparison.OrdinalIgnoreCase);
                }
                UriBuilder.Path = HttpUtility.UrlPathEncode(path);
            }

            if (this.QueryStrings.Any())
            {
                UriBuilder.Query = string.Join("&", this.QueryStrings.Select(q => q.Key + "=" + HttpUtility.UrlEncode(q.Value)));
            }

            if (this.HttpMethod == HttpMethod.Post || this.HttpMethod.Method == "PATCH" ||
                this.HttpMethod == HttpMethod.Put)
            {
                if (this.MultiPartAttribute != null)
                {
                    var multipleContent = new MultipartContent(this.MultiPartAttribute.MultiPartType, Guid.NewGuid().ToString());

                    if (FormBodys.Any())
                    {
                        var content = new FormUrlEncodedContent(this.FormBodys);
                        multipleContent.Add(content);
                    }
                    if (JsonBody != null)
                    {
                        var stringWriter = new StringWriter();
                        this.JsonSerializer.Serialize(stringWriter, JsonBody);
                        var content = new StringContent(stringWriter.ToString(), Utf8Encoding, "application/json");
                        multipleContent.Add(content);
                    }

                    if (RawContents.Any())
                    {
                        foreach (var c in RawContents)
                        {
                            multipleContent.Add(c);
                        }
                    }

                    httpMessage.Content = multipleContent;
                }
                else
                {
                    if (new[] {
                        FormBodys.Any(),
                        JsonBody != null,
                        RawContents.Any()
                    }.Count(i => i == true) > 1)
                    {
                        throw new NotSupportedException("Not support multiple kinds of http content in a message!");
                    }

                    if (FormBodys.Any())
                    {
                        httpMessage.Content = new FormUrlEncodedContent(this.FormBodys);
                        if (httpMessage.Content.Headers != null && httpMessage.Content.Headers.ContentType != null)
                        {
                            httpMessage.Content.Headers.ContentType.CharSet = Utf8Encoding.HeaderName;
                        }
                    }
                    else if (JsonBody != null)
                    {
                        var stringWriter = new StringWriter();
                        this.JsonSerializer.Serialize(stringWriter, JsonBody);
                        httpMessage.Content = new StringContent(stringWriter.ToString(), Utf8Encoding, "application/json");
                        if (httpMessage.Content.Headers != null && httpMessage.Content.Headers.ContentType != null)
                        {
                            httpMessage.Content.Headers.ContentType.CharSet = Utf8Encoding.HeaderName;
                        }
                    }
                    if (RawContents.Any())
                    {
                        httpMessage.Content = RawContents.FirstOrDefault();
                    }
                }
            }
            httpMessage.RequestUri = this.UriBuilder.Uri;


            foreach (var h in this.Headers.GroupBy(h => h.Key))
            {
                httpMessage.Headers.TryAddWithoutValidation(h.Key, h.Select(i => i.Value));
            }

            foreach (var c in this.Cookies)
            {
                httpMessage.Headers.GetCookies().Add(c);
            }


            return(httpMessage);
        }
Пример #25
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");


            string toTranslate = req.Query["text"];

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            toTranslate = toTranslate ?? data?.text;

            if (toTranslate == null)
            {
                var err = JsonConvert.SerializeObject(new { error = "field 'text' must be provided!" });
                return(new BadRequestObjectResult(err)
                {
                    ContentTypes = { "application/json" }
                });
            }
            try
            {
                // Call  API
                HttpClient newClient = new HttpClient();
                var        json      = JsonConvert.SerializeObject(new { text = toTranslate });

                var content = new StringContent(
                    json,
                    System.Text.Encoding.UTF8,
                    "application/json"
                    );

                using (HttpClient httpClient = new HttpClient())
                {
                    HttpResponseMessage result =
                        httpClient.PostAsync("https://api.funtranslations.com/translate/pirate.json",
                                             content).Result;

                    if (result.IsSuccessStatusCode)
                    {
                        JObject msg = JObject.Parse(result.Content.ReadAsStringAsync().Result);

                        string translated = (string)msg["contents"]["translated"];

                        //Return response
                        return(new OkObjectResult(translated));
                    }
                    else
                    {
                        JObject error = JObject.Parse(result.Content.ReadAsStringAsync().Result);
                        return(new BadRequestObjectResult(error));
                    }
                }
            }
            catch (Exception ex)
            {
                return(new BadRequestObjectResult(ex));
            }
        }
Пример #26
0
 public override Task <HttpResponseMessage> Execute(string url, StringContent stringContent)
 {
     return(Client.PostAsync(url, stringContent));
 }
        private static async Task MapAggregateContent(DownstreamContext originalContext, List <DownstreamContext> downstreamContexts)
        {
            var contentBuilder = new StringBuilder();

            contentBuilder.Append("{");

            var responseKeys = downstreamContexts.Select(s => s.DownstreamReRoute.Key).Distinct().ToList();

            for (var k = 0; k < responseKeys.Count; k++)
            {
                var contexts = downstreamContexts.Where(w => w.DownstreamReRoute.Key == responseKeys[k]).ToList();
                if (contexts.Count == 1)
                {
                    if (contexts[0].IsError)
                    {
                        MapAggregateError(originalContext, contexts[0]);
                        return;
                    }

                    var content = await contexts[0].DownstreamResponse.Content.ReadAsStringAsync();
                    contentBuilder.Append($"\"{responseKeys[k]}\":{content}");
                }
                else
                {
                    contentBuilder.Append($"\"{responseKeys[k]}\":");
                    contentBuilder.Append("[");

                    for (var i = 0; i < contexts.Count; i++)
                    {
                        if (contexts[i].IsError)
                        {
                            MapAggregateError(originalContext, contexts[i]);
                            return;
                        }

                        var content = await contexts[i].DownstreamResponse.Content.ReadAsStringAsync();
                        if (string.IsNullOrWhiteSpace(content))
                        {
                            continue;
                        }

                        contentBuilder.Append($"{content}");

                        if (i + 1 < contexts.Count)
                        {
                            contentBuilder.Append(",");
                        }
                    }

                    contentBuilder.Append("]");
                }

                if (k + 1 < responseKeys.Count)
                {
                    contentBuilder.Append(",");
                }
            }

            contentBuilder.Append("}");

            var stringContent = new StringContent(contentBuilder.ToString())
            {
                Headers = { ContentType = new MediaTypeHeaderValue("application/json") }
            };

            originalContext.DownstreamResponse = new DownstreamResponse(stringContent, HttpStatusCode.OK, new List <KeyValuePair <string, IEnumerable <string> > >(), "cannot return from aggregate..which reason phrase would you use?");
        }
 public async Task PostAsync_CallMethod_UnicodeStringContent(Uri remoteServer)
 {
     using (var client = new HttpClient())
     {
         string data = "\ub4f1\uffc7\u4e82\u67ab4\uc6d4\ud1a0\uc694\uc77c\uffda3\u3155\uc218\uffdb";
         var content = new StringContent(data, Encoding.UTF8);
         content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data);
         
         using (HttpResponseMessage response = await client.PostAsync(remoteServer, content))
         {
             Assert.Equal(HttpStatusCode.OK, response.StatusCode);
         }
     }
 }
 // string + chars(self) -> chars
 public override Content/*!*/ ConcatTo(StringContent/*!*/ content) {
     int count = content.Data.Length;
     var result = new char[count + _count];
     content.Data.CopyTo(0, result, 0, count);
     Array.Copy(_data, 0, result, count, _count);
     return new CharArrayContent(result, null);
 }
Пример #30
0
        async void performCodeExchangeAsync(string code, string code_verifier)
        {
            Ring.IsActive = true;
            string tokenRequestBody = string.Format(
                "code={0}&redirect_uri={1}&client_id={2}&code_verifier={3}&scope=&grant_type=authorization_code",
                code,
                System.Uri.EscapeDataString(redirectURI),
                clientID,
                code_verifier
                );
            StringContent content =
                new StringContent(tokenRequestBody, Encoding.UTF8, "application/x-www-form-urlencoded");

            HttpClientHandler handler = new HttpClientHandler();

            handler.AllowAutoRedirect = true;
            HttpClient client = new HttpClient(handler);

            //output(Environment.NewLine + "Exchanging code for tokens...");

            HttpResponseMessage response = await client.PostAsync(tokenEndpoint, content);

            string responseString = await response.Content.ReadAsStringAsync();

            //output(responseString);

            if (!response.IsSuccessStatusCode)
            {
                output("Authorization code exchange failed.");
                return;
            }

            JsonObject tokens      = JsonObject.Parse(responseString);
            string     accessToken = tokens.GetNamedString("access_token");

            client.DefaultRequestHeaders.Authorization =
                new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);

            //output("Making API Call to Userinfo...");
            HttpResponseMessage userinfoResponse = client.GetAsync(userInfoEndpoint).Result;
            //var info = await userinfoResponse.Content.ReadAsStringAsync();
            //JsonObject obj = JsonObject.Parse(info);
            string userinfoResponseContent = await userinfoResponse.Content.ReadAsStringAsync();

            output(userinfoResponseContent);

            UserInfo userInfo = Str2UserInfo(userinfoResponseContent);

            FileUtil.PostUser(userInfo);



            if (userinfoResponseContent != null)
            {
                App.sub         = userInfo.sub;
                App.name        = userInfo.name;
                App.given_name  = userInfo.given_name;
                App.family_name = userInfo.family_name;
                App.profile     = userInfo.profile;
                App.picture     = userInfo.picture;
                App.gender      = userInfo.gender;
                App.locale      = userInfo.locale;
                this.Frame.Navigate(typeof(MainScreen));
            }
        }
 // string + string -> string
 public override Content/*!*/ ConcatTo(StringContent/*!*/ content) {
     return new StringContent(content.Data + _data, null);
 }
        protected async void CreateItems <U>(U reportObject) where U : class
        {
            try
            {
                ToggleBusy(true);

                var client = await GetHTTPClient();

                var data = reportObject;

                var body = JsonConvert.SerializeObject(data, Formatting.None,
                                                       new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                });
                var contents = new StringContent(body);
                contents.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");
                if (CheckConnection())
                {
                    Device.BeginInvokeOnMainThread(async() =>
                    {
                        string url     = SPUtility.GetListURL(ReportType.FlighCrewVoyage);
                        var postResult = await client.PostAsync(url, contents);
                        if (postResult.IsSuccessStatusCode)
                        {
                            App.DAUtil.Delete(_flightcrew);

                            lblLoading.Text = "Item created successfully." + Environment.NewLine;

                            var spData = JsonConvert.DeserializeObject <SPData>(postResult.Content.ReadAsStringAsync().Result,
                                                                                new JsonSerializerSettings {
                                DateParseHandling = DateParseHandling.None
                            });
                            int itemId = spData.d.Id;

                            await Task.Delay(500);
                            await SendAttachments(itemId);

                            MessagingCenter.Send(this, "home");
                        }
                        else
                        {
                            var ex = await postResult.Content.ReadAsStringAsync();
                            await DisplayAlert("Error", ex, "Ok");
                        }

                        ToggleBusy(false);
                    });
                }
                else
                {
                    SaveOfflineItem(body, ReportType.FlighCrewVoyage, _attachementView.GetAttachmentInfoAsString());

                    await DisplayAlert("", "Item stored in local storage", "Ok");

                    ToggleBusy(false);
                    MessagingCenter.Send(this, "home");
                }
            }
            catch (HttpRequestException ex)
            {
                DependencyService.Get <IMessage>().ShortAlert("Upload Error");
            }
            catch (Exception ex)
            {
                DependencyService.Get <IMessage>().ShortAlert("Upload Error" + ex.Message);
            }
        }
Пример #33
0
 public abstract int ReverseOrdinalCompareTo(StringContent/*!*/ content);
        /// <summary>
        /// Analyze text.
        ///
        /// Analyzes text, HTML, or a public webpage for the following features:
        /// - Categories
        /// - Concepts
        /// - Emotion
        /// - Entities
        /// - Keywords
        /// - Metadata
        /// - Relations
        /// - Semantic roles
        /// - Sentiment
        /// - Syntax
        /// - Summarization (Experimental)
        ///
        /// If a language for the input text is not specified with the `language` parameter, the service [automatically
        /// detects the
        /// language](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-detectable-languages).
        /// </summary>
        /// <param name="features">Specific features to analyze the document for.</param>
        /// <param name="text">The plain text to analyze. One of the `text`, `html`, or `url` parameters is required.
        /// (optional)</param>
        /// <param name="html">The HTML file to analyze. One of the `text`, `html`, or `url` parameters is required.
        /// (optional)</param>
        /// <param name="url">The webpage to analyze. One of the `text`, `html`, or `url` parameters is required.
        /// (optional)</param>
        /// <param name="clean">Set this to `false` to disable webpage cleaning. For more information about webpage
        /// cleaning, see [Analyzing
        /// webpages](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-analyzing-webpages).
        /// (optional, default to true)</param>
        /// <param name="xpath">An [XPath
        /// query](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-analyzing-webpages#xpath)
        /// to perform on `html` or `url` input. Results of the query will be appended to the cleaned webpage text
        /// before it is analyzed. To analyze only the results of the XPath query, set the `clean` parameter to `false`.
        /// (optional)</param>
        /// <param name="fallbackToRaw">Whether to use raw HTML content if text cleaning fails. (optional, default to
        /// true)</param>
        /// <param name="returnAnalyzedText">Whether or not to return the analyzed text. (optional, default to
        /// false)</param>
        /// <param name="language">ISO 639-1 code that specifies the language of your text. This overrides automatic
        /// language detection. Language support differs depending on the features you include in your analysis. For
        /// more information, see [Language
        /// support](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-language-support).
        /// (optional)</param>
        /// <param name="limitTextCharacters">Sets the maximum number of characters that are processed by the service.
        /// (optional)</param>
        /// <returns><see cref="AnalysisResults" />AnalysisResults</returns>
        public DetailedResponse<AnalysisResults> Analyze(Features features, string text = null, string html = null, string url = null, bool? clean = null, string xpath = null, bool? fallbackToRaw = null, bool? returnAnalyzedText = null, string language = null, long? limitTextCharacters = null)
        {
            if (string.IsNullOrEmpty(Version))
            {
                throw new ArgumentNullException("`Version` is required");
            }
            if (features == null)
            {
                throw new ArgumentNullException("`features` is required for `Analyze`");
            }
            DetailedResponse<AnalysisResults> result = null;

            try
            {
                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.PostAsync($"{this.Endpoint}/v1/analyze");

                restRequest.WithHeader("Accept", "application/json");
                if (!string.IsNullOrEmpty(Version))
                {
                    restRequest.WithArgument("version", Version);
                }
                restRequest.WithHeader("Content-Type", "application/json");

                JObject bodyObject = new JObject();
                if (features != null)
                {
                    bodyObject["features"] = JToken.FromObject(features);
                }
                if (!string.IsNullOrEmpty(text))
                {
                    bodyObject["text"] = text;
                }
                if (!string.IsNullOrEmpty(html))
                {
                    bodyObject["html"] = html;
                }
                if (!string.IsNullOrEmpty(url))
                {
                    bodyObject["url"] = url;
                }
                if (clean != null)
                {
                    bodyObject["clean"] = JToken.FromObject(clean);
                }
                if (!string.IsNullOrEmpty(xpath))
                {
                    bodyObject["xpath"] = xpath;
                }
                if (fallbackToRaw != null)
                {
                    bodyObject["fallback_to_raw"] = JToken.FromObject(fallbackToRaw);
                }
                if (returnAnalyzedText != null)
                {
                    bodyObject["return_analyzed_text"] = JToken.FromObject(returnAnalyzedText);
                }
                if (!string.IsNullOrEmpty(language))
                {
                    bodyObject["language"] = language;
                }
                if (limitTextCharacters != null)
                {
                    bodyObject["limit_text_characters"] = JToken.FromObject(limitTextCharacters);
                }
                var httpContent = new StringContent(JsonConvert.SerializeObject(bodyObject), Encoding.UTF8, HttpMediaType.APPLICATION_JSON);
                restRequest.WithBodyContent(httpContent);

                restRequest.WithHeaders(Common.GetSdkHeaders("natural-language-understanding", "v1", "Analyze"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

                result = restRequest.As<AnalysisResults>().Result;
                if (result == null)
                {
                    result = new DetailedResponse<AnalysisResults>();
                }
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return result;
        }
Пример #35
0
			protected override async Task<Response> GetResponseFromHttp (
				TestContext ctx, HttpWebResponse response, WebException error, CancellationToken cancellationToken)
			{
				cancellationToken.ThrowIfCancellationRequested ();
				HttpContent content = null;

				ctx.LogDebug (4, $"{ME} GET RESPONSE FROM HTTP");

				switch (TestRunner.EffectiveType) {
				case HttpRequestTestType.ReadTimeout:
					return await ReadWithTimeout (5000, WebExceptionStatus.Timeout).ConfigureAwait (false);
				}

				using (var stream = response.GetResponseStream ()) {
					switch (TestRunner.EffectiveType) {
					case HttpRequestTestType.TestResponseStream:
						content = await TestResponseStream (stream).ConfigureAwait (false);
						break;

					case HttpRequestTestType.LargeChunkRead:
						content = await LargeChunkRead (stream).ConfigureAwait (false);
						break;

					case HttpRequestTestType.LargeGZipRead:
						content = await ReadAsString (stream).ConfigureAwait (false);
						break;

					case HttpRequestTestType.GZipWithLength:
						content = await GZipWithLength (stream).ConfigureAwait (false);
						break;

					case HttpRequestTestType.ResponseStreamCheckLength2:
						content = await ResponseStreamCheckLength (stream, true).ConfigureAwait (false);
						break;

					case HttpRequestTestType.ResponseStreamCheckLength:
						content = await ResponseStreamCheckLength (stream, false).ConfigureAwait (false);
						break;

					case HttpRequestTestType.GetNoLength:
						content = await GetNoLength (stream).ConfigureAwait (false);
						break;

					default:
						content = await ReadAsString (stream).ConfigureAwait (false);
						break;
					}
				}

				var status = response.StatusCode;

				response.Dispose ();
				finishedTcs.TrySetResult (true);
				return new SimpleResponse (this, status, content, error);

				async Task<Response> ReadWithTimeout (int timeout, WebExceptionStatus expectedStatus)
				{
					StreamReader reader = null;
					try {
						reader = new StreamReader (response.GetResponseStream ());
						var readTask = reader.ReadToEndAsync ();
						if (timeout > 0) {
							var timeoutTask = Task.Delay (timeout);
							var task = await Task.WhenAny (timeoutTask, readTask).ConfigureAwait (false);
							if (task == timeoutTask)
								throw ctx.AssertFail ("Timeout expired.");
						}
						var ret = await readTask.ConfigureAwait (false);
						ctx.LogMessage ($"EXPECTED ERROR: {ret}");
						throw ctx.AssertFail ("Expected exception.");
					} catch (WebException wexc) {
						ctx.Assert ((WebExceptionStatus)wexc.Status, Is.EqualTo (expectedStatus));
						return new SimpleResponse (this, HttpStatusCode.InternalServerError, null, wexc);
					} finally {
						finishedTcs.TrySetResult (true);
					}
				}

				async Task<HttpContent> ReadAsString (Stream stream)
				{
					using (var reader = new StreamReader (stream)) {
						string text = null;
						if (!reader.EndOfStream)
							text = await reader.ReadToEndAsync ().ConfigureAwait (false);
						return StringContent.CreateMaybeNull (text);
					}
				}

				async Task<HttpContent> TestResponseStream (Stream stream)
				{
					var buffer = new byte[5];
					var ret = await stream.ReadAsync (buffer, 4, 1).ConfigureAwait (false);
					ctx.Assert (ret, Is.EqualTo (1), "#A1");
					ctx.Assert (buffer[4], Is.EqualTo ((byte)65), "#A2");
					ret = await stream.ReadAsync (buffer, 0, 2);
					ctx.Assert (ret, Is.EqualTo (2), "#B1");
					return Handler.Content;
				}

				async Task<HttpContent> LargeChunkRead (Stream stream)
				{
					var buffer = new byte[43];
					var ret = await stream.ReadAsync (buffer, 0, buffer.Length).ConfigureAwait (false);
					ctx.Assert (ret, Is.EqualTo (ConnectionHandler.TheQuickBrownFox.Length), "#A1");
					var text = Encoding.UTF8.GetString (buffer, 0, ret);
					return new StringContent (text);
				}

				async Task<HttpContent> GZipWithLength (Stream stream)
				{
					using (var ms = new MemoryStream ()) {
						await stream.CopyToAsync (ms, 16384).ConfigureAwait (false);
						var bytes = ms.ToArray ();
						var text = Encoding.UTF8.GetString (bytes, 0, bytes.Length);
						return new StringContent (text);
					}
				}

				async Task<HttpContent> ResponseStreamCheckLength (Stream stream, bool chunked)
				{
					await ctx.AssertException<NotSupportedException> (() => Task.FromResult (stream.Length), "Length should throw");
					if (chunked) {
						ctx.Assert (response.ContentLength, Is.EqualTo (-1L), "ContentLength");
						ctx.Assert (response.Headers["Transfer-Encoding"], Is.EqualTo ("chunked"), "chunked encoding");
					} else {
						ctx.Assert (response.ContentLength, Is.EqualTo ((long)Handler.Content.Length), "ContentLength");
						ctx.Assert (response.Headers["Content-Length"], Is.EqualTo (Handler.Content.Length.ToString ()), "Content-Length header");
					}
					return await GZipWithLength (stream).ConfigureAwait (false);
				}

				async Task<HttpContent> GetNoLength (Stream stream)
				{
					ctx.Assert (response.ContentLength, Is.EqualTo (-1L), "ContentLength");
					ctx.Assert (response.Headers["Content-Length"], Is.Null, "No Content-Length: header");
					return await ReadAsString (stream);
				}
			}
Пример #36
0
 public TestHttpMessageHandler(string content = "test")
 {
     Content        = new StringContent(content);
     ContentFactory = () => Content;
 }
Пример #37
0
        /// <summary>
        /// Create Folder
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task <Object> CreateDocumentLibrary(string listTitle, string documentTemplateUrlTitle = null)
        {
            // return early if SharePoint is disabled.
            if (!IsValid())
            {
                return(null);
            }

            HttpRequestMessage endpointRequest =
                new HttpRequestMessage(HttpMethod.Post, ApiEndpoint + "web/Lists");

            if (documentTemplateUrlTitle == null)
            {
                documentTemplateUrlTitle = listTitle;
            }
            var library = CreateNewDocumentLibraryRequest(documentTemplateUrlTitle);


            string        jsonString = JsonConvert.SerializeObject(library);
            StringContent strContent = new StringContent(jsonString, Encoding.UTF8);

            strContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");
            endpointRequest.Content        = strContent;

            // make the request.
            var response = await _Client.SendAsync(endpointRequest);

            HttpStatusCode _statusCode = response.StatusCode;

            if (_statusCode != HttpStatusCode.Created)
            {
                string _responseContent = null;
                var    ex = new SharePointRestException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                _responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                ex.Request  = new HttpRequestMessageWrapper(endpointRequest, null);
                ex.Response = new HttpResponseMessageWrapper(response, _responseContent);

                endpointRequest.Dispose();
                if (response != null)
                {
                    response.Dispose();
                }
                throw ex;
            }
            else
            {
                jsonString = await response.Content.ReadAsStringAsync();

                var ob = Newtonsoft.Json.JsonConvert.DeserializeObject <DocumentLibraryResponse>(jsonString);

                if (listTitle != documentTemplateUrlTitle)
                {
                    // update list title
                    endpointRequest = new HttpRequestMessage(HttpMethod.Post, $"{ApiEndpoint}web/lists(guid'{ob.d.Id}')");
                    var type    = new { type = "SP.List" };
                    var request = new
                    {
                        __metadata = type,
                        Title      = listTitle
                    };
                    jsonString = JsonConvert.SerializeObject(request);
                    strContent = new StringContent(jsonString, Encoding.UTF8);
                    strContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");
                    endpointRequest.Headers.Add("IF-MATCH", "*");
                    endpointRequest.Headers.Add("X-HTTP-Method", "MERGE");
                    endpointRequest.Content = strContent;
                    response = await _Client.SendAsync(endpointRequest);

                    jsonString = await response.Content.ReadAsStringAsync();

                    response.EnsureSuccessStatusCode();
                }
            }

            return(library);
        }
Пример #38
0
        public async Task <XmlElement> SubmitRequestAsync(GalWebMethod _methodName, string _token, XmlElement _request, string _filter)
        {
            string svcCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(UserName + ":" + Password));

            XDocument          soapEnvelopeXml = GetSoapEnvelope(_methodName, _token, _request.GetXElement(), _filter);
            HttpClient         httpClient      = new HttpClient();
            HttpContent        httpContent     = new StringContent(soapEnvelopeXml.ToString());
            HttpRequestMessage req             = new HttpRequestMessage(HttpMethod.Post, Url);

            req.Headers.Add("SOAPAction", "\"" + WebServiceNS + _methodName.ToString() + "\"");
            req.Headers.Add("Authorization", "Basic " + svcCredentials);
            req.Method  = HttpMethod.Post;
            req.Content = httpContent;
            req.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml; charset=utf-8");

            HttpResponseMessage response;

            response = await httpClient.SendAsync(req);

            var responseBodyAsText = await response.Content.ReadAsStringAsync();

            #region C O M M E N T E D  C O D E  U S I N G   HttpWebRequest

            /*
             * HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Url);
             * webRequest.Headers["SOAPAction"] = "http://webservices.galileo.com/" + _methodName.ToString();
             * webRequest.Headers["Authorization"] = "Basic " + svcCredentials;
             * webRequest.ContentType = "text/xml;charset=\"utf-8\"";
             * webRequest.Accept = "text/xml";
             * webRequest.Method = "POST";
             *
             *
             *
             * using (var stream = await Task.Factory.FromAsync<Stream>(webRequest.BeginGetRequestStream, webRequest.EndGetRequestStream, null))
             * {
             *  soapEnvelopeXml.Save(stream);
             * }
             *
             *
             *
             * // begin async call to web request.
             * IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
             *
             * // suspend this thread until call is complete. You might want to
             * // do something usefull here like update your UI.
             * asyncResult.AsyncWaitHandle.WaitOne();
             *
             * // get the response from the completed web request.
             * string soapResult;
             * using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
             * {
             *  using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
             *  {
             *      soapResult = rd.ReadToEnd();
             *  }
             * }
             */
            #endregion

            return(GetResponseBody(_methodName, responseBodyAsText));
        }
            public void GivenContentWithBlacklistedWordsWhereWordIsInBlackListTwice_PhrasesThatExist_PhraseOnlyReturnedOnce()
            {
                // Arrange.
                const string content = "This is zebra content with an aardvark ass in it.";
                
                IList<string> fakeBlacklist = new List<string>();
                fakeBlacklist.Add("aardvark");
                fakeBlacklist.Add("ass");
                fakeBlacklist.Add("Ass");
                fakeBlacklist.Add("zebra");
                var stringContent = new StringContent(fakeBlacklist);

                // Act.
                var result = stringContent.PhrasesThatExist(content);

                // Assert.
                Assert.NotNull(result);
                Assert.NotEmpty(result);
                Assert.NotEqual(fakeBlacklist.Count, result.Count);
            }
        public async Task PostAsync_Redirect_ResultingGetFormattedCorrectly(bool secure)
        {
            const string ContentString = "This is the content string.";
            var content = new StringContent(ContentString);
            Uri redirectUri = Configuration.Http.RedirectUriForDestinationUri(
                secure,
                302,
                secure ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer,
                1);

            using (var client = new HttpClient())
            using (HttpResponseMessage response = await client.PostAsync(redirectUri, content))
            {
                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                string responseContent = await response.Content.ReadAsStringAsync();
                Assert.DoesNotContain(ContentString, responseContent);
                Assert.DoesNotContain("Content-Length", responseContent);
            }
        }
Пример #41
0
        private static async Task <HttpResponseMessage> GetResponse(HttpClient client, StringContent content, string endPoint)
        {
            HttpResponseMessage response = null;

            try
            {
                var url = $"https://identitytoolkit.googleapis.com/v1/accounts:{endPoint}?key={_apiKey}";
                response = await client.PostAsync(url, content);
            }
            catch (System.Net.Http.HttpRequestException)
            {
                MessageBox.Show("Please check your Internet connection!", "Failed Request", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception)
            {
                throw;
            }
            return(response);
        }
Пример #42
0
		public HttpRequestHandler (HttpRequestTestRunner parent)
			: base (parent.EffectiveType.ToString ())
		{
			TestRunner = parent;
			ME = $"{GetType ().Name}({parent.EffectiveType})";
			readyTcs = new TaskCompletionSource<bool> ();
			Flags = RequestFlags.KeepAlive;

			switch (parent.EffectiveType) {
			case HttpRequestTestType.LargeHeader:
			case HttpRequestTestType.LargeHeader2:
			case HttpRequestTestType.SendResponseAsBlob:
				Content = ConnectionHandler.TheQuickBrownFoxContent;
				CloseConnection = true;
				break;
			case HttpRequestTestType.CloseRequestStream:
				OperationFlags = HttpOperationFlags.AbortAfterClientExits;
				CloseConnection = false;
				break;
			case HttpRequestTestType.ReadTimeout:
				CloseConnection = false;
				break;
			case HttpRequestTestType.RedirectNoLength:
				Target = new HelloWorldHandler (ME);
				OperationFlags |= HttpOperationFlags.RedirectOnNewConnection;
				CloseConnection = false;
				break;
			case HttpRequestTestType.PutChunked:
			case HttpRequestTestType.PutChunkDontCloseRequest:
				CloseConnection = true;
				break;
			case HttpRequestTestType.ServerAbortsRedirect:
				OperationFlags = HttpOperationFlags.ServerAbortsRedirection;
				CloseConnection = false;
				break;
			case HttpRequestTestType.ServerAbortsPost:
				OperationFlags = HttpOperationFlags.ServerAbortsRedirection;
				CloseConnection = true;
				break;
			case HttpRequestTestType.PostChunked:
				OperationFlags = HttpOperationFlags.DontReadRequestBody;
				CloseConnection = false;
				break;
			case HttpRequestTestType.EntityTooBig:
			case HttpRequestTestType.ClientAbortsPost:
				OperationFlags = HttpOperationFlags.AbortAfterClientExits | HttpOperationFlags.DontReadRequestBody;
				CloseConnection = false;
				break;
			case HttpRequestTestType.PostContentLength:
				OperationFlags = HttpOperationFlags.DontReadRequestBody;
				break;
			case HttpRequestTestType.SimpleGZip:
				Content = HttpContent.TheQuickBrownFox;
				CloseConnection = true;
				break;
			case HttpRequestTestType.TestResponseStream:
				Content = new StringContent ("AAAA");
				CloseConnection = true;
				break;
			case HttpRequestTestType.LargeChunkRead:
				Content = HttpContent.TheQuickBrownFoxChunked;
				ExpectedContent = Content.RemoveTransferEncoding ();
				CloseConnection = false;
				break;
			case HttpRequestTestType.LargeGZipRead:
				Content = ConnectionHandler.GetLargeChunkedContent (16384);
				ExpectedContent = Content.RemoveTransferEncoding ();
				CloseConnection = false;
				break;
			case HttpRequestTestType.GZipWithLength:
				Content = ConnectionHandler.GetLargeStringContent (16384);
				ExpectedContent = Content;
				CloseConnection = false;
				break;
			case HttpRequestTestType.ResponseStreamCheckLength2:
				Content = HttpContent.HelloChunked;
				ExpectedContent = Content.RemoveTransferEncoding ();
				CloseConnection = false;
				break;
			case HttpRequestTestType.ResponseStreamCheckLength:
				Content = HttpContent.HelloWorld;
				ExpectedContent = Content;
				CloseConnection = false;
				break;
			case HttpRequestTestType.GetNoLength:
				ExpectedContent = ConnectionHandler.TheQuickBrownFoxContent;
				CloseConnection = false;
				break;
			case HttpRequestTestType.ImplicitHost:
			case HttpRequestTestType.CustomHost:
			case HttpRequestTestType.CustomHostWithPort:
			case HttpRequestTestType.CustomHostDefaultPort:
				CloseConnection = false;
				break;
			default:
				throw new NotSupportedException (parent.EffectiveType.ToString ());
			}

			if (CloseConnection)
				Flags |= RequestFlags.CloseConnection;

			if (ExpectedContent == null)
				ExpectedContent = Content ?? new StringContent (ME);
		}
            public void GivenSomeContentWithNoBadWordsAndBadPhrasesSuppliedSeparately_PhrasesThatExist_ReturnsAListOfBadPhrasesFound()
            {
                // Arrange.
                const string content =
                    "sdhfasjdfh sadfo8as 68sa6t &%7tsTSOtafdsf dsakf haspdf y78 6* ";

                var stringContent = new StringContent();

                // Act.
                var results = stringContent.PhrasesThatExist(content, PhraseList);

                // Assert.
                Assert.Null(results);
            }
        public async Task Run([BlobTrigger("vision/{name}", Connection = "StorageConnectionString")] Stream myBlob, string name,
                              [CosmosDB(
                                   databaseName: "%CosmosDB%",
                                   collectionName: "%CosmosCollection%",
                                   ConnectionStringSetting = "CosmosDBConnection")] IAsyncCollector <Entry> document,
                              [TwilioSms(
                                   AccountSidSetting = "TwilioAccountSid",
                                   AuthTokenSetting = "TwilioAuthToken",
                                   From = "%FromNumber%")] IAsyncCollector <CreateMessageOptions> smsOptions,
                              ILogger log)
        {
            //We need to obtain linux timestamp from image name
            //(8 chars "capture_" prefix, 12 = prefix + ."jpg" suffix)
            var timeStampString = name.Substring(8, name.Length - 12);
            var dto             = DateTimeOffset.FromUnixTimeMilliseconds(Convert.ToInt64(timeStampString));
            var timestamp       = dto.DateTime;

            List <string> entrants = new List <string>();

            try
            {
                //Make sure you specify Recognition Model, which was used when creating person in person group
                var detectedFaces = await _faceClient.Face.DetectWithStreamAsync(myBlob, recognitionModel : RecognitionModel.Recognition02);

                var group = (await _faceClient.PersonGroup.ListAsync())
                            .Where(g => g.Name == Environment.GetEnvironmentVariable("PersonGroupName")).FirstOrDefault();

                var dfIds = detectedFaces.Select(f => f.FaceId.ToGuid()).ToList();

                if (dfIds.Count != 0 && group != null)
                {
                    var identifiedFaces = await _faceClient.Face.IdentifyAsync(dfIds, group.PersonGroupId);

                    log.LogInformation(identifiedFaces.Count().ToString());

                    if (identifiedFaces.Count > 0)
                    {
                        foreach (var f in identifiedFaces)
                        {
                            if (f.Candidates.Count > 0 && f.Candidates.First().Confidence > 0.7)
                            {
                                var pInfo = await _faceClient.PersonGroupPerson.GetAsync(group.PersonGroupId, f.Candidates.First().PersonId);

                                //We put it to lower, as LUIS entities are always returned in "ToLower" form
                                entrants.Add(pInfo.Name.ToLower());
                            }
                        }
                    }
                }

                var entry = new Entry(Guid.NewGuid().ToString(), timestamp, entrants, name.ToLower());
                await document.AddAsync(entry);

                if (!entrants.Any())
                {
                    //If no known entrant identified, we send sms notification
                    await smsOptions.AddAsync(new CreateMessageOptions(Environment.GetEnvironmentVariable("ToNumber"))
                    {
                        Body = "Warning, unidentified entrant!"
                    });
                }

                //Invoking Bot Proactive message by sending request to notify endpoint
                var content = new StringContent($"{{\"imageName\":\"{name}\",\"text\":\"{String.Join(", ", entrants.ToArray())}\"}}", Encoding.UTF8, "application/json");
                await _httpClient.PostAsync(Environment.GetEnvironmentVariable("ProactiveBotEndpoint"), content);
            }
            catch (Exception e)
            {
                log.LogInformation(e.Message);
            }

            log.LogInformation("Succesfully processed blob: " + name);
        }
 public async Task PostAsync_CallMethod_EmptyContent(Uri remoteServer)
 {
     using (var client = new HttpClient())
     {
         var content = new StringContent(string.Empty);
         using (HttpResponseMessage response = await client.PostAsync(remoteServer, content))
         {
             Assert.Equal(HttpStatusCode.OK, response.StatusCode);
             
             string responseContent = await response.Content.ReadAsStringAsync();
             _output.WriteLine(responseContent);                    
             TestHelper.VerifyResponseBody(
                 responseContent,
                 response.Content.Headers.ContentMD5,
                 false,
                 string.Empty);                  
         }
     }
 }
Пример #46
0
        private async void btnSave_Clicked(object sender, EventArgs e)
        {
            if (Result.Equals("AddPlace"))//AddPlace
            {
                if (tblErrPlaceName.IsVisible == false && tblErrIpAddress.IsVisible == false && tblErrAddress.IsVisible == false && tblErrPassWordAPI.IsVisible == false && tblErrPassWordDB.IsVisible == false && tblErrPortAPI.IsVisible == false && tblErrPortDB.IsVisible == false && tblErrUsernameAPI.IsVisible == false && tblErrUsernameDB.IsVisible == false && pkrTypePlace.SelectedItem != null)
                {
                    placeModel             = new PlaceModel();
                    placeModel.Name        = Name;
                    placeModel.PassWordAPI = PassWordAPI;
                    placeModel.PassWordDB  = PassWordDB;
                    placeModel.PortAPI     = Int32.Parse(PortAPI);
                    placeModel.PortDB      = Int32.Parse(PortDB);
                    placeModel.TypePlace   = pkrTypePlace.SelectedIndex;
                    placeModel.UserNameAPI = UserNameAPI;
                    placeModel.UserNameDB  = UserNameDB;
                    placeModel.Address     = Address;
                    placeModel.IpAddress   = IpAddress;

                    string url = "http://" + Global.Intance.SerIpAdress + ":" + Global.Intance.SerPortAPI + "/api/AddNewPlace";

                    try
                    {
                        var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                        var fileName  = Path.Combine(documents, "cookie.txt");
                        var cookie    = File.ReadAllText(fileName);

                        HttpClient client   = new HttpClient();
                        string     jsonData = JsonConvert.SerializeObject(placeModel);

                        StringContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                        content.Headers.Add("cookie", cookie);
                        HttpResponseMessage response = await client.PostAsync(url, content);

                        string result = await response.Content.ReadAsStringAsync();

                        //int responseData = Int32.Parse(result);

                        var responseData = JsonConvert.DeserializeObject <RespondPlaceModel>(result);

                        if (responseData != null && responseData.Result == true)
                        {
                            //DependencyService.Get<IMessage>().ShortTime(message);
                            ////MessagingCenter.Send(this, "Update");//Gửi thông điệp update listview về PlacePage
                            //await Navigation.PushAsync(new PlacePage(User));
                            //await Navigation.PopAsync();

                            MessagingCenter.Send(this, "Update");//Gửi thông điệp update listview về PlacePage
                            await Navigation.PopAsync();

                            var message = "Thành công!";
                            DependencyService.Get <IMessage>().ShortTime(message.ToString());
                        }
                        else if (responseData != null && responseData.Result == false)
                        {
                            var message = responseData.Content.ToString();
                            DependencyService.Get <IMessage>().LongTime(message);
                        }
                        else
                        {
                            var message = "Thêm không thành công!";
                            DependencyService.Get <IMessage>().LongTime(message);
                        }
                    }
                    catch (Exception ex)
                    {
                        var Err = "Không nết nối được máy chủ";
                        DependencyService.Get <IMessage>().LongTime(Err);
                    }
                }
                else
                {
                    if (pkrTypePlace.SelectedItem == null)
                    {
                        await DisplayAlert("Thông báo", "Vui lòng chọn loại cơ sở!", "OK");
                    }
                    else
                    {
                        await DisplayAlert("Thông báo", "Vui lòng nhập đúng thông tin!", "OK");
                    }
                }
            }
            else //EditPlace
            {
                if (tblErrPlaceName.IsVisible == false && tblErrIpAddress.IsVisible == false && tblErrAddress.IsVisible == false && tblErrPassWordAPI.IsVisible == false && tblErrPassWordDB.IsVisible == false && tblErrPortAPI.IsVisible == false && tblErrPortDB.IsVisible == false && tblErrUsernameAPI.IsVisible == false && tblErrUsernameDB.IsVisible == false && pkrTypePlace.SelectedItem != null && !string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Address) && !string.IsNullOrEmpty(PortDB) && !string.IsNullOrEmpty(UserNameDB) && !string.IsNullOrEmpty(PassWordDB) && !string.IsNullOrEmpty(PortAPI) && !string.IsNullOrEmpty(UserNameAPI) && !string.IsNullOrEmpty(PassWordAPI) && pkrTypePlace.SelectedIndex != -1)
                {
                    placeModel.Name        = Name;
                    placeModel.PassWordAPI = PassWordAPI;
                    placeModel.PassWordDB  = PassWordDB;
                    placeModel.PortAPI     = Int32.Parse(PortAPI);
                    placeModel.PortDB      = Int32.Parse(PortDB);
                    placeModel.TypePlace   = pkrTypePlace.SelectedIndex;
                    placeModel.UserNameAPI = UserNameAPI;
                    placeModel.UserNameDB  = UserNameDB;
                    placeModel.Address     = Address;

                    string url = "http://" + Global.Intance.SerIpAdress + ":" + Global.Intance.SerPortAPI + "/api/EditPlace";

                    try
                    {
                        var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                        var fileName  = Path.Combine(documents, "cookie.txt");
                        var cookie    = File.ReadAllText(fileName);

                        HttpClient client   = new HttpClient();
                        string     jsonData = JsonConvert.SerializeObject(placeModel);

                        StringContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                        content.Headers.Add("cookie", cookie);
                        HttpResponseMessage response = await client.PostAsync(url, content);

                        string result = await response.Content.ReadAsStringAsync();

                        var responseData = JsonConvert.DeserializeObject <RespondPlaceModel>(result);

                        if (responseData != null && responseData.Result == true)
                        {
                            MessagingCenter.Send(this, "Update");//Gửi thông điệp update listview về PlacePage
                            await Navigation.PopAsync();

                            var message = responseData.Content;
                            DependencyService.Get <IMessage>().ShortTime(message[0].ToString());
                        }
                        else
                        {
                            var message = "Không thành công!";
                            DependencyService.Get <IMessage>().LongTime(message);
                        }
                    }
                    catch (Exception ex)
                    {
                        var Err = "Không nết nối được máy chủ";
                        DependencyService.Get <IMessage>().LongTime(Err);
                    }
                }
                else
                {
                    if (pkrTypePlace.SelectedItem == null)
                    {
                        await DisplayAlert("Thông báo", "Vui lòng chọn loại cơ sở!", "OK");
                    }
                    else
                    {
                        await DisplayAlert("Thông báo", "Vui lòng nhập đúng thông tin!", "OK");
                    }
                }
            }
        }
        public async Task PostAsync_CallMethodTwice_StringContent(Uri remoteServer)
        {
            using (var client = new HttpClient())
            {
                string data = "Test String";
                var content = new StringContent(data, Encoding.UTF8);
                content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data);
                HttpResponseMessage response;
                using (response = await client.PostAsync(remoteServer, content))
                {
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                }

                // Repeat call.
                content = new StringContent(data, Encoding.UTF8);
                content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data);
                using (response = await client.PostAsync(remoteServer, content))
                {
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                }
            }
        }
Пример #48
0
        private async void login_Tapped(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(email.Text) && !string.IsNullOrEmpty(password.Text))
            {
                if (NetworkCheck.IsInternet())
                {
                    using (var client = new HttpClient())
                    {
                        var postData = new UserRegister
                        {
                            email   = email.Text,
                            userPWD = password.Text
                        };
                        // create the request content and define Json
                        var json    = JsonConvert.SerializeObject(postData);
                        var content = new StringContent(json, Encoding.UTF8, "application/json");

                        //  send a POST request
                        var uri    = app.url + "/AR_admin/userlogin";
                        var result = await client.PostAsync(uri, content);

                        if (result.IsSuccessStatusCode)
                        {
                            var resultString = await result.Content.ReadAsStringAsync();

                            var post = JsonConvert.DeserializeObject <Result>(resultString);
                            if (post != null && post.result != null && post.result != "" && post.result == "0")
                            {
                                if (Xamarin.Forms.Application.Current.Properties.ContainsKey("email") != false)
                                {
                                    Xamarin.Forms.Application.Current.Properties["email"] = email.Text;
                                }
                                else
                                {
                                    Xamarin.Forms.Application.Current.Properties.Add("email", email.Text);
                                }
                                await Xamarin.Forms.Application.Current.SavePropertiesAsync();

                                //write user login log
                                var postLogData = new UserLog
                                {
                                    email = email.Text
                                };
                                var jsonLog    = JsonConvert.SerializeObject(postLogData);
                                var contentLog = new StringContent(jsonLog, Encoding.UTF8, "application/json");

                                //  send a POST request
                                var uriLog    = app.url + "/AR_admin/UserLoginLog";
                                var resultLog = await client.PostAsync(uriLog, contentLog);

                                //導到選擇模式畫面
                                await Navigation.PushAsync(new MyProfile(), true);

                                Navigation.RemovePage(this);
                            }
                            else
                            {
                                await DisplayAlert("訊息", "登入失敗!", "OK");
                            }
                        }
                        else
                        {
                            await DisplayAlert("訊息", app.errorMessage, "OK");
                        }
                    }
                }
                else
                {
                    await DisplayAlert("訊息", app.networkMessage, "OK");
                }
            }
            else
            {
                await DisplayAlert("訊息", "請輸入Email和密碼!", "OK");
            }
        }
 internal CharArrayContent/*!*/ Concatenate(StringContent/*!*/ content) {
     int count = content.Data.Length;
     var result = new char[_count + count];
     Array.Copy(_data, 0, result, 0, _count);
     content.Data.CopyTo(0, result, _count, count);
     return new CharArrayContent(result, null);
 }
        public async void MPostAsync()
        {
            string url    = "http://blumonpay.biz/BancaMifel/Pruebas/login_test";
            string myJson = "{'Usuario':'asd','Contrasena':'123'}";
            var    obj    = new Login {
                User = "******", Pass = "******"
            };
            string json  = JsonConvert.SerializeObject(obj, Formatting.Indented);
            string json2 = await Task.Run(() => JsonConvert.SerializeObject(obj, Formatting.Indented));

            var httpContent = new StringContent(myJson, Encoding.UTF8, "application/json");

            using (var httpClient = new HttpClient())
            {
                var httpResponse = await httpClient.PostAsync(url, httpContent);

                if (httpResponse.Content != null)
                {
                    var responseContent = await httpResponse.Content.ReadAsStringAsync();

                    lblMensaje.Text = responseContent;
                }
            }

            //HttpClient client = new HttpClient();
            //client.BaseAddress = new Uri("http://example.com/");
            //client.DefaultRequestHeaders
            //      .Accept
            //      .Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "relativeAddress");
            //request.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}",
            //                                    Encoding.UTF8,
            //                                    "application/json");


            //var request = (HttpWebRequest)WebRequest.Create(url);
            //request.ContentType = "application/json";
            //request.Method = "POST";



            //using (var client = new HttpClient())
            //{
            //    var response = await client.PostAsync(
            //        url,
            //         new StringContent("{\"Usuario\":\"Doe\",\"Contrasena\":33}", Encoding.UTF8, "application/json"));
            //    lblMensaje.Text = await response.Content.ReadAsStringAsync();

            //}



            //HttpResponseMessage response = null;
            //try
            //{
            //    using (var client = new HttpClient())
            //    {
            //        response = client.PostAsync(
            //         url,
            //          new StringContent(json, Encoding.UTF8, "application/json")).Result;
            //        if (response.IsSuccessStatusCode)
            //        {
            //            lblMensaje.Text = response.StatusCode.ToString();
            //        }
            //        else
            //        {
            //            lblMensaje.Text = "NO OK";
            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //    lblMensaje.Text = "Error";
            //}



            //var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            //httpWebRequest.ContentType = "application/json";
            //httpWebRequest.Method = "POST";
            //using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            //{
            //    string json2 = "{\"Usuario\":\"test\"," +
            //                  "\"Contrasena\":\"bla\"}";
            //    streamWriter.Write(json2);
            //    streamWriter.Flush();
            //    streamWriter.Close();
            //}
            //var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            //using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            //{
            //    var result = streamReader.ReadToEnd();
            //    lblMensaje.Text = result;
            //}



            //var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

            //httpWebRequest.ContentType = "application/json";
            //httpWebRequest.Method = "POST";
            //using (var streamWriter = new

            //StreamWriter(httpWebRequest.GetRequestStream()))
            //{

            //    streamWriter.Write(new StringContent(myJson, Encoding.UTF8, "application/json"));
            //}
            //var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            //using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            //{
            //    var result = streamReader.ReadToEnd();
            //    lblMensaje.Text = result.ToString();
            //}



            //var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            //httpWebRequest.ContentType = "application/json";
            //httpWebRequest.Method = "POST";
            //using (var streamWriter = new

            //StreamWriter(httpWebRequest.GetRequestStream()))
            //{

            //    streamWriter.Write(json);
            //}
            //var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            //using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            //{
            //    var result = streamReader.ReadToEnd();
            //    lblMensaje.Text = result;
            //}


            //using (HttpClient client = new HttpClient())
            //{
            //    using (HttpResponseMessage response = await client.PostAsync(url, new StringContent(myJson, Encoding.UTF8, "application/json")))
            //    {

            //        using (HttpContent content = response.Content)
            //        {
            //            string   = await content.ReadAsStringAsync();
            //            lblMensaje.Text = MyContent;
            //        }
            //    }
            //}
        }
            // content.chars + this.chars[start, count]
            public override void AppendTo(StringContent/*!*/ content, int start, int count) {
                if (start > _count - count) {
                    throw new ArgumentOutOfRangeException("start");
                }

                content.Append(_data, start, count);
            }
Пример #52
0
        // uploads public key to server under the 'email' passed in, updates private key on this machine with 'email'
        void sendKey(string email)
        {
            var oldJson = "";

            try
            {
                oldJson = File.ReadAllText(Directory.GetCurrentDirectory() + "\\public.key");
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine("You are trying to send a key that does not exist!");
                Environment.Exit(1);
            }

            var pk = JsonSerializer.Deserialize <Key>(oldJson);

            pk.email = email;
            var newJson = JsonSerializer.Serialize(pk);

            using (var client = new HttpClient())
            {
                var uriFull  = uri + "/Key/" + email;
                var content  = new StringContent(newJson, Encoding.UTF8, "application/json");
                var response = client.PutAsync(uriFull, content).Result;

                // if query executed successfully, process the response data
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("Key Saved");
                }
                else
                {
                    Console.WriteLine("Query failed: " + response.ReasonPhrase);
                    Environment.Exit(1);
                }
            }

            // key was placed correctly, so update private.key with associated email
            var oldPrivate = File.ReadAllText(Directory.GetCurrentDirectory() + "\\private.key");
            var keyObj     = JsonSerializer.Deserialize <PrivateKey>(oldPrivate);
            var addresses  = new List <string>();

            foreach (var addr in keyObj.email)
            {
                addresses.Add(addr);
            }
            addresses.Add(email);
            keyObj.email = addresses.ToArray();

            var newPk = JsonSerializer.Serialize(keyObj);

            using (var fileStream = new StreamWriter(Directory.GetCurrentDirectory() + "\\private.key"))
            {
                try
                {
                    fileStream.WriteLine(newPk);
                }
                catch (IOException)
                {
                    Console.WriteLine("Could not edit private.key!");
                    Environment.Exit(1);
                }
            }
        }
 // content.chars <=> this.chars
 public override int ReverseOrdinalCompareTo(StringContent/*!*/ content) {
     return content.OrdinalCompareTo(_data);
 }
Пример #54
0
        // finds key on local machine that corresponds to the 'email' param, then encrypts using that public key.
        // finally we base64 encode the message and pass it on to the server
        void sendMsg(string email, string msg)
        {
            // look for key
            var keyPath = Directory.GetCurrentDirectory() + "\\" + email + ".key";

            // get key and deserialize
            var keyJson = "";

            try
            {
                keyJson = File.ReadAllText(keyPath);
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine("Key does not exist for " + email);
                Environment.Exit(1);
            }
            catch (IOException)
            {
                Console.WriteLine("Could not access key for " + email + "!");
                Environment.Exit(1);
            }

            var keyObj = JsonSerializer.Deserialize <Key>(keyJson);

            // decode key
            var key   = keyObj.key;
            var bytes = Convert.FromBase64String(key);

            // get # of bytes for 1st value 'e'
            var first4 = new byte[4];

            for (var i = 0; i < 4; i++)
            {
                first4[i] = bytes[i];
            }
            // reverse if necessary due to endianness
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(first4);
            }
            var eLen = new BigInteger(first4);

            // read bytes for 'e', and convert to BigInt
            var eBytes = new byte[(int)eLen];

            for (var i = 0; i < eLen; i++)
            {
                eBytes[i] = bytes[i + 4];
            }
            var eVal = new BigInteger(eBytes);

            // get # of bytes for 2nd value 'n'
            var second4 = new byte[4];

            for (var i = 0; i < 4; i++)
            {
                second4[i] = bytes[i + 4 + (int)eLen];
            }
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(second4);
            }
            var rLen = new BigInteger(second4);

            // read bytes for 'n' and convert to BigInt
            var rBytes = new byte[(int)rLen];

            for (var i = 0; i < rLen; i++)
            {
                rBytes[i] = bytes[8 + (int)eLen + i];
            }
            var rVal = new BigInteger(rBytes);

            // encode message
            var msgBigInt = new BigInteger(Encoding.ASCII.GetBytes(msg));
            var msgModPow = BigInteger.ModPow(msgBigInt, eVal, rVal);
            var msgBase64 = Convert.ToBase64String(msgModPow.ToByteArray());
            var msgObj    = new Message();

            msgObj.email   = email;
            msgObj.content = msgBase64;
            var jsonMsg = JsonSerializer.Serialize(msgObj);

            // send message
            using (var client = new HttpClient())
            {
                var uriFull = uri + "/Message/" + email;
                var content = new StringContent(jsonMsg, Encoding.UTF8, "application/json");

                var response = client.PutAsync(uriFull, content).Result;

                // if query executed successfully, process the response data
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("Message Written");
                }
                else
                {
                    Console.WriteLine("Query failed: " + response.ReasonPhrase);
                    Environment.Exit(1);
                }
            }
        }
 // content.chars + this.chars[start, count]
 public override void AppendTo(StringContent/*!*/ content, int start, int count) {
     content.Append(_data, start, count);
 }
        // Helper function to greet user with information in GreetingState.
        private async Task <DialogTurnResult> GetPolicyRenewalDate(WaterfallStepContext stepContext)
        {
            var context       = stepContext.Context;
            var greetingState = await UserProfileAccessor.GetAsync(context);

            // Display their profile information and end dialog.
            await context.SendActivityAsync($"Getting policy renewal date for {greetingState.Mobile} - {greetingState.BirthYear} from CRM.. Please wait...");

            var authBodyValues = new Dictionary <string, string>
            {
                { "tenancyName", "sathish-paripoorna" }, { "usernameOrEmailAddress", "*****@*****.**" }, { "password", "Psss@2018" },
            };

            var authResult         = string.Empty;
            var startJobResult     = string.Empty;
            var renewalResultValue = string.Empty;
            var jobCreatedID       = string.Empty;

            int[] robitIDs = new int[1];
            robitIDs[0] = 74213;

            int     timeoutSec           = 90;
            string  contentType          = "application/json";
            var     authKeyValue         = string.Empty;
            dynamic startJobResultValues = null;
            string  polRenewalDate       = string.Empty;

            using (var authHttpClient = new HttpClient())
            {
                authHttpClient.BaseAddress = new Uri("https://platform.uipath.com");
                authHttpClient.Timeout     = new TimeSpan(0, 0, timeoutSec);
                authHttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));
                var authJson = JsonConvert.SerializeObject(authBodyValues);

                using (var stringContent = new StringContent(authJson, Encoding.UTF8, "application/json"))
                {
                    var authResponse = authHttpClient.PostAsync("api/account/authenticate", stringContent).Result;
                    if (authResponse.IsSuccessStatusCode)
                    {
                        authResult = authResponse.Content.ReadAsStringAsync().Result;
                        dynamic authResultValues = JsonConvert.DeserializeObject(authResult);
                        authKeyValue = authResultValues.result;

                        if (authKeyValue != string.Empty)
                        {
                            object startJobArguments = new
                            {
                                in_cust_id = greetingState.Mobile,
                            };

                            object startJobBody = new
                            {
                                ReleaseKey     = "30a75006-fd84-42e0-87ad-0ce347018683",
                                RobotIds       = robitIDs,
                                JobsCount      = 0,
                                Strategy       = "Specific",
                                InputArguments = "{in_cust_id:" + greetingState.Mobile + "}",
                            };

                            object startJobWrapper = new
                            {
                                startInfo = startJobBody,
                            };

                            using (var startJobHttpClient = new HttpClient())
                            {
                                startJobHttpClient.BaseAddress = new Uri("https://platform.uipath.com");
                                startJobHttpClient.Timeout     = new TimeSpan(0, 0, timeoutSec);
                                startJobHttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));
                                startJobHttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authKeyValue);

                                var startJobJson = JsonConvert.SerializeObject(startJobWrapper);

                                using (var startJobContent = new StringContent(startJobJson, Encoding.UTF8, "application/json"))
                                {
                                    var startJobResponse = startJobHttpClient.PostAsync("/odata/Jobs/UiPath.Server.Configuration.OData.StartJobs", startJobContent).Result;
                                    Thread.Sleep(20000);
                                    if (startJobResponse.IsSuccessStatusCode)
                                    {
                                        startJobResult       = startJobResponse.Content.ReadAsStringAsync().Result;
                                        startJobResultValues = JsonConvert.DeserializeObject(startJobResult);
                                        jobCreatedID         = startJobResultValues.value[0].Id;
                                        if (jobCreatedID != null)
                                        {
                                            using (var getJobHttpClient = new HttpClient())
                                            {
                                                polRenewalDate = await GetRenewalJobStatusResult(getJobHttpClient, greetingState.Mobile, authKeyValue).ConfigureAwait(false);

                                                Thread.Sleep(3000);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            await context.SendActivityAsync($"You renewal date for policy no `{polRenewalDate}`");

            return(await stepContext.EndDialogAsync());
        }
Пример #57
0
 public abstract void AppendTo(StringContent/*!*/ content, int start, int count);
Пример #58
0
        public static dynamic GetActivityLevelLogsCore(Logging logging)
        {
            string AppInsightsWorkspaceId = System.Environment.GetEnvironmentVariable("AppInsightsWorkspaceId");

            using var client = new HttpClient();
            string token = Shared.Azure.AzureSDK.GetAzureRestApiToken("https://api.applicationinsights.io");

            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            TaskMetaDataDatabase TMD = new TaskMetaDataDatabase();

            using SqlConnection _conRead = TMD.GetSqlConnection();

            //Get Last Request Date
            var MaxTimesGen = _conRead.QueryWithRetry(@"
                                    select max([timestamp]) maxtimestamp from ActivityLevelLogs");

            DateTimeOffset MaxLogTimeGenerated = DateTimeOffset.UtcNow.AddDays(-30);

            foreach (var datafactory in MaxTimesGen)
            {
                if (datafactory.maxtimestamp != null)
                {
                    MaxLogTimeGenerated = ((DateTimeOffset)datafactory.maxtimestamp).AddMinutes(-5);
                }

                //string workspaceId = datafactory.LogAnalyticsWorkspaceId.ToString();

                Dictionary <string, object> KqlParams = new Dictionary <string, object>
                {
                    { "MaxLogTimeGenerated", MaxLogTimeGenerated.ToString("yyyy-MM-dd HH:mm:ss.ff K") }
                    //{"SubscriptionId", ((string)datafactory.SubscriptionUid.ToString()).ToUpper()},
                    //{"ResourceGroupName", ((string)datafactory.ResourceGroup.ToString()).ToUpper() },
                    //{"DataFactoryName", ((string)datafactory.Name.ToString()).ToUpper() },
                    //{"DatafactoryId", datafactory.Id.ToString()  }
                };

                string KQL = System.IO.File.ReadAllText(Shared.GlobalConfigs.GetStringConfig("KQLTemplateLocation") + "GetActivityLevelLogs.kql");
                KQL = KQL.FormatWith(KqlParams, FormatWith.MissingKeyBehaviour.ThrowException, null, '{', '}');

                JObject JsonContent = new JObject();
                JsonContent["query"] = KQL;

                var postContent = new StringContent(JsonContent.ToString(), System.Text.Encoding.UTF8, "application/json");

                var response = client.PostAsync($"https://api.applicationinsights.io/v1/apps/{AppInsightsWorkspaceId}/query", postContent).Result;
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    //Start to parse the response content
                    HttpContent responseContent = response.Content;
                    var         content         = response.Content.ReadAsStringAsync().Result;
                    var         tables          = ((JArray)(JObject.Parse(content)["tables"]));
                    if (tables.Count > 0)
                    {
                        DataTable dt = new DataTable();

                        var rows    = (JArray)(tables[0]["rows"]);
                        var columns = (JArray)(tables[0]["columns"]);
                        foreach (JObject c in columns)
                        {
                            DataColumn dc = new DataColumn();
                            dc.ColumnName = c["name"].ToString();
                            dc.DataType   = KustoDataTypeMapper[c["type"].ToString()];
                            dt.Columns.Add(dc);
                        }


                        foreach (JArray r in rows)
                        {
                            DataRow dr = dt.NewRow();
                            for (int i = 0; i < columns.Count; i++)
                            {
                                if (((Newtonsoft.Json.Linq.JValue)r[i]).Value != null)
                                {
                                    dr[i] = ((Newtonsoft.Json.Linq.JValue)r[i]).Value;
                                }
                                else
                                {
                                    dr[i] = DBNull.Value;
                                }
                            }
                            dt.Rows.Add(dr);
                        }

                        Table t = new Table();
                        t.Schema = "dbo";
                        string TableGuid = Guid.NewGuid().ToString();
                        t.Name = "#ActivityLevelLogs{TableGuid}";
                        using (SqlConnection _conWrite = TMD.GetSqlConnection())
                        {
                            TMD.BulkInsert(dt, t, true, _conWrite);
                            Dictionary <string, string> SqlParams = new Dictionary <string, string>
                            {
                                { "TempTable", t.QuotedSchemaAndName() },
                                { "DatafactoryId", "1" }
                            };

                            string MergeSQL = GenerateSQLStatementTemplates.GetSQL(Shared.GlobalConfigs.GetStringConfig("SQLTemplateLocation"), "MergeIntoActivityLevelLogs", SqlParams);
                            logging.LogInformation(MergeSQL.ToString());
                            _conWrite.ExecuteWithRetry(MergeSQL);
                            _conWrite.Close();
                            _conWrite.Dispose();
                        }
                    }

                    else
                    {
                        logging.LogErrors(new Exception("Kusto query failed getting ADFPipeline Stats."));
                    }
                }
            }

            return(new { });
        }
Пример #59
0
        public static async Task SyncLogicAppJson(string requestId, TraceListener tracer)
        {
            _tracer = tracer;

            var logicAppUrl = LogicAppUrl;

            if (string.IsNullOrEmpty(logicAppUrl))
            {
                return;
            }

            var fileInfo = new FileInfo(LogicAppJsonFilePath);

            if (!fileInfo.Exists)
            {
                Trace(TraceEventType.Verbose, "File {0} does not exists", fileInfo.FullName);
                return;
            }

            var displayUrl = logicAppUrl;
            var queryIndex = logicAppUrl.IndexOf('?');

            if (queryIndex > 0)
            {
                // for display/logging, strip out querystring secret
                displayUrl = logicAppUrl.Substring(0, queryIndex);
            }

            var       content    = File.ReadAllText(fileInfo.FullName);
            var       statusCode = default(HttpStatusCode);
            Exception exception  = null;

            try
            {
                Trace(TraceEventType.Verbose, "Begin HttpPut {0}, x-ms-client-request-id: {1}", displayUrl, requestId);

                using (var client = HttpClientFactory())
                {
                    client.DefaultRequestHeaders.UserAgent.Add(_userAgent.Value);
                    client.DefaultRequestHeaders.Add(Constants.ClientRequestIdHeader, requestId);

                    var payload = new StringContent(content ?? string.Empty, Encoding.UTF8, "application/json");
                    using (var response = await client.PutAsync(logicAppUrl, payload))
                    {
                        statusCode = response.StatusCode;
                        response.EnsureSuccessStatusCode();
                    }
                }
            }
            catch (Exception ex)
            {
                exception = ex;
                throw;
            }
            finally
            {
                Trace(TraceEventType.Verbose, "End HttpPut, status: {0}", statusCode);

                Trace(TraceEventType.Information,
                      "Syncing logicapp {0} with payload size {1} bytes {2}",
                      displayUrl,
                      content.Length,
                      exception == null ? "successful." : ("failed with " + exception));
            }
        }
Пример #60
0
        public async Task <IActionResult> Qiang(MoKaiQiang qiang)
        {
            #region 基础验证
            if (qiang == null || qiang.ShopId <= 0)
            {
                return(RedirectToAction("Error", new { msg = "操作太快,请稍后重试。" }));
            }

            if (!Request.Cookies.TryGetValue(EnumHelper.EmDataKey.SessionKey.ToString(), out string token))
            {
                return(RedirectToAction("Error", new { msg = "请先去登录。" }));
            }
            var sessionData = await _redis.Get <MoUserInfo>(token);

            if (sessionData == null || sessionData.UserId <= 0)
            {
                return(RedirectToAction("Error", new { msg = "请先去登录!" }));
            }

            var shop = await _redis.GetHashField <MoShopping>(EnumHelper.EmDataKey.ShoppingHash.ToString(), qiang.ShopId.ToString());

            if (shop == null)
            {
                return(NotFound());
            }
            else if (shop.MaxNum <= 0)
            {
                return(RedirectToAction("Error", new { msg = $"你太慢了,商品:{shop.Name},已经被抢完了!" }));
            }
            else if (shop.MaxNum < qiang.Num)
            {
                return(RedirectToAction("Error", new { msg = $"库存不足,商品:{shop.Name},只剩{shop.MaxNum}了!" }));
            }
            else if (shop.MaxGouNum < qiang.Num)
            {
                return(RedirectToAction("Error", new { msg = $"一个账号每次最多只能抢购【{shop.Name}】{shop.MaxGouNum}件。" }));
            }

            #endregion

            #region 请求抢购商品的分布式接口
            var rq = new MoQiangGouRq();
            rq.Num        = qiang.Num;
            rq.ShoppingId = qiang.ShopId;
            rq.MemberRq   = new MoMemberRq
            {
                Ip       = HttpContext.Connection.RemoteIpAddress.ToString(), //用户Ip
                RqSource = (int)EnumHelper.EmRqSource.Web,
                Token    = token
            };
            var strRq   = JsonConvert.SerializeObject(rq);
            var content = new StringContent(strRq, System.Text.Encoding.UTF8, "application/json");

            //基础接口地址
            string apiBaseUrl  = ConfigData.ApiUrl; //$"http://{HttpContext.Connection.LocalIpAddress}:4545";
            var    qiangApiUrl = $"{apiBaseUrl}/api/order/SubmitQiangGouOrder";
            var    strRp       = await HttpTool.HttpPostAsync(qiangApiUrl, content, 30);

            if (string.IsNullOrWhiteSpace(strRp))
            {
                return(RedirectToAction("Error", new { msg = $"抢单超时,请查看你的订单列表是否抢单成功。" }));
            }
            var rp = JsonConvert.DeserializeObject <MoQiangGouRp>(strRp);
            if (rp == null)
            {
                return(RedirectToAction("Error", new { msg = $"抢单超时,请查看你的订单列表是否抢单成功。" }));
            }
            else if (rp.RpStatus != 1)
            {
                return(Error(rp.RpMsg));
            }
            #endregion

            return(RedirectToAction("QiangResult", new { id = rp.OrderId }));
        }