示例#1
0
        public ActionResult Create(DriverViewModel driverViewModel)
        {
            try
            {
                if (Request.Files.Count > 0)
                {
                    HttpPostedFileBase[] httpPostedFileBase = new HttpPostedFileBase[8];
                    if (driverViewModel.PassportBackFile != null)
                    {
                        httpPostedFileBase[0] = driverViewModel.PassportBackFile;
                    }
                    if (driverViewModel.DriverImageUrlFile != null)
                    {
                        httpPostedFileBase[1] = driverViewModel.DriverImageUrlFile;
                    }
                    if (driverViewModel.DrivingLicenseBackFile != null)
                    {
                        httpPostedFileBase[2] = driverViewModel.DrivingLicenseBackFile;
                    }
                    if (driverViewModel.DrivingLicenseBackFile != null)
                    {
                        httpPostedFileBase[3] = driverViewModel.DrivingLicenseFrontFile;
                    }
                    if (driverViewModel.IDUAECopyBackFile != null)
                    {
                        httpPostedFileBase[4] = driverViewModel.IDUAECopyBackFile;
                    }
                    if (driverViewModel.IDUAECopyFrontFile != null)
                    {
                        httpPostedFileBase[5] = driverViewModel.IDUAECopyFrontFile;
                    }
                    if (driverViewModel.VisaCopyFile != null)
                    {
                        httpPostedFileBase[6] = driverViewModel.VisaCopyFile;
                    }
                    if (driverViewModel.PassportCopyFile != null)
                    {
                        httpPostedFileBase[7] = driverViewModel.PassportCopyFile;
                    }

                    var file = driverViewModel.PassportBackFile;

                    using (HttpClient client = new HttpClient())
                    {
                        using (var content = new MultipartFormDataContent())
                        {
                            if (httpPostedFileBase.ToList().Count > 0)
                            {
                                for (int i = 0; i < 8; i++)
                                {
                                    if (httpPostedFileBase[i] != null)
                                    {
                                        file = httpPostedFileBase[i];

                                        byte[] fileBytes = new byte[file.InputStream.Length + 1];
                                        file.InputStream.Read(fileBytes, 0, fileBytes.Length);
                                        var fileContent = new ByteArrayContent(fileBytes);

                                        if (i == 0)
                                        {
                                            fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("PassportBack")
                                            {
                                                FileName = file.FileName
                                            };
                                        }
                                        else if (i == 1)
                                        {
                                            fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("DriverImageUrl")
                                            {
                                                FileName = file.FileName
                                            };
                                        }
                                        else if (i == 2)
                                        {
                                            fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("DrivingLicenseBack")
                                            {
                                                FileName = file.FileName
                                            };
                                        }
                                        else if (i == 3)
                                        {
                                            fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("DrivingLicenseFront")
                                            {
                                                FileName = file.FileName
                                            };
                                        }
                                        else if (i == 4)
                                        {
                                            fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("IDUAECopyBack")
                                            {
                                                FileName = file.FileName
                                            };
                                        }
                                        else if (i == 5)
                                        {
                                            fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("IDUAECopyFront")
                                            {
                                                FileName = file.FileName
                                            };
                                        }
                                        else if (i == 6)
                                        {
                                            fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("VisaCopy")
                                            {
                                                FileName = file.FileName
                                            };
                                        }
                                        else if (i == 7)
                                        {
                                            fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("PassportCopy")
                                            {
                                                FileName = file.FileName
                                            };
                                        }
                                        content.Add(fileContent);
                                    }
                                }
                            }

                            string UserId = Session["UserId"].ToString();
                            content.Add(new StringContent(UserId), "CreatedBy");
                            CompanyId = Convert.ToInt32(Session["CompanyId"]);
                            content.Add(new StringContent(CompanyId.ToString()), "CompanyId");
                            content.Add(new StringContent(driverViewModel.Name == null ? "" : driverViewModel.Name), "FullName");
                            content.Add(new StringContent(driverViewModel.Contact == null ? "" : driverViewModel.Contact), "Contact");
                            content.Add(new StringContent(driverViewModel.Email == null ? "" : driverViewModel.Email), "Email");
                            content.Add(new StringContent(driverViewModel.Facebook == null ? "" : driverViewModel.Facebook), "Facebook");
                            content.Add(new StringContent("ClientDocs"), "ClientDocs");

                            if (driverViewModel.LicienceList.ToList().Count == 1)
                            {
                                content.Add(new StringContent("[" + driverViewModel.LicienceList[0].ToString() + "]"), "LicenseTypes");
                            }
                            else if (driverViewModel.LicienceList.ToList().Count == 2)
                            {
                                content.Add(new StringContent("[" + driverViewModel.LicienceList[0].ToString() + "," + driverViewModel.LicienceList[1].ToString() + "]"), "LicenseTypes");
                            }
                            else
                            {
                                content.Add(new StringContent("[" + driverViewModel.LicienceList[0].ToString() + "," + driverViewModel.LicienceList[1].ToString() + "," + driverViewModel.LicienceList[2].ToString() + "]"), "LicenseTypes");
                            }
                            content.Add(new StringContent(driverViewModel.LicenseExpiry == null ? "" : driverViewModel.LicenseExpiry), "DrivingLicenseExpiryDate");
                            content.Add(new StringContent(driverViewModel.Nationality == null ? "" : driverViewModel.Nationality), "Nationality");
                            content.Add(new StringContent(driverViewModel.Comments == null ? "" : driverViewModel.Comments), "Comments");

                            var result = webServices.PostMultiPart(content, "Driver/Add", true);
                            if (result.StatusCode == System.Net.HttpStatusCode.Accepted)
                            {
                                return(Redirect(nameof(Index)));
                            }
                        }
                    }
                }
                return(RedirectToAction(nameof(Details), new { Id = driverViewModel.Id }));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#2
0
        // MULTIPART
        // This method is accessed via a custom descriptor so it must not be an auto block
        public static async Task HttpRequestMultipart(BotData data, MultipartHttpRequestOptions options)
        {
            var clientOptions = GetClientOptions(data, options);

            using var client = HttpFactory.GetRLHttpClient(data.UseProxy ? data.Proxy : null, clientOptions);

            foreach (var cookie in options.CustomCookies)
            {
                data.COOKIES[cookie.Key] = cookie.Value;
            }

            if (string.IsNullOrWhiteSpace(options.Boundary))
            {
                options.Boundary = GenerateMultipartBoundary();
            }

            // Rewrite the value of the Content-Type header otherwise it will add double quotes around it like
            // Content-Type: multipart/form-data; boundary="------WebKitFormBoundaryewozmkbxwbblilpm"
            var multipartContent = new MultipartFormDataContent(options.Boundary);

            multipartContent.Headers.ContentType.Parameters.First(o => o.Name == "boundary").Value = options.Boundary;

            FileStream fileStream = null;

            foreach (var c in options.Contents)
            {
                switch (c)
                {
                case StringHttpContent x:
                    multipartContent.Add(new StringContent(x.Data, Encoding.UTF8, x.ContentType), x.Name);
                    break;

                case RawHttpContent x:
                    var byteContent = new ByteArrayContent(x.Data);
                    byteContent.Headers.ContentType = new MediaTypeHeaderValue(x.ContentType);
                    multipartContent.Add(byteContent, x.Name);
                    break;

                case FileHttpContent x:
                    lock (FileLocker.GetHandle(x.FileName))
                    {
                        if (data.Providers.Security.RestrictBlocksToCWD)
                        {
                            FileUtils.ThrowIfNotInCWD(x.FileName);
                        }

                        fileStream = new FileStream(x.FileName, FileMode.Open);
                        var fileContent = CreateFileContent(fileStream, x.Name, Path.GetFileName(x.FileName), x.ContentType);
                        multipartContent.Add(fileContent, x.Name);
                    }
                    break;
                }
            }

            using var request = new HttpRequest
                  {
                      Method  = new System.Net.Http.HttpMethod(options.Method.ToString()),
                      Uri     = new Uri(options.Url),
                      Version = Version.Parse(options.HttpVersion),
                      Headers = options.CustomHeaders,
                      Cookies = data.COOKIES,
                      AbsoluteUriInFirstLine = options.AbsoluteUriInFirstLine,
                      Content = multipartContent
                  };

            data.Logger.LogHeader();

            try
            {
                Activity.Current = null;
                var timeoutCts = new CancellationTokenSource(options.TimeoutMilliseconds);
                var linkedCts  = CancellationTokenSource.CreateLinkedTokenSource(data.CancellationToken, timeoutCts.Token);
                using var response = await client.SendAsync(request, linkedCts.Token);

                LogHttpRequestData(data, client);
                await LogHttpResponseData(data, response, request);
            }
            catch
            {
                LogHttpRequestData(data, request, options.Boundary, options.Contents);
                throw;
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Dispose();
                }

                request.Dispose();
                client.Dispose();
            }
        }
    static async Task UploadToS3Worker(FileInfo Info, string Region, string KeyId, string AccessKey, string BucketName, string FolderName)
    {
        // --------------------------------------------------
        // "AWS Signature Version 4"
        // http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html
        // --------------------------------------------------
        Log(" Uploading " + Info.Name);

        // --------------------------------------------------
        // http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html
        string TimeStamp  = DateTime.UtcNow.ToString("yyyyMMddTHHmmssZ");
        string DateExpire = DateTime.UtcNow.AddDays(1).ToString("yyyy-MM-dd");
        string AWSDate    = DateTime.UtcNow.AddDays(1).ToString("yyyyMMdd");
        string MimeType   = (MimeTypeMapping.ContainsKey(Info.Extension))
                                                        ? MimeTypeMapping[Info.Extension]
                                                        : "application/octet-stream";
        string MimePath      = MimeType.Split('/')[0];
        string AWSCredential = KeyId + "/" + AWSDate + "/" + Region + "/s3/aws4_request";

        // --------------------------------------------------
        string policy = "{ \"expiration\": \"" + DateExpire + "T12:00:00.000Z\"," +
                        " \"conditions\": [" +
                        " { \"bucket\": \"" + BucketName + "\" }," +
                        " [ \"starts-with\", \"$key\", \"" + FolderName + "/\" ]," +
                        " { \"acl\": \"public-read\" }," +
                        " [ \"starts-with\", \"$content-type\", \"" + MimePath + "/\" ],";

        if (Info.Extension.EndsWith("gz"))
        {
            policy += " [ \"starts-with\", \"$content-encoding\", \"gzip\" ],";
        }
        policy += " { \"x-amz-credential\": \"" + AWSCredential + "\" }," +
                  " { \"x-amz-algorithm\": \"AWS4-HMAC-SHA256\" }," +
                  " { \"x-amz-date\": \"" + TimeStamp + "\" }" +
                  " ]" +
                  "}";
        string policyBase64 = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(policy), Base64FormattingOptions.InsertLineBreaks);

        // --------------------------------------------------
        // http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html
        var kha = KeyedHashAlgorithm.Create("HmacSHA256");

        kha.Key = Encoding.UTF8.GetBytes(("AWS4" + AccessKey).ToCharArray()); // kSecret
        byte[] sig = kha.ComputeHash(Encoding.UTF8.GetBytes(AWSDate));
        kha.Key = sig;                                                        // kDate

        sig     = kha.ComputeHash(Encoding.UTF8.GetBytes(Region));
        kha.Key = sig;         // kRegion

        sig     = kha.ComputeHash(Encoding.UTF8.GetBytes("s3"));
        kha.Key = sig;         // kService

        sig     = kha.ComputeHash(Encoding.UTF8.GetBytes("aws4_request"));
        kha.Key = sig;         // kSigning

        sig = kha.ComputeHash(Encoding.UTF8.GetBytes(policyBase64));
        string signature = BitConverter.ToString(sig).Replace("-", "").ToLower();         // for Authorization

        // debugging...
        //Console.WriteLine("policy: [" + policy + "]");
        //Console.WriteLine("policyBase64: [" + policyBase64 + "]");
        //Console.WriteLine("signature: [" + signature + "]");

        // --------------------------------------------------
        HttpClient httpClient = new HttpClient();
        var        formData   = new MultipartFormDataContent();

        formData.Add(new StringContent(FolderName + "/" + Info.Name), "key");
        formData.Add(new StringContent("public-read"), "acl");
        formData.Add(new StringContent(AWSCredential), "X-Amz-Credential");
        formData.Add(new StringContent("AWS4-HMAC-SHA256"), "X-Amz-Algorithm");
        formData.Add(new StringContent(signature), "X-Amz-Signature");
        formData.Add(new StringContent(TimeStamp), "X-Amz-Date");
        formData.Add(new StringContent(policyBase64), "Policy");
        formData.Add(new StringContent(MimeType), "Content-Type");
        if (Info.Extension.EndsWith("gz"))
        {
            formData.Add(new StringContent("gzip"), "Content-Encoding");
        }
        // debugging...
        //Console.WriteLine("key: [" + FolderName + "/" + Info.Name + "]");
        //Console.WriteLine("AWSCredential: [" + AWSCredential + "]");
        //Console.WriteLine("TimeStamp: [" + TimeStamp + "]");
        //Console.WriteLine("MimeType: [" + MimeType + "]");

        // the file ----------------------------------------
        var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(Info.FullName));

        fileContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(MimeType);
        formData.Add(fileContent, "file", Info.Name);
        int adjustTimeout = (int)(Info.Length / (100 * 1000));        // [seconds] give 10 secs for each ~MB ( (10s * 1000ms) / ( 1024KB * 1024MB * 1000ms ) )

        if (adjustTimeout > 100)                                      // default timeout is 100 sec
        {
            httpClient.Timeout = TimeSpan.FromSeconds(adjustTimeout); // increase timeout
        }
        //Console.WriteLine("httpClient Timeout: [" + httpClient.Timeout + "]" );

        // upload ----------------------------------------
        string URL      = "https://" + BucketName + ".s3.amazonaws.com/";
        var    response = await httpClient.PostAsync(URL, formData);

        if (response.IsSuccessStatusCode)
        {
            Log("Upload done: " + Info.Name);
        }
        else
        {
            var contents = response.Content.ReadAsStringAsync();
            var reason   = Regex.Replace(
/* grab inner block */ Regex.Replace(contents.Result, "<[^>]+>\n<[^>]+>([^<]+)</[^>]+>", "$1")
/* strip tags */, "<([^>]+)>([^<]+)</[^>]+>", "$1 - $2\n");

            //Console.WriteLine("Fail to Upload: " + Info.Name + " Header - " + response.ToString());
            Console.WriteLine("Fail to Upload: " + Info.Name + "\nResponse - " + reason);
            throw new Exception("FAILED TO UPLOAD: " + Info.Name);
        }
    }
示例#4
0
        public async Task <string> ValidarFormatoINE(byte[] ByteArray)
        {
            var client = new HttpClient();

            // Solicitar encabezados: reemplace esta clave de ejemplo con su clave de suscripción válida.
            client.DefaultRequestHeaders.Add("Prediction-Key", "559018cc3d434cef8095da2e8b8dd30c");

            // URL de predicción: reemplace esta URL de ejemplo con su URL de predicción válida.
            string url = "https://southcentralus.api.cognitive.microsoft.com/customvision/v1.1/Prediction/d05cabb8-3952-4334-9b40-a8afc191ce61/image?iterationId=b8221738-c389-4e06-9151-b91c7dec8a5d";

            HttpResponseMessage response;

            // cuerpo de solicitud Pruebe esta muestra con una imagen almacenada localmente.
            // byte[] byteData = GetImageAsByteArray(imageFilePath);

            using (var content = new ByteArrayContent(ByteArray))
            {
                content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                response = await client.PostAsync(url, content);

                Consulta model = null;

                var respuesta = response.Content.ReadAsStringAsync();

                respuesta.Wait();


                model = (Consulta)JsonConvert.DeserializeObject(respuesta.Result.ToString(), new Consulta().GetType());


                string Descripcion1 = (from cust in model.Predictions
                                       where cust.Tag == "scaner"
                                       select cust.Probability.ToString()).FirstOrDefault();

                string NumeroCadena = Descripcion1.Remove(4, 8);

                string Descripcion2 = (from cust in model.Predictions
                                       where cust.Tag == "scaner"
                                       select cust.Probability.ToString()).FirstOrDefault();
                string NumeroCadena2 = Descripcion1.Remove(4, 8);


                double NumeroSuma1 = Convert.ToDouble(NumeroCadena);

                double NumeroSuma2 = Convert.ToDouble(NumeroCadena2);


                double resultado = NumeroSuma1 + NumeroSuma2;


                string aprobada  = "true";
                string rechazada = "false";

                string evaluacion = "";


                if (resultado >= 60)
                {
                    evaluacion = aprobada;
                }

                else
                {
                    evaluacion = rechazada;
                }

                return(evaluacion);
            }
        }
示例#5
0
文件: Auto.cs 项目: tomeelog/wapic
        // Optional: here you can check for content-type for ex 'image/png' or other..
        public override async Task <ValidateResult> ValidateAsync <T>(IField <T> field, T state)
        {
            var result = await base.ValidateAsync(field, state);

            if (result.IsValid)
            {
                var isValidForMe = this.Attachment.ContentType.ToLowerInvariant().Contains("image/png");

                if (!isValidForMe)
                {
                    result.IsValid  = false;
                    result.Feedback = $"Hey, dude! Provide a proper 'image/png' attachment, not any file on your computer like '{this.Attachment.Name}'!";
                }
                else
                {
                    var url = this.Attachment.ContentUrl;

                    HttpClient httpClient = new HttpClient();
                    Stream     filestrem  = await httpClient.GetStreamAsync(url);

                    httpClient.Dispose();

                    byte[] ImageAsByteArray = null;

                    using (MemoryStream ms = new MemoryStream())
                    {
                        int count = 0;
                        do
                        {
                            byte[] buf = new byte[1024];
                            count = filestrem.Read(buf, 0, 1024);
                            ms.Write(buf, 0, count);
                        } while (filestrem.CanRead && count > 0);
                        ImageAsByteArray = ms.ToArray();
                    }

                    HttpClient client = new HttpClient();

                    // Request headers.
                    client.DefaultRequestHeaders.Add(
                        "Ocp-Apim-Subscription-Key", "fcb7a03c796c40a3954a249c9b87d79c");

                    // Request parameters. A third optional parameter is "details".
                    string requestParameters =
                        "visualFeatures=Categories,Description,Color";

                    // Assemble the URI for the REST API Call.
                    string uri = "https://southcentralus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + requestParameters;

                    HttpResponseMessage response;


                    using (ByteArrayContent content = new ByteArrayContent(ImageAsByteArray))
                    {
                        // This example uses content type "application/octet-stream".
                        // The other content types you can use are "application/json"
                        // and "multipart/form-data".
                        content.Headers.ContentType =
                            new MediaTypeHeaderValue("application/octet-stream");

                        // Make the REST API call.
                        response = await client.PostAsync(uri, content);
                    }

                    // Get the JSON response.
                    string contentString = await response.Content.ReadAsStringAsync();

                    Console.WriteLine(contentString);
                    var rs = Newtonsoft.Json.Linq.JToken.Parse(contentString);

                    if (rs.HasValues)
                    {
                        string val = ((Newtonsoft.Json.Linq.JValue)((Newtonsoft.Json.Linq.JProperty)((Newtonsoft.Json.Linq.JContainer)((Newtonsoft.Json.Linq.JContainer)((Newtonsoft.Json.Linq.JContainer)((Newtonsoft.Json.Linq.JContainer)rs).First).First).First).First).Value).Value.ToString();

                        Result rsult = JsonConvert.DeserializeObject <Result>(contentString);

                        var    f = rsult.description;
                        string r = f.captions[0].text.ToString();
                        Console.WriteLine(r);
                        if (!val.Contains("car"))
                        {
                            result.IsValid  = false;
                            result.Feedback = $"I can see {r}. please upload your lovely image ";
                        }
                    }
                }
            }
            return(result);
        }
示例#6
0
        internal static MultipartFormDataContent AddPartContent(this MultipartFormDataContent baseContent, string name, string stringContent)
        {
            var content = new ByteArrayContent(Encoding.UTF8.GetBytes(stringContent));

            return(baseContent.AddPartContent(name, content));
        }
        /// <summary>
        /// Pushes the file to amazon aws.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="fileUploadResponse">The file upload response.</param>
        /// <exception cref="System.Exception"></exception>
        private void PushFileToAmazonAWS(PushFileRequest request, FileUploadResponse fileUploadResponse)
        {
            StringContent    awsaccesskeyidContent = null;
            StringContent    aclContent            = null;
            StringContent    keyContent            = null;
            StringContent    signatureContent      = null;
            StringContent    policyContent         = null;
            StringContent    contentTypeContent    = null;
            StringContent    cacheControlContent   = null;
            ByteArrayContent fileContent           = null;

            try
            {
                using (var multiPartCont = new MultipartFormDataContent())
                {
                    awsaccesskeyidContent = CreateStringContentFromNameValue(FileUploadResponseData.Properties.AWSAccessKeyId, fileUploadResponse.Data.AWSAccessKeyId);
                    aclContent            = CreateStringContentFromNameValue(FileUploadResponseData.Properties.Acl, fileUploadResponse.Data.Acl);
                    keyContent            = CreateStringContentFromNameValue(FileUploadResponseData.Properties.Key, fileUploadResponse.Data.Key);
                    signatureContent      = CreateStringContentFromNameValue(FileUploadResponseData.Properties.Signature, fileUploadResponse.Data.Signature);
                    policyContent         = CreateStringContentFromNameValue(FileUploadResponseData.Properties.Policy, fileUploadResponse.Data.Policy);
                    contentTypeContent    = CreateStringContentFromNameValue(PushbulletConstants.AmazonHeaders.ContentType, fileUploadResponse.FileType);

                    multiPartCont.Add(awsaccesskeyidContent);
                    multiPartCont.Add(aclContent);
                    multiPartCont.Add(keyContent);
                    multiPartCont.Add(signatureContent);
                    multiPartCont.Add(policyContent);
                    multiPartCont.Add(contentTypeContent);

                    using (var memoryStream = new MemoryStream()) {
                        request.FileStream.CopyTo(memoryStream);
                        fileContent = new ByteArrayContent(memoryStream.ToArray());
                    }

                    fileContent.Headers.Add(PushbulletConstants.AmazonHeaders.ContentType, PushbulletConstants.MimeTypes.OctetStream);
                    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                    {
                        Name     = string.Format("\"{0}\"", "file"),
                        FileName = string.Format("\"{0}\"", request.FileName)
                    };

                    multiPartCont.Add(fileContent);

                    using (var httpClient = new HttpClient())
                    {
                        Task <HttpResponseMessage> httpRequest  = httpClient.PostAsync(fileUploadResponse.UploadUrl, multiPartCont);
                        HttpResponseMessage        httpResponse = httpRequest.Result;

                        Task <string> xmlContentResponse = httpResponse.Content.ReadAsStringAsync();
                        if (!string.IsNullOrWhiteSpace(xmlContentResponse.Result))
                        {
                            throw new Exception(xmlContentResponse.Result);
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (awsaccesskeyidContent != null)
                {
                    awsaccesskeyidContent.Dispose();
                }
                if (aclContent != null)
                {
                    aclContent.Dispose();
                }
                if (keyContent != null)
                {
                    keyContent.Dispose();
                }
                if (signatureContent != null)
                {
                    signatureContent.Dispose();
                }
                if (policyContent != null)
                {
                    policyContent.Dispose();
                }
                if (contentTypeContent != null)
                {
                    contentTypeContent.Dispose();
                }
                if (cacheControlContent != null)
                {
                    cacheControlContent.Dispose();
                }
                if (fileContent != null)
                {
                    fileContent.Dispose();
                }
            }
        }
示例#8
0
        /// <summary>
        /// Gets the text visible in the specified image file by using
        /// the Computer Vision REST API.
        /// </summary>
        /// <param name="imageFilePath">The image file with printed text.</param>
        static async Task MakeOCRRequest(string imageFilePath, bool isUrl)
        {
            try
            {
                HttpClient client = new HttpClient();

                // Request headers.
                client.DefaultRequestHeaders.Add(
                    "Ocp-Apim-Subscription-Key", subscriptionKey);

                // Request parameters.
                // The language parameter doesn't specify a language, so the
                // method detects it automatically.
                // The detectOrientation parameter is set to true, so the method detects and
                // and corrects text orientation before detecting text.
                string requestParameters = "language=unk&detectOrientation=true";

                // Assemble the URI for the REST API method.
                string urlRequest = urlBase + "?" + requestParameters;

                HttpResponseMessage response;

                if (isUrl)
                {
                    var jsonString = JsonConvert.SerializeObject(new { url = imageFilePath });
                    var content    = new StringContent(jsonString, Encoding.UTF8, "application/json");

                    // This example uses the "application/json" content type.
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                    Console.WriteLine("\nWait a moment for the results to appear. (Remote)\n");
                    // Asynchronously call the REST API method.
                    response = await client.PostAsync(urlRequest, content);
                }
                else
                {
                    // Read the contents of the specified local image
                    // into a byte array.
                    byte[] byteData = GetImageAsByteArray(imageFilePath);

                    // Add the byte array as an octet stream to the request body.
                    using (ByteArrayContent content = new ByteArrayContent(byteData))
                    {
                        // This example uses the "application/octet-stream" content type.
                        content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

                        Console.WriteLine("\nWait a moment for the results to appear. (Local)\n");
                        // Asynchronously call the REST API method.
                        response = await client.PostAsync(urlRequest, content);
                    }
                }

                // Asynchronously get the JSON response.
                string contentString = await response.Content.ReadAsStringAsync();

                // Display the JSON response.
                Console.WriteLine("\nResponse:\n\n{0}\n",
                                  JToken.Parse(contentString).ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("\n" + e.Message);
            }
        }
示例#9
0
        private void SetRequestContent(HttpMethod RequestMethod)
        {
            List <KeyValuePair <string, string> > KeyValues = new List <KeyValuePair <string, string> >();

            if ((RequestMethod.ToString() == ApplicationAPIUtils.eRequestType.GET.ToString()))
            {
                if (eContentType == ApplicationAPIUtils.eContentType.XwwwFormUrlEncoded)
                {
                    string GetRequest = "?";
                    if (mAct.RequestKeyValues.Count() > 0)
                    {
                        for (int i = 0; i < mAct.RequestKeyValues.Count(); i++)
                        {
                            GetRequest += mAct.RequestKeyValues[i].ItemName.ToString() + "=" + mAct.RequestKeyValues[i].ValueForDriver + "&";
                        }
                    }
                    string ValuesURL = mAct.GetInputParamCalculatedValue(ActWebAPIBase.Fields.EndPointURL) + GetRequest.Substring(0, GetRequest.Length - 1);
                    Client.BaseAddress = new Uri(ValuesURL);
                }
                else
                {
                    Client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", ContentType);
                }
            }
            else
            {
                if ((eContentType != ApplicationAPIUtils.eContentType.XwwwFormUrlEncoded) && (eContentType != ApplicationAPIUtils.eContentType.FormData))
                {
                    string RequestBodyType = mAct.GetInputParamValue(ActWebAPIBase.Fields.RequestBodyTypeRadioButton);
                    if (RequestBodyType == ApplicationAPIUtils.eRequestBodyType.FreeText.ToString())
                    {
                        string RequestBodyWithDynamicParameters = mAct.GetInputParamCalculatedValue(ActWebAPIBase.Fields.RequestBody).ToString();
                        BodyString = SetDynamicValues(RequestBodyWithDynamicParameters);
                    }
                    else if (RequestBodyType == ApplicationAPIUtils.eRequestBodyType.TemplateFile.ToString())
                    {
                        BodyString = SetDynamicValues(GetStringBodyFromFile());
                    }
                }

                switch (eContentType)
                {
                case ApplicationAPIUtils.eContentType.XwwwFormUrlEncoded:
                    if (mAct.RequestKeyValues.Count() > 0)
                    {
                        KeyValues = ConstructURLEncoded((ActWebAPIRest)mAct);
                        RequestMessage.Content = new FormUrlEncodedContent(KeyValues);
                    }
                    break;

                case ApplicationAPIUtils.eContentType.FormData:
                    if (mAct.RequestKeyValues.Count() > 0)
                    {
                        MultipartFormDataContent requestContent = new MultipartFormDataContent();
                        List <KeyValuePair <string, string> > FormDataKeyValues = new List <KeyValuePair <string, string> >();
                        for (int i = 0; i < mAct.RequestKeyValues.Count(); i++)
                        {
                            if (mAct.RequestKeyValues[i].ValueType == WebAPIKeyBodyValues.eValueType.Text)
                            {
                                FormDataKeyValues.Add(new KeyValuePair <string, string>(mAct.RequestKeyValues[i].ItemName.ToString(), mAct.RequestKeyValues[i].ValueForDriver));
                                requestContent.Add(new StringContent(mAct.RequestKeyValues[i].ValueForDriver), mAct.RequestKeyValues[i].ItemName.ToString());
                            }
                            if (mAct.RequestKeyValues[i].ValueType == WebAPIKeyBodyValues.eValueType.File)
                            {
                                string     path          = mAct.RequestKeyValues[i].ValueForDriver;
                                string     FullPath      = path.Replace("~\\", mAct.SolutionFolder);
                                FileStream FileStream    = File.OpenRead(FullPath);
                                var        streamContent = new StreamContent(FileStream);
                                var        fileContent   = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
                                fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
                                requestContent.Add(fileContent, mAct.RequestKeyValues[i].ItemName.ToString(), Path.GetFileName(path));
                            }
                        }
                        RequestMessage.Content = requestContent;
                    }
                    break;

                case ApplicationAPIUtils.eContentType.XML:
                    string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
                    if (BodyString.StartsWith(_byteOrderMarkUtf8))
                    {
                        var lastIndexOfUtf8 = _byteOrderMarkUtf8.Length - 1;
                        BodyString = BodyString.Remove(0, lastIndexOfUtf8);
                    }
                    RequestMessage.Content = new StringContent(BodyString, Encoding.UTF8, ContentType);
                    break;

                default:
                    RequestMessage.Content = new StringContent(BodyString, Encoding.UTF8, ContentType);
                    break;
                }
            }
        }
示例#10
0
        public static void Run(
            [BlobTrigger("images/{name}", Connection = "AZURE_STORAGE_CONNECTION_STRING")]
            Stream imageStream,
            [Blob("thumbnails/{name}", FileAccess.Write, Connection = "AZURE_STORAGE_CONNECTION_STRING")]
            Stream thumbnailImageStream,
            [CosmosDB("imagesdb", "images", Id = "id", ConnectionStringSetting = "COSMOS_DB", CreateIfNotExists = true)]
            out dynamic document,
            string name,
            ILogger log)
        {
            log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {imageStream.Length} Bytes");
            Image <Rgba32> originalImage = Image.Load(imageStream);

            originalImage.Mutate(x => x.Resize(new ResizeOptions()
            {
                Size = new Size(200, 200),
                Mode = ResizeMode.Pad
            }));
            originalImage.SaveAsJpeg(thumbnailImageStream);

            // call computer vision api to get a description of the image
            HttpClient client = new HttpClient();

            // Request headers.
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", Environment.GetEnvironmentVariable("COMP_VISION_KEY"));

            // Request parameters. A third optional parameter is "details".
            // The Analyze Image method returns information about the following
            // visual features:
            // Categories:  categorizes image content according to a
            //              taxonomy defined in documentation.
            // Description: describes the image content with a complete
            //              sentence in supported languages.
            // Color:       determines the accent color, dominant color,
            //              and whether an image is black & white.
            string requestParameters =
                "visualFeatures=Description&language=en";

            // Assemble the URI for the REST API method.
            string uri = Environment.GetEnvironmentVariable("COMP_VISION_URL", EnvironmentVariableTarget.Process) + "?" + requestParameters;

            HttpResponseMessage response;

            // Read the contents of the image into a byte array.

            byte[] byteData = GetImageByteData(imageStream);

            // Add the byte array as an octet stream to the request body.
            using (ByteArrayContent content = new ByteArrayContent(byteData))
            {
                // This example uses the "application/octet-stream" content type.
                // The other content types you can use are "application/json"
                // and "multipart/form-data".
                content.Headers.ContentType =
                    new MediaTypeHeaderValue("application/octet-stream");

                // Asynchronously call the REST API method.
                response = client.PostAsync(uri, content).Result;
            }

            // Asynchronously get the JSON response.
            string result = response.Content.ReadAsStringAsync().Result;


            document = new
            {
                id            = name,
                imgPath       = "/images/" + name,
                thumbnailPath = "/thumbnails/" + name,
                description   = result
            };
        }
示例#11
0
        private async Task AnalizarTexto()
        {
            var          httpClient2     = new HttpClient();
            const string subscriptionKey = "11353e12efd34147a54b3914bb575f44";

            httpClient2.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
            const string endpoint2 = "https://southcentralus.api.cognitive.microsoft.com/vision/v2.0/ocr?language=es&detectOrientation=true";

            HttpResponseMessage response2;

            byte[] byteData = GetImageAsByteArray(_foto.Path);

            using (UserDialogs.Instance.Loading("Obteniendo información..."))
            {
                using (ByteArrayContent content = new ByteArrayContent(byteData))
                {
                    content.Headers.ContentType =
                        new MediaTypeHeaderValue("application/octet-stream");

                    response2 = await httpClient2.PostAsync(endpoint2, content);
                }

                if (!response2.IsSuccessStatusCode)
                {
                    UserDialogs.Instance.Toast("A ocurrido un error en ocr");
                    return;
                }

                //catch (Exception exp)
                //{
                //    await DisplayAlert("Error de conexion", exp.ToString(), "OK");
                //}

                text.Text = "";
                List <Region> regions = new List <Region>();
                List <Line>   lines   = new List <Line>();
                List <Word>   words   = new List <Word>();
                var           json2   = await response2.Content.ReadAsStringAsync();

                var str             = string.Empty;
                var nombre          = string.Empty;
                var primerApellido  = string.Empty;
                var segundoApellido = string.Empty;
                var numDNI          = string.Empty;
                var apellidos       = string.Empty;


                var textObject = JsonConvert.DeserializeObject <TextObject>(json2);

                regions = textObject.regions.ToList();

                foreach (var r in regions)
                {
                    lines.AddRange(r.lines.ToList());
                }

                foreach (var l in lines)
                {
                    words.AddRange(l.words.ToList());
                }

                foreach (var w in words)
                {
                    text.Text = $"{text.Text} {w.text}";

                    str = $"{text.Text} {w.text}";

                    if (char.IsDigit(w.text[0]) && w.text.Length == 9 && char.IsLetter(w.text[w.text.Length - 1]))
                    {
                        numDNI = w.text;
                    }
                }

                switch (tagFoto)
                {
                case "DNI 2.0":
                    //Obtener datos desde un dni 2.0
                    primerApellido  = getBetween(str, "APELLIDO", "SEGUNDO");
                    segundoApellido = getBetween(str, "SEGUNDO APELLIDO", "NOMBRE");
                    nombre          = getBetween(str, "NOMBRE", "NACIONALIDAD");

                    //Alert para datos de DNI 2.0
                    await DisplayAlert("DNI 2.0: Datos obtenidos", $"PRIMER APELLIDO: {primerApellido}\nSEGUNDO APELLIDO: {segundoApellido} \nNOMBRE: {nombre}\nDNI: {numDNI}", "Ok");

                    break;

                case "DNI 3.0":
                    //Obtener datos desde un dni 3.0
                    apellidos = getBetween(str, "APELLIDOS", "NOMBRE");
                    nombre    = getBetween(str, "NOMBRE", "SEXO");
                    //numDNI = getBetween(str, "DNI ", "");
                    //Alert para datos de DNI 3.0
                    await DisplayAlert("DNI 3.0: Datos obtenidos", $"APELLIDOS: {apellidos} \nNOMBRE: {nombre} \nDNI: {numDNI}", "Ok");

                    break;

                default:
                    await DisplayAlert("Error", "Documento no válido", "Ok");

                    break;
                }
            }
        }
示例#12
0
        public static void Run(CancellationToken token)
        {
            var randomBufferGenerator = new RandomBufferGenerator(50000);
            var scheduler             = new DefaultTaskScheduler();
            var httpClient            = new HttpClient
            {
                BaseAddress = ApiBaseAddress
            };

            Task.Run(
                () => scheduler.Interval(
                    TimeSpan.FromSeconds(1),
                    TaskCreationOptions.None,
                    async() =>
            {
                var satisfied   = httpClient.GetAsync("api/satisfying", token);
                var tolerating  = httpClient.GetAsync("api/tolerating", token);
                var frustrating = httpClient.GetAsync("api/frustrating", token);

                await Task.WhenAll(satisfied, tolerating, frustrating);
            },
                    token),
                token);

            Task.Run(
                () => scheduler.Interval(
                    TimeSpan.FromSeconds(3),
                    TaskCreationOptions.None,
                    async() =>
            {
                var randomStatusCode = httpClient.GetAsync("api/randomstatuscode", token);
                var exceptionThrower = httpClient.GetAsync("api/exceptionThrowing", token);

                await Task.WhenAll(randomStatusCode, exceptionThrower);
            },
                    token),
                token);

            Task.Run(
                () => scheduler.Interval(
                    TimeSpan.FromSeconds(3),
                    TaskCreationOptions.None,
                    async() =>
            {
                await httpClient.GetAsync("api/test", token);
            },
                    token),
                token);

            Task.Run(
                () => scheduler.Interval(
                    TimeSpan.FromSeconds(2),
                    TaskCreationOptions.None,
                    async() =>
            {
                var putBytes    = new ByteArrayContent(randomBufferGenerator.GenerateBufferFromSeed());
                var putFormData = new MultipartFormDataContent {
                    { putBytes, "put-file", "rnd-put" }
                };
                var putRequest = httpClient.PutAsync("api/file", putFormData, token);

                var postBytes    = new ByteArrayContent(randomBufferGenerator.GenerateBufferFromSeed());
                var postFormData = new MultipartFormDataContent {
                    { postBytes, "post-file", "rnd-post" }
                };
                var postRequest = httpClient.PostAsync("api/file", postFormData, token);

                await Task.WhenAll(putRequest, postRequest);
            },
                    token),
                token);
        }
示例#13
0
        public AppResult DetectFace(byte[] buffer, AppBodyFaceInfo appbody)
        {
            AppResult appResult = new AppResult();
            ApiResult apiResult = new ApiResult();

            // HTTP Client
            var client      = new HttpClient();
            var queryString = HttpUtility.ParseQueryString(string.Empty);

            // Request headers
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", faceApiKey);

            // Request parameters
            queryString["returnFaceId"]         = "true";
            queryString["returnFaceLandmarks"]  = "false";
            queryString["returnFaceAttributes"] = "age,gender,smile,glasses,headPose,facialHair";
            var uri = $"{faceApiEndpoint}/detect?" + queryString;

            // Call REST API
            var content = new ByteArrayContent(buffer);

            content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            var response = client.PostAsync(uri, content);

            response.Wait();

            apiResult.IsSuccessStatusCode = response.Result.IsSuccessStatusCode;
            if (apiResult.IsSuccessStatusCode)
            {
                var resdata = response.Result.Content.ReadAsStringAsync();
                resdata.Wait();
                apiResult.Result = resdata.Result.ToString();

                JArray  ja_result      = (JArray)JsonConvert.DeserializeObject(apiResult.Result);
                JObject faceAttributes = null;

                if (ja_result.Count > 0)
                {
                    appbody.visitor_faceId = (string)ja_result[0]["faceId"];
                    faceAttributes         = (JObject)ja_result[0]["faceAttributes"];

                    int age = (int)faceAttributes["age"];
                    appbody.age    = age.ToString();
                    appbody.gender = (string)faceAttributes["gender"];
                    double smile = (double)faceAttributes["smile"];
                    if (smile >= smileConfidence)
                    {
                        appbody.smile = "true";
                    }
                    else
                    {
                        appbody.smile = "false";
                    }
                    string glasses = (string)faceAttributes["glasses"];
                    if (glasses == "NoGlasses")
                    {
                        appbody.glasses = "false";
                    }
                    else if (glasses.Length > 0)
                    {
                        appbody.glasses = "true";
                    }
                    else
                    {
                        appbody.glasses = "false";
                    }
                    double facialHair_moustache = (double)faceAttributes["facialHair"]["moustache"];
                    double facialHair_beard     = (double)faceAttributes["facialHair"]["beard"];
                    double facialHair_sideburns = (double)faceAttributes["facialHair"]["sideburns"];
                    if (facialHair_moustache >= facialHairConfidence || facialHair_beard >= facialHairConfidence)
                    {
                        appbody.facialHair = "true";
                    }
                    else
                    {
                        appbody.facialHair = "false";
                    }
                }
                else
                {
                    appbody.age        = "";
                    appbody.gender     = "";
                    appbody.smile      = "";
                    appbody.glasses    = "";
                    appbody.facialHair = "";
                }
            }
            else
            {
                apiResult.Message = response.Result.ToString();
            }

            appResult.apiResult = apiResult;
            appResult.appBody   = appbody;

            return(appResult);
        }
示例#14
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            StateClient stateClient = activity.GetStateClient();

            userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

            botData = await stateClient.BotState.GetConversationDataAsync(activity.ChannelId, activity.Conversation.Id);

            userMessage = activity.Text;

            if (activity.Type == ActivityTypes.Message)
            {
                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                // calculate something for us to return
                //int length = (activity.Text ?? string.Empty).Length;

                if (userMessage.Length > 0)
                {
                    if (userMessage.ToLower().Contains("genesis") || userMessage.ToLower().Contains("hi") || userMessage.ToLower().Contains("hello"))
                    {
                        userData.SetProperty <bool>("isSelectCustomerOption", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                        await QuestionRegister("1. Are you wanting to join Genesis Energy?", connector, stateClient, activity);
                        await QuestionRegister("2. Are you an existing customer?", connector, stateClient, activity);
                        await QuestionRegister("3. Are you making an enquiry?", connector, stateClient, activity);

                        //await stateClient.BotState.SetPrivateConversationDataAsync(activity.ChannelId, activity.Conversation.Id, activity.From.Id, botData);

                        //await connector.Conversations.SendToConversationAsync(CustomerOptions(activity));

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }

                    if (userData.GetProperty <bool>("isSelectCustomerOption"))
                    {
                        if (userMessage.ToLower().Contains("join") || userMessage.ToLower().Equals("1"))
                        {
                            // Adding new customer
                            userData.SetProperty <bool>("isRegister", true);
                            userData.SetProperty <bool>("isFirstName", true);
                            userData.SetProperty <bool>("isSelectCustomerOption", false);

                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                            //await stateClient.BotState.SetPrivateConversationDataAsync(activity.ChannelId, activity.Conversation.Id, activity.From.Id, botData);
                        }
                        else
                        {
                            userData.SetProperty <bool>("isSelectCustomerOption", true);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                            //await stateClient.BotState.SetPrivateConversationDataAsync(activity.ChannelId, activity.Conversation.Id, activity.From.Id, botData);

                            await connector.Conversations.SendToConversationAsync(CustomerOptions(activity));

                            return(Request.CreateResponse(HttpStatusCode.OK));
                        }
                    }


                    // Adding new customer
                    if (userData.GetProperty <bool>("isRegister"))
                    {
                        //await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        if (userData.GetProperty <bool>("isFirstName"))
                        {
                            if (!String.IsNullOrEmpty(userMessage) && !String.IsNullOrWhiteSpace(userMessage))
                            {
                                await QuestionRegister("Enter your first name:", connector, stateClient, activity);

                                userData.SetProperty <bool>("isFirstName", false);
                                userData.SetProperty <bool>("isMiddleName", true);
                                await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                //await stateClient.BotState.SetPrivateConversationDataAsync(activity.ChannelId, activity.Conversation.Id, activity.From.Id, botData);

                                return(Request.CreateResponse(HttpStatusCode.OK));
                            }
                        }
                        if (userData.GetProperty <bool>("isMiddleName"))
                        {
                            if (!String.IsNullOrEmpty(userMessage) && !String.IsNullOrWhiteSpace(userMessage))
                            {
                                userData.SetProperty <string>("FirstName", userMessage);
                                await QuestionRegister("Enter your middle name:", connector, stateClient, activity);

                                userData.SetProperty <bool>("isMiddleName", false);
                                userData.SetProperty <bool>("isLastName", true);
                                await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                //await stateClient.BotState.SetPrivateConversationDataAsync(activity.ChannelId, activity.Conversation.Id, activity.From.Id, botData);
                                return(Request.CreateResponse(HttpStatusCode.OK));
                            }
                        }
                        if (userData.GetProperty <bool>("isLastName"))
                        {
                            if (!String.IsNullOrEmpty(userMessage) && !String.IsNullOrWhiteSpace(userMessage))
                            {
                                userData.SetProperty <string>("MiddleName", userMessage);
                                await QuestionRegister("Enter your last name:", connector, stateClient, activity);

                                userData.SetProperty <bool>("isLastName", false);
                                userData.SetProperty <bool>("isDoB", true);
                                await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                //await stateClient.BotState.SetPrivateConversationDataAsync(activity.ChannelId, activity.Conversation.Id, activity.From.Id, botData);
                                return(Request.CreateResponse(HttpStatusCode.OK));
                            }
                        }

                        if (userData.GetProperty <bool>("isDoB"))
                        {
                            if (!String.IsNullOrEmpty(userMessage) && !String.IsNullOrWhiteSpace(userMessage))
                            {
                                userData.SetProperty <string>("LastName", userMessage);
                                await QuestionRegister("Enter your Date of Birth with format as (mm/dd/yyyy):", connector, stateClient, activity);

                                userData.SetProperty <bool>("isDoB", false);
                                userData.SetProperty <bool>("isMobile", true);
                                await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                //await stateClient.BotState.SetPrivateConversationDataAsync(activity.ChannelId, activity.Conversation.Id, activity.From.Id, botData);
                                return(Request.CreateResponse(HttpStatusCode.OK));
                            }
                        }
                        if (userData.GetProperty <bool>("isMobile"))
                        {
                            if (!String.IsNullOrEmpty(userMessage) && !String.IsNullOrWhiteSpace(userMessage))
                            {
                                userData.SetProperty <string>("DoB", userMessage);
                                await QuestionRegister("Enter your contact Mobile number:", connector, stateClient, activity);

                                userData.SetProperty <bool>("isMobile", false);
                                userData.SetProperty <bool>("isEmail", true);
                                await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                //await stateClient.BotState.SetPrivateConversationDataAsync(activity.ChannelId, activity.Conversation.Id, activity.From.Id, botData);
                                return(Request.CreateResponse(HttpStatusCode.OK));
                            }
                        }
                        if (userData.GetProperty <bool>("isEmail"))
                        {
                            userData.SetProperty <string>("Mobile", userMessage);
                            await QuestionRegister("Enter your contact Email:", connector, stateClient, activity);

                            userData.SetProperty <bool>("isEmail", false);
                            userData.SetProperty <bool>("isPassword", true);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                            //await stateClient.BotState.SetPrivateConversationDataAsync(activity.ChannelId, activity.Conversation.Id, activity.From.Id, botData);
                            return(Request.CreateResponse(HttpStatusCode.OK));
                        }
                        if (userData.GetProperty <bool>("isPassword"))
                        {
                            userData.SetProperty <string>("Email", userMessage);
                            await QuestionRegister("Enter your Password:"******"isPassword", false);
                            userData.SetProperty <bool>("isAddress", true);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                            //await stateClient.BotState.SetPrivateConversationDataAsync(activity.ChannelId, activity.Conversation.Id, activity.From.Id, botData);
                            return(Request.CreateResponse(HttpStatusCode.OK));
                        }

                        if (userData.GetProperty <bool>("isAddress"))
                        {
                            userData.SetProperty <string>("Password", userMessage);
                            await QuestionRegister("Enter your House Address:", connector, stateClient, activity);

                            userData.SetProperty <bool>("isAddress", false);
                            userData.SetProperty <bool>("isEnd", true);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                            //await stateClient.BotState.SetPrivateConversationDataAsync(activity.ChannelId, activity.Conversation.Id, activity.From.Id, botData);
                            return(Request.CreateResponse(HttpStatusCode.OK));
                        }
                        if (userData.GetProperty <bool>("isEnd"))
                        {
                            userData.SetProperty <string>("Address", userMessage);
                            Customer customer = new Customer
                            {
                                firstName     = botData.GetProperty <string>("FirstName"),
                                middleName    = botData.GetProperty <string>("MiddleName"),
                                lastName      = botData.GetProperty <string>("LastName"),
                                dob           = botData.GetProperty <string>("DoB"),
                                mobilePhone   = botData.GetProperty <string>("Mobile"),
                                email         = botData.GetProperty <string>("Email"),
                                postalAddress = botData.GetProperty <string>("Address"),
                                password      = botData.GetProperty <string>("Password"),
                            };
                            userData.SetProperty <Customer>("CustomerDetail", customer);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                            HttpClient httpClient = new HttpClient();
                            // Customer Details
                            var    uri  = "http://52.237.219.181:8081/v1/expr/faceboobbot/customerddetails";
                            var    req  = JsonConvert.SerializeObject(customer);
                            byte[] data = Encoding.UTF8.GetBytes(req);
                            HttpResponseMessage res;
                            using (var content = new ByteArrayContent(data))
                            {
                                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                                res = await httpClient.PostAsync(uri, content);
                            }
                            string stringJson = await res.Content.ReadAsStringAsync();

                            CustomerResponse customerResponse = JsonConvert.DeserializeObject <CustomerResponse>(stringJson);

                            // Property
                            Property property = new Property
                            {
                                address          = userData.GetProperty <string>("Address"),
                                service          = "Electricity",
                                moveInDate       = DateTime.Now.ToShortDateString(),
                                primaryResidence = "Y",
                                customerId       = customerResponse.customerId
                            };
                            uri  = "http://52.237.219.181:8081/v1/expr/faceboobbot/propertydetails";
                            req  = JsonConvert.SerializeObject(property);
                            data = Encoding.UTF8.GetBytes(req);
                            using (var content = new ByteArrayContent(data))
                            {
                                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                                res = await httpClient.PostAsync(uri, content);
                            }
                            stringJson = await res.Content.ReadAsStringAsync();

                            await QuestionRegister("Thanks for your register!", connector, stateClient, activity);

                            userData.SetProperty <bool>("isEnd", false);
                            userData.SetProperty <bool>("isRegister", false);
                            userData.SetProperty <bool>("isSelectCustomerOption", true);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                            //await stateClient.BotState.SetPrivateConversationDataAsync(activity.ChannelId, activity.Conversation.Id, activity.From.Id, botData);
                            //await connector.Conversations.SendToConversationAsync(CustomerDetailConfirm(activity, userData.GetProperty<Customer>("CustomerDetail")));
                            return(Request.CreateResponse(HttpStatusCode.OK));
                        }
                    }
                }

                // return our reply to the user
                Activity reply = activity.CreateReply(botMessage);
                await connector.Conversations.ReplyToActivityAsync(reply);
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
        /// <summary>
        /// Convert document to HTML.
        ///
        /// Converts a document to HTML.
        /// </summary>
        /// <param name="file">The document to convert.</param>
        /// <param name="filename">The filename for file.</param>
        /// <param name="fileContentType">The content type of file. (optional)</param>
        /// <param name="model">The analysis model to be used by the service. For the **Element classification** and
        /// **Compare two documents** methods, the default is `contracts`. For the **Extract tables** method, the
        /// default is `tables`. These defaults apply to the standalone methods as well as to the methods' use in
        /// batch-processing requests. (optional)</param>
        /// <returns><see cref="HTMLReturn" />HTMLReturn</returns>
        public DetailedResponse <HTMLReturn> ConvertToHtml(System.IO.MemoryStream file, string filename, string fileContentType = null, string model = null)
        {
            if (file == null)
            {
                throw new ArgumentNullException("`file` is required for `ConvertToHtml`");
            }
            if (string.IsNullOrEmpty(filename))
            {
                throw new ArgumentNullException("`filename` is required for `ConvertToHtml`");
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            DetailedResponse <HTMLReturn> result = null;

            try
            {
                var formData = new MultipartFormDataContent();

                if (file != null)
                {
                    var fileContent = new ByteArrayContent(file.ToArray());
                    System.Net.Http.Headers.MediaTypeHeaderValue contentType;
                    System.Net.Http.Headers.MediaTypeHeaderValue.TryParse(fileContentType, out contentType);
                    fileContent.Headers.ContentType = contentType;
                    formData.Add(fileContent, "file", filename);
                }

                IClient client = this.Client;
                if (_tokenManager != null)
                {
                    client = this.Client.WithAuthentication(_tokenManager.GetToken());
                }

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

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");
                if (!string.IsNullOrEmpty(model))
                {
                    restRequest.WithArgument("model", model);
                }
                restRequest.WithBodyContent(formData);

                restRequest.WithHeaders(Common.GetSdkHeaders("compare-comply", "v1", "ConvertToHtml"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

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

            return(result);
        }
示例#16
0
        public ResultValue <SisImportCanvasDto> ImportEnrollments(int accountId, List <EnrollmentCanvasDto> enrollments)
        {
            var result = new ResultValue <SisImportCanvasDto>();
            var csv    = new StringBuilder();

            csv.AppendLine("course_id,user_id,role,section_id,status");
            foreach (var enrollment in enrollments)
            {
                var line = $"{enrollment.CourseId},{enrollment.UserId},{enrollment.Role}," +
                           $"{enrollment.SectionId}, {enrollment.Status}";
                csv.AppendLine(line);
            }

            var url = API_URL + accountId + "/sis_imports";

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", GlobalValues.TokenCanvas);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
                client.Timeout = new TimeSpan(0, 0, 40);
                var uri     = new Uri(GlobalValues.UrlCanvas + url);
                var request = new HttpRequestMessage(HttpMethod.Post, uri);
                var content = new MultipartFormDataContent();
                request.Headers.ExpectContinue = false;
                request.Content = content;

                byte[] toBytes     = Encoding.UTF8.GetBytes(csv.ToString());
                var    fileContent = new ByteArrayContent(toBytes);
                content.Add(new StringContent("instructure_csv"), "import_type");
                content.Add(fileContent, "\"attachment\"", "\"" + "enrollments.csv" + "\"");

                var response = client.SendAsync(request).Result;
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var returnData = response.Content.ReadAsAsync <dynamic>().Result;
                    result.Value = new SisImportCanvasDto
                    {
                        Id            = returnData["id"],
                        WorkflowState = returnData["workflow_state"],
                        Progress      = returnData["progress"]
                    };
                }
                else
                {
                    var statusCode = Convert.ToInt32(response.StatusCode);
                    var status     = response.StatusCode.ToString();
                    var exception  = request.Content.ReadAsStringAsync().Result;
                    var logEntity  = new LogDto
                    {
                        Date       = DateTime.Now,
                        Loger      = uri.ToString(),
                        Message    = "POST " + status + ":" + statusCode,
                        Exception  = exception,
                        Level      = GlobalValues.WARNING,
                        StatusCode = statusCode
                    };
                    var idLog = _logService.SaveLog(logEntity);
                    result.Errors.Add(string.Format(CanvasApiStrings.ErrorApi, idLog));
                    return(result);
                }
            }
            return(result);
        }
示例#17
0
        /// <summary>
        /// Create a classifier. Train a new multi-faceted classifier on the uploaded image data. Create your custom classifier with positive or negative examples. Include at least two sets of examples, either two positive example files or one positive and one negative file. You can upload a maximum of 256 MB per call.  Encode all names in UTF-8 if they contain non-ASCII characters (.zip and image file names, and classifier and class names). The service assumes UTF-8 encoding if it encounters non-ASCII characters.
        /// </summary>
        /// <param name="createClassifier">Object used to define options for creating a classifier.</param>
        /// <returns><see cref="Classifier" />Classifier</returns>
        public Classifier CreateClassifier(CreateClassifier createClassifier, Dictionary <string, object> customData = null)
        {
            if (createClassifier == null)
            {
                throw new ArgumentNullException(nameof(createClassifier));
            }

            if (!createClassifier.IsValid())
            {
                throw new ArgumentException("At least one positive example and one negative example is required to train a classifier.");
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            Classifier result = null;

            try
            {
                var formData = new MultipartFormDataContent();

                if (createClassifier.Name != null)
                {
                    var nameContent = new StringContent(createClassifier.Name, Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    nameContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
                    formData.Add(nameContent, "name");
                }

                if (createClassifier.PositiveExamples != null && createClassifier.PositiveExamples.Count > 0)
                {
                    foreach (KeyValuePair <string, Stream> kvp in createClassifier.PositiveExamples)
                    {
                        var classnamePositiveExamplesContent = new ByteArrayContent((kvp.Value as Stream).ReadAllBytes());
                        MediaTypeHeaderValue contentType;
                        MediaTypeHeaderValue.TryParse("application/zip", out contentType);
                        classnamePositiveExamplesContent.Headers.ContentType = contentType;
                        formData.Add(classnamePositiveExamplesContent, string.Format("{0}_positive_examples", kvp.Key), string.Format("{0}_positive_examples.zip", kvp.Key));
                    }
                }

                if (createClassifier.NegativeExamples != null)
                {
                    var negativeExamplesContent = new ByteArrayContent((createClassifier.NegativeExamples as Stream).ReadAllBytes());
                    MediaTypeHeaderValue contentType;
                    MediaTypeHeaderValue.TryParse("application/zip", out contentType);
                    negativeExamplesContent.Headers.ContentType = contentType;
                    formData.Add(negativeExamplesContent, "negative_examples", "negative_examples.zip");
                }

                result = this.Client.PostAsync($"{this.Endpoint}/v3/classifiers")
                         .WithArgument("api_key", ApiKey)
                         .WithArgument("version", VersionDate)
                         .WithBodyContent(formData)
                         .WithFormatter(new MediaTypeHeaderValue("application/octet-stream"))
                         .As <Classifier>()
                         .Result;
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
示例#18
0
        public async Task SyncDataAsync(int platformid)
        {
            initNonExistingRepo(true);
            EntiteitManager entiteitManager = new EntiteitManager(uowManager);
            //Sync willen we datum van vandaag en gisteren.
            DateTime vandaag  = DateTime.Today.Date;
            DateTime gisteren = DateTime.Today.AddDays(-30).Date;
            List <Domain.Entiteit.Persoon> AllePersonen = entiteitManager.GetAllPeople(platformid);

            //Enkele test entiteiten, puur voor debug, later vragen we deze op uit onze repository//

            /*
             * List<Domain.Entiteit.Persoon> AllePersonen = entiteitManager.GetAllPeople(0);
             *
             * /*  PostRequest postRequest1 = new PostRequest()
             * {
             * since = gisteren,
             * until = vandaag
             * };
             *
             * using (HttpClient http = new HttpClient())
             * {
             *  string uri = "https://kdg.textgain.com/query";
             *  http.DefaultRequestHeaders.Add("X-API-Key", "aEN3K6VJPEoh3sMp9ZVA73kkr");
             * // var myContent = JsonConvert.SerializeObject(postRequest1);
             *  //var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
             *  //var byteContent = new ByteArrayContent(buffer);
             *  //byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
             *  var result = await http.PostAsync(uri,null).Result.Content.ReadAsStringAsync();
             *  try
             *  {
             *      var posts = JsonConvert.DeserializeObject<List<TextGainResponse>>(result);
             *      if (posts.Count != 0)
             *      {
             *         // ConvertAndSaveToDb(posts);
             *
             *        //  System.IO.File.WriteAllText(@"C:\Users\Zeger\source\repos\Integratieproject\WebUI\Controllers\DataTextGain.json", result);
             *      }
             *  }
             *  catch (Newtonsoft.Json.JsonReaderException)
             *  {
             *
             *  }
             *
             * }*/
            //Voor elke entiteit een request maken, momenteel gebruikt het test data, later halen we al onze entiteiten op.
            foreach (var Persoon in AllePersonen)
            {
                PostRequest postRequest = new PostRequest()
                {
                    name = Persoon.Naam,
                    //since = new DateTime(2018, 04, 01),
                    //until = new DateTime(2018, 04, 30)
                    since = gisteren,
                    until = vandaag
                };



                using (HttpClient http = new HttpClient())
                {
                    string uri = "https://kdg.textgain.com/query";
                    http.DefaultRequestHeaders.Add("X-API-Key", "aEN3K6VJPEoh3sMp9ZVA73kkr");
                    var myContent   = JsonConvert.SerializeObject(postRequest);
                    var buffer      = System.Text.Encoding.UTF8.GetBytes(myContent);
                    var byteContent = new ByteArrayContent(buffer);
                    byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    var result = await http.PostAsync(uri, byteContent).Result.Content.ReadAsStringAsync();

                    try
                    {
                        var posts = JsonConvert.DeserializeObject <List <TextGainResponse> >(result);
                        if (posts.Count != 0)
                        {
                            ConvertAndSaveToDb(posts, Persoon.EntiteitId);
                            //  System.IO.File.WriteAllText(@"C:\Users\Zeger\source\repos\Integratieproject\WebUI\controllers\DataTextGain" + Persoon.EntiteitId + ".json", result);
                        }
                    }
                    catch (Newtonsoft.Json.JsonReaderException)
                    {
                    }
                }
            }
        }
        private HttpContent PreparePersonModelHttpContent(out PersonModel personModel)
        {
            personModel = new PersonModel()
            {
                FirstName = "First",
                LastName  = "Last",
                Photo     = new HttpFile("photo.png", "image/png", new byte[] { 0, 1, 2, 3, 7 }),
                Years     = new List <int>()
                {
                    2001, 2010, 2015
                },
                Roles = new List <PersonRole>
                {
                    new PersonRole()
                    {
                        RoleId = 1,
                        Rights = new List <int>()
                        {
                            1, 2, 5
                        }
                    }
                },
                IsActive         = true,
                ActivityProgress = null,
                Attachments      = new List <HttpFile>()
                {
                    new HttpFile("file1.tt", "text/plain", new byte[] { 1, 3, 5 }),
                    new HttpFile("file2.cf", "text/plain", new byte[] { 4, 2, 5 })
                }
            };

            var httpContent = new MultipartFormDataContent("testnewboundary");

            httpContent.Add(new StringContent(personModel.LastName), "LastName");
            httpContent.Add(new StringContent(personModel.FirstName), "FirstName");
            httpContent.Add(new StringContent(personModel.ActivityProgress == null ? "undefined" : personModel.ActivityProgress.ToString()), "ActivityProgress");
            httpContent.Add(new StringContent(personModel.IsActive ? "on" : "off"), "IsActive");

            foreach (var year in personModel.Years)
            {
                httpContent.Add(new StringContent(year.ToString()), "Years");
            }

            httpContent.Add(new StringContent(personModel.Roles[0].RoleId.ToString()), "Roles[0].RoleId");
            foreach (var right in personModel.Roles[0].Rights)
            {
                httpContent.Add(new StringContent(right.ToString()), "Roles[0].Rights");
            }

            var fileContent = new ByteArrayContent(personModel.Photo.Buffer);

            fileContent.Headers.ContentType        = new MediaTypeHeaderValue(personModel.Photo.MediaType);
            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = personModel.Photo.FileName,
                Name     = "Photo"
            };
            httpContent.Add(fileContent);

            for (int i = 0; i < personModel.Attachments.Count; i++)
            {
                var attachment = personModel.Attachments[i];
                var content    = new ByteArrayContent(attachment.Buffer);
                content.Headers.ContentType        = new MediaTypeHeaderValue(attachment.MediaType);
                content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = attachment.FileName,
                    Name     = "Attachments"
                };
                httpContent.Add(content);
            }

            return(httpContent);
        }
        private async Task WorkerAsync()
        {
            _timer.Stop();

            string fromMail = "";

            try
            {
                _emails = EmailService.GetAll().Where(x => !x.IsSent).OrderBy(x => x.Id).ToList();

                if (_emails.Count == 0)
                {
                    _timer.Start(); return;
                }

                foreach (var email in _emails)
                {
                    using (var client = new HttpClient())
                    {
                        client.BaseAddress = new Uri(_apiUrl);

                        using (var stream = new MemoryStream())
                            using (var bson = new BsonWriter(stream))
                            {
                                var jsonSerializer = new JsonSerializer();

                                fromMail = email.From;

                                _emailAttachments = EmailAttachmentService.GetAllNoTracking().Where(x => x.EmailId == email.Id).ToList();

                                var attachments = _emailAttachments.Select(attachment => new EMailAttachmentViewModel
                                {
                                    File     = attachment.File,
                                    FileName = attachment.FileName,
                                    EmailId  = attachment.EmailId
                                }).ToList();

                                if (email.Retry >= _retryLimitation)
                                {
                                    continue;
                                }
                                var willBeSentAgainEmail = new EMailViewModel
                                {
                                    Id               = email.Id,
                                    From             = email.From,
                                    To               = email.To,
                                    Subject          = email.Subject,
                                    Body             = email.Body,
                                    Bcc              = email.Bcc,
                                    Cc               = email.Cc,
                                    Exception        = email.Exception,
                                    Retry            = ++email.Retry,
                                    SmtpServer       = email.SmtpServer,
                                    IsRead           = false,
                                    IsSent           = false,
                                    LastTryDate      = DateTime.Now,
                                    EmailAttachments = attachments
                                };

                                jsonSerializer.Serialize(bson, willBeSentAgainEmail);

                                client.DefaultRequestHeaders.Accept.Clear();
                                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));

                                var byteArrayContent = new ByteArrayContent(stream.ToArray());
                                byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("application/bson");

                                await client?.PostAsync("api/mail/sendemailasync", byteArrayContent, _cancellationToken);
                            }
                    }
                }
                _timer.Start();
            }
            catch (Exception ex)
            {
                _timer.Start();
                #region Write Log
                string address = BaseAddress + ".MailController(IEmail emailService)";
                var    dic     = LogBusiness.GetDictionary();
                dic.Add(LogFieldName.FullyQualifiedFunctionName, address);
                var dicParams = LogBusiness.GetDictionary();
                dicParams.Add(LogFieldName.Token, dicParams);
                dic = LogBusiness.GetDictionary();
                dic.Add(LogFieldName.FullyQualifiedFunctionName, address);
                dic.Add(LogFieldName.ErrorMessage, ex.Message);
                dic.Add(LogFieldName.StackTrace, ex.StackTrace);
                LogBusiness.CustomLog(fromMail, LogEvent.ErrorEvent, dic, dicParams);
                #endregion
            }
            _timer.Start();
        }
        public override async Task <HttpTextResponse> RequestTextAsync(HttpRequestInfo requestInfo)
        {
            HttpTextResponse response = new HttpTextResponse();

            HttpClient client;

            Logger.LogInfo("Requesting " + requestInfo.Method + " url " + requestInfo.Url);

            var handler = new HttpClientHandler();

            handler.ClientCertificateOptions = ClientCertificateOption.Automatic;

            client = new HttpClient(handler);

            HttpRequestMessage httpRequest = new HttpRequestMessage(ToRequestMethod(requestInfo.Method), new Uri(requestInfo.Url));

            if (requestInfo.Method == HttpMethod.GET || requestInfo.Method == HttpMethod.DELETE)
            {
                if (requestInfo.Headers != null)
                {
                    foreach (var header in requestInfo.Headers)
                    {
                        httpRequest.Headers.Add(header.Key, header.Value);
                    }
                }
            }
            else if (requestInfo.Method == HttpMethod.POST || requestInfo.Method == HttpMethod.PUT)
            {
                var content = new ByteArrayContent((requestInfo.Body ?? string.Empty).ToBytes());

                if (requestInfo.Headers != null)
                {
                    foreach (var header in requestInfo.Headers)
                    {
                        if (header.Key == HttpHeaders.ContentType)
                        {
                            content.Headers.ContentType = new MediaTypeHeaderValue(header.Value);
                        }
                        else
                        {
                            httpRequest.Headers.Add(header.Key, header.Value);
                        }
                    }
                }

                httpRequest.Content = content;
            }

            var httpResponse = await client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead, _tokenSource.Token);

            response.StatusCode = (int)httpResponse.StatusCode;

            if (httpResponse.Headers != null)
            {
                response.Headers = new Dictionary <string, string>();

                foreach (var header in httpResponse.Headers)
                {
                    response.Headers[header.Key] = String.Join("; ", header.Value);
                }
            }

            response.Text = await httpResponse.Content.ReadAsStringAsync();

            response.IsSuccessful = httpResponse.IsSuccessStatusCode;

            LogResponse(requestInfo, response);

            return(response);
        }
        public async Task <object> Upload(AlfrescoFile file)
        {
            var client = new HttpClient();

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("X-Alfresco-Remote-User", file.User);
            var multiContent = new MultipartFormDataContent();
            var fileData     = Convert.FromBase64String(file.FileContent);
            var bytes        = new ByteArrayContent(fileData);
            //validate filename
            var prefix = "UN_";

            switch (file.Type)
            {
            case "Сертификат качества":
                prefix = "CQ_";
                break;

            case "Сертификат анализа":
                prefix = "CA_";
                break;

            case "Декларация":
                prefix = "D_";
                break;

            case "Сертификат производителя (русский язык)":
                prefix = "MC_";
                break;

            case "Регистрационное удостоверение":
                prefix = "RC_";
                break;

            case "Сертификат соответствия":
                prefix = "CC_";
                break;

            case "Протокол анализа":
                prefix = "AP_";
                break;

            case "Сертификат соответствия РОСТЕСТ":
                prefix = "CCR_";
                break;

            case "Информационное письмо":
                prefix = "IM_";
                break;

            case "Гигиенический сертификат":
                prefix = "HC_";
                break;

            case "Паспорт":
                prefix = "P_";
                break;

            case "Договор":
                prefix = "A_";
                break;

            case "Протокол разногласий":
                prefix = "DRP_";
                break;

            case "Доверенность":
                prefix = "PA_";
                break;

            case "Доп. соглашения к договору":
                prefix = "EA_";
                break;

            case "Аналитический Лист":
                prefix = "AS_";
                break;

            case "Акт о забраковке":
                prefix = "RA_";
                break;
            }
            var rnd      = new Random();
            var fileName = prefix + DateTime.Now.ToString("yyyyMMddHmm_" + rnd.Next(1, 9999)) + Path.GetExtension(file.FileName).ToLower();

            multiContent.Add(bytes, "filedata", fileName);
            multiContent.Add(new StringContent("name"), fileName);
            var result = await client.PostAsync(file.UploadUrl, multiContent);

            if (result.StatusCode != System.Net.HttpStatusCode.Created)
            {
                return(await result.Content.ReadAsStringAsync());
            }
            var response = await result.Content.ReadAsStringAsync();

            var item  = JObject.Parse(response);
            var props = new JObject
            {
                ["sc:type"]  = !string.IsNullOrEmpty(file.Type) ? file.Type : "Неизвестный",
                ["cm:title"] = file.FileName
            };

            if (!string.IsNullOrEmpty(file.Date))
            {
                var date = DateTime.ParseExact(file.Date, "dd.MM.yyyy", CultureInfo.InvariantCulture);
                props["sc:date"] = date.ToString("yyyy-MM-dd");
            }
            if (!string.IsNullOrEmpty(file.Expired))
            {
                var expired = DateTime.ParseExact(file.Expired, "dd.MM.yyyy", CultureInfo.InvariantCulture);
                props["sc:expired"] = expired.ToString("yyyy-MM-dd");
            }
            var o = new JObject
            {
                ["nodeType"]   = "sc:series",
                ["properties"] = props,
            };
            var json = o.ToString();
            var url  = file.ShareUrl + item["entry"]["id"];

            result = await client.PutAsync(url, new StringContent(json, Encoding.UTF8, "application/json"));

            return(await result.Content.ReadAsStringAsync());
        }
示例#23
0
        public static IApplicationBuilder UseTestStuff(
            this IApplicationBuilder app,
            IHostApplicationLifetime lifetime,
            bool runSampleRequestsFromApp)
        {
            app.Use(
                (context, next) =>
            {
                RandomClientIdForTesting.SetTheFakeClaimsPrincipal(context);
                return(next());
            });

            var token = lifetime.ApplicationStopping;

            if (runSampleRequestsFromApp)
            {
                var apdexSamples = new AppMetricsTaskScheduler(
                    TimeSpan.FromSeconds(ApdexSamplesInterval),
                    () =>
                {
                    var satisfiedV2WithParam = HttpClient.GetAsync("api/v2/satisfying/1", token);
                    var satisfiedV2NoParam   = HttpClient.GetAsync("api/v2/satisfying", token);
                    var satisfied            = HttpClient.GetAsync("api/satisfying", token);
                    var tolerating           = HttpClient.GetAsync("api/tolerating", token);
                    var frustrating          = HttpClient.GetAsync("api/frustrating", token);

                    return(Task.WhenAll(satisfied, satisfiedV2WithParam, satisfiedV2NoParam, tolerating, frustrating));
                });

                apdexSamples.Start();

                var randomErrorSamples = new AppMetricsTaskScheduler(
                    TimeSpan.FromSeconds(RandomSamplesInterval),
                    () =>
                {
                    var randomStatusCode = HttpClient.GetAsync("api/randomstatuscode", token);
                    var randomException  = HttpClient.GetAsync("api/randomexception", token);

                    return(Task.WhenAll(randomStatusCode, randomException));
                });

                randomErrorSamples.Start();

                var testSamples = new AppMetricsTaskScheduler(
                    TimeSpan.FromSeconds(GetEndpointSuccessInterval),
                    () =>
                {
                    var testOne = HttpClient.GetAsync("api/test", token);
                    var testTwo = HttpClient.GetAsync("api/test/params/abc/123", token);

                    return(Task.WhenAll(testOne, testTwo));
                });

                testSamples.Start();

                var slaSamples = new AppMetricsTaskScheduler(
                    TimeSpan.FromSeconds(SlaEndpointsInterval),
                    () => HttpClient.GetAsync("api/slatest/timer", token));

                slaSamples.Start();

                var randomBufferGenerator = new RandomBufferGenerator(50000);
                var postPutSamples        = new AppMetricsTaskScheduler(
                    TimeSpan.FromSeconds(PutAndPostRequestsInterval),
                    () =>
                {
                    var putBytes    = new ByteArrayContent(randomBufferGenerator.GenerateBufferFromSeed());
                    var putFormData = new MultipartFormDataContent {
                        { putBytes, "put-file", "rnd-put" }
                    };
                    var putRequest = HttpClient.PutAsync("api/file", putFormData, token);

                    var postBytes    = new ByteArrayContent(randomBufferGenerator.GenerateBufferFromSeed());
                    var postFormData = new MultipartFormDataContent {
                        { postBytes, "post-file", "rnd-post" }
                    };
                    var postRequest = HttpClient.PostAsync("api/file", postFormData, token);

                    return(Task.WhenAll(putRequest, postRequest));
                });

                postPutSamples.Start();
            }

            return(app);
        }
示例#24
0
        public async Task Http2_FlowControl_ClientDoesNotExceedWindows()
        {
            const int InitialWindowSize = 65535;
            const int ContentSize       = 100_000;

            HttpClientHandler handler = CreateHttpClientHandler();

            handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates;
            TestHelper.EnsureHttp2Feature(handler);

            var content = new ByteArrayContent(TestHelper.GenerateRandomContent(ContentSize));

            using (var server = Http2LoopbackServer.CreateServer())
                using (var client = new HttpClient(handler))
                {
                    Task <HttpResponseMessage> clientTask = client.PostAsync(server.Address, content);

                    await server.EstablishConnectionAsync();

                    Frame frame = await server.ReadFrameAsync(TimeSpan.FromSeconds(30));

                    int streamId = frame.StreamId;
                    Assert.Equal(FrameType.Headers, frame.Type);
                    Assert.Equal(FrameFlags.EndHeaders, frame.Flags);

                    // Receive up to initial window size
                    int bytesReceived = 0;
                    while (bytesReceived < InitialWindowSize)
                    {
                        frame = await server.ReadFrameAsync(TimeSpan.FromSeconds(30));

                        Assert.Equal(streamId, frame.StreamId);
                        Assert.Equal(FrameType.Data, frame.Type);
                        Assert.Equal(FrameFlags.None, frame.Flags);
                        Assert.True(frame.Length > 0);

                        bytesReceived += frame.Length;
                    }

                    Assert.Equal(InitialWindowSize, bytesReceived);

                    // Issue another read. It shouldn't complete yet. Wait a brief period of time to ensure it doesn't complete.
                    Task <Frame> readFrameTask = server.ReadFrameAsync(TimeSpan.FromSeconds(30));

                    await Task.Delay(500);

                    Assert.False(readFrameTask.IsCompleted);

                    // Increase connection window by one. This should still not complete the read.
                    await server.WriteFrameAsync(new WindowUpdateFrame(1, 0));

                    await Task.Delay(500);

                    Assert.False(readFrameTask.IsCompleted);

                    // Increase stream window by two. This should complete the read with a single byte.
                    await server.WriteFrameAsync(new WindowUpdateFrame(2, streamId));

                    frame = await readFrameTask;
                    Assert.Equal(1, frame.Length);
                    bytesReceived++;

                    // Issue another read and ensure it doesn't complete yet.
                    readFrameTask = server.ReadFrameAsync(TimeSpan.FromSeconds(30));

                    await Task.Delay(500);

                    Assert.False(readFrameTask.IsCompleted);

                    // Increase connection window by two. This should complete the read with a single byte.
                    await server.WriteFrameAsync(new WindowUpdateFrame(2, 0));

                    frame = await readFrameTask;
                    Assert.Equal(1, frame.Length);
                    bytesReceived++;

                    // Issue another read and ensure it doesn't complete yet.
                    readFrameTask = server.ReadFrameAsync(TimeSpan.FromSeconds(30));

                    await Task.Delay(500);

                    Assert.False(readFrameTask.IsCompleted);

                    // Increase connection window to allow exactly the remaining request size. This should still not complete the read.
                    await server.WriteFrameAsync(new WindowUpdateFrame(ContentSize - bytesReceived - 1, 0));

                    await Task.Delay(500);

                    Assert.False(readFrameTask.IsCompleted);

                    // Increase stream window to allow exactly the remaining request size. This should allow the rest of the request to be sent.
                    await server.WriteFrameAsync(new WindowUpdateFrame(ContentSize - bytesReceived, streamId));

                    frame = await readFrameTask;
                    Assert.Equal(streamId, frame.StreamId);
                    Assert.Equal(FrameType.Data, frame.Type);
                    Assert.Equal(FrameFlags.None, frame.Flags);
                    Assert.True(frame.Length > 0);

                    bytesReceived += frame.Length;

                    // Read to end of stream
                    bytesReceived += await ReadToEndOfStream(server, streamId);

                    Assert.Equal(ContentSize, bytesReceived);

                    await server.SendDefaultResponseAsync(streamId);

                    HttpResponseMessage response = await clientTask;
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                }
        }
        private SpeechRecognitionEvent Recognize(string sessionId, string contentType, Metadata metaData, Stream audio, string transferEncoding = "", string model = "", string customizationId = "", bool?continuous = null, int?inactivityTimeout = null, string[] keywords = null, double?keywordsThreshold = null, int?maxAlternatives = null, double?wordAlternativesThreshold = null, bool?wordConfidence = null, bool?timestamps = null, bool profanityFilter = false, bool?smartFormatting = null, bool?speakerLabels = null)
        {
            if (string.IsNullOrEmpty(contentType))
            {
                throw new ArgumentNullException($"{nameof(contentType)}");
            }

            SpeechRecognitionEvent result = null;

            try
            {
                string   urlService = string.Empty;
                IRequest request    = null;

                if (string.IsNullOrEmpty(sessionId))
                {
                    request =
                        this.Client.WithAuthentication(this.UserName, this.Password)
                        .PostAsync($"{this.Endpoint}{PATH_RECOGNIZE}");
                }
                else
                {
                    request =
                        this.Client.WithAuthentication(this.UserName, this.Password)
                        .PostAsync($"{this.Endpoint}{string.Format(PATH_SESSION_RECOGNIZE, sessionId)}")
                        .WithHeader("Cookie", sessionId);
                }

                if (!string.IsNullOrEmpty(transferEncoding))
                {
                    request.WithHeader("Transfer-Encoding", transferEncoding);
                }

                if (metaData == null)
                {
                    // if a session exists, the model should not be sent
                    if (string.IsNullOrEmpty(sessionId))
                    {
                        request.WithArgument("model", model);
                    }

                    if (!string.IsNullOrEmpty(customizationId))
                    {
                        request.WithArgument("customization_id", customizationId);
                    }

                    if (continuous.HasValue)
                    {
                        request.WithArgument("continuous", continuous.Value);
                    }

                    if (inactivityTimeout.HasValue && inactivityTimeout.Value > 0)
                    {
                        request.WithArgument("inactivity_timeout", inactivityTimeout.Value);
                    }

                    if (keywords != null && keywords.Length > 0)
                    {
                        request.WithArgument("keywords", keywords);
                    }

                    if (keywordsThreshold.HasValue && keywordsThreshold.Value > 0)
                    {
                        request.WithArgument("keywords_threshold", keywordsThreshold.Value);
                    }

                    if (maxAlternatives.HasValue && maxAlternatives.Value > 0)
                    {
                        request.WithArgument("max_alternatives", maxAlternatives.Value);
                    }

                    if (wordAlternativesThreshold.HasValue && wordAlternativesThreshold.Value > 0)
                    {
                        request.WithArgument("word_alternatives_threshold", wordAlternativesThreshold.Value);
                    }

                    if (wordConfidence.HasValue)
                    {
                        request.WithArgument("word_confidence", wordConfidence.Value);
                    }

                    if (timestamps.HasValue)
                    {
                        request.WithArgument("timestamps", timestamps.Value);
                    }

                    if (profanityFilter)
                    {
                        request.WithArgument("profanity_filter", profanityFilter);
                    }

                    if (smartFormatting.HasValue)
                    {
                        request.WithArgument("smart_formatting", smartFormatting.Value);
                    }

                    if (speakerLabels.HasValue)
                    {
                        request.WithArgument("speaker_labels", speakerLabels.Value);
                    }

                    StreamContent bodyContent = new StreamContent(audio);
                    bodyContent.Headers.Add("Content-Type", contentType);

                    request.WithBodyContent(bodyContent);
                }
                else
                {
                    var json = JsonConvert.SerializeObject(metaData);

                    StringContent metadata = new StringContent(json);
                    metadata.Headers.ContentType = MediaTypeHeaderValue.Parse(HttpMediaType.APPLICATION_JSON);

                    var audioContent = new ByteArrayContent((audio as Stream).ReadAllBytes());
                    audioContent.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType);

                    MultipartFormDataContent formData = new MultipartFormDataContent();

                    // if a session exists, the model should not be sent
                    if (string.IsNullOrEmpty(sessionId))
                    {
                        request.WithArgument("model", model);
                    }

                    formData.Add(metadata, "metadata");
                    formData.Add(audioContent, "upload");

                    request.WithBodyContent(formData);
                }

                result =
                    request.As <SpeechRecognitionEvent>()
                    .Result;
            }
            catch (AggregateException ae)
            {
                throw ae.InnerException as ServiceResponseException;
            }

            return(result);
        }
示例#26
0
        public async Task Http2_InitialWindowSize_ClientDoesNotExceedWindows()
        {
            const int DefaultInitialWindowSize = 65535;
            const int ContentSize = 100_000;

            HttpClientHandler handler = CreateHttpClientHandler();

            handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates;
            TestHelper.EnsureHttp2Feature(handler);

            var content = new ByteArrayContent(TestHelper.GenerateRandomContent(ContentSize));

            using (var server = Http2LoopbackServer.CreateServer())
                using (var client = new HttpClient(handler))
                {
                    Task <HttpResponseMessage> clientTask = client.PostAsync(server.Address, content);

                    await server.EstablishConnectionAsync();

                    // Bump connection window so it won't block the client.
                    await server.WriteFrameAsync(new WindowUpdateFrame(ContentSize - DefaultInitialWindowSize, 0));

                    Frame frame = await server.ReadFrameAsync(TimeSpan.FromSeconds(30));

                    int streamId = frame.StreamId;
                    Assert.Equal(FrameType.Headers, frame.Type);
                    Assert.Equal(FrameFlags.EndHeaders, frame.Flags);

                    // Receive up to initial window size
                    int bytesReceived = 0;
                    while (bytesReceived < DefaultInitialWindowSize)
                    {
                        frame = await server.ReadFrameAsync(TimeSpan.FromSeconds(30));

                        Assert.Equal(streamId, frame.StreamId);
                        Assert.Equal(FrameType.Data, frame.Type);
                        Assert.Equal(FrameFlags.None, frame.Flags);
                        Assert.True(frame.Length > 0);

                        bytesReceived += frame.Length;
                    }

                    Assert.Equal(DefaultInitialWindowSize, bytesReceived);

                    // Issue another read. It shouldn't complete yet. Wait a brief period of time to ensure it doesn't complete.
                    Task <Frame> readFrameTask = server.ReadFrameAsync(TimeSpan.FromSeconds(30));

                    await Task.Delay(500);

                    Assert.False(readFrameTask.IsCompleted);

                    // Change SETTINGS_INITIAL_WINDOW_SIZE to 0. This will make the client's credit go negative.
                    server.ExpectSettingsAck();
                    await server.WriteFrameAsync(new SettingsFrame(new SettingsEntry {
                        SettingId = SettingId.InitialWindowSize, Value = 0
                    }));

                    await Task.Delay(500);

                    Assert.False(readFrameTask.IsCompleted);

                    // Increase stream window by one. Client credit will still be negative.
                    await server.WriteFrameAsync(new WindowUpdateFrame(1, streamId));

                    await Task.Delay(500);

                    Assert.False(readFrameTask.IsCompleted);

                    // Change SETTINGS_INITIAL_WINDOW_SIZE to 1. Client credit will still be negative.
                    server.ExpectSettingsAck();
                    await server.WriteFrameAsync(new SettingsFrame(new SettingsEntry {
                        SettingId = SettingId.InitialWindowSize, Value = 1
                    }));

                    await Task.Delay(500);

                    Assert.False(readFrameTask.IsCompleted);

                    // Increase stream window so client credit will be 0.
                    await server.WriteFrameAsync(new WindowUpdateFrame(DefaultInitialWindowSize - 2, streamId));

                    await Task.Delay(500);

                    Assert.False(readFrameTask.IsCompleted);

                    // Increase stream window by one, so client can now send a single byte.
                    await server.WriteFrameAsync(new WindowUpdateFrame(1, streamId));

                    frame = await readFrameTask;
                    Assert.Equal(FrameType.Data, frame.Type);
                    Assert.Equal(1, frame.Length);
                    bytesReceived++;

                    // Issue another read and ensure it doesn't complete yet.
                    readFrameTask = server.ReadFrameAsync(TimeSpan.FromSeconds(30));

                    await Task.Delay(500);

                    Assert.False(readFrameTask.IsCompleted);

                    // Increase SETTINGS_INITIAL_WINDOW_SIZE to 2, so client can now send a single byte.
                    server.ExpectSettingsAck();
                    await server.WriteFrameAsync(new SettingsFrame(new SettingsEntry {
                        SettingId = SettingId.InitialWindowSize, Value = 2
                    }));

                    frame = await readFrameTask;
                    Assert.Equal(FrameType.Data, frame.Type);
                    Assert.Equal(1, frame.Length);
                    bytesReceived++;

                    // Issue another read and ensure it doesn't complete yet.
                    readFrameTask = server.ReadFrameAsync(TimeSpan.FromSeconds(30));

                    await Task.Delay(500);

                    Assert.False(readFrameTask.IsCompleted);

                    // Increase SETTINGS_INITIAL_WINDOW_SIZE to be enough that the client can send the rest of the content.
                    server.ExpectSettingsAck();
                    await server.WriteFrameAsync(new SettingsFrame(new SettingsEntry {
                        SettingId = SettingId.InitialWindowSize, Value = ContentSize - (DefaultInitialWindowSize - 1)
                    }));

                    frame = await readFrameTask;
                    Assert.Equal(streamId, frame.StreamId);
                    Assert.Equal(FrameType.Data, frame.Type);
                    Assert.Equal(FrameFlags.None, frame.Flags);
                    Assert.True(frame.Length > 0);

                    bytesReceived += frame.Length;

                    // Read to end of stream
                    bytesReceived += await ReadToEndOfStream(server, streamId);

                    Assert.Equal(ContentSize, bytesReceived);

                    await server.SendDefaultResponseAsync(streamId);

                    HttpResponseMessage response = await clientTask;
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                }
        }
        public async Task MakeRequest(Batch batch)
        {
            Stopwatch watch = new Stopwatch();

            try
            {
                Uri uri = new Uri(_client.Config.Host + "/v1/import");

                // set the current request time
                batch.SentAt = DateTime.Now.ToString("o");

                string json = JsonConvert.SerializeObject(batch);

                // Basic Authentication
                // https://segment.io/docs/tracking-api/reference/#authentication
#if NET35
                _httpClient.Headers.Set("Authorization", "Basic " + BasicAuthHeader(batch.WriteKey, string.Empty));
                _httpClient.Headers.Set("Content-Type", "application/json; charset=utf-8");
#else
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", BasicAuthHeader(batch.WriteKey, string.Empty));
#endif

                // Prepare request data;
                var requestData = Encoding.UTF8.GetBytes(json);

                // Compress request data if compression is set
                if (_client.Config.CompressRequest)
                {
#if NET35
                    _httpClient.Headers.Add(HttpRequestHeader.ContentEncoding, "gzip");
#else
                    //_httpClient.DefaultRequestHeaders.Add("Content-Encoding", "gzip");
#endif

                    // Compress request data with GZip
                    using (MemoryStream memory = new MemoryStream())
                    {
                        using (GZipStream gzip = new GZipStream(memory, CompressionMode.Compress, true))
                        {
                            gzip.Write(requestData, 0, requestData.Length);
                        }
                        requestData = memory.ToArray();
                    }
                }

                Logger.Info("Sending analytics request to Segment.io ..", new Dict
                {
                    { "batch id", batch.MessageId },
                    { "json size", json.Length },
                    { "batch size", batch.batch.Count }
                });

                // Retries with exponential backoff
                const int MAXIMUM_BACKOFF_DURATION = 10000; // Set maximum waiting limit to 10s
                int       backoff = 100;                    // Set initial waiting time to 100ms

                int    statusCode  = (int)HttpStatusCode.OK;
                string responseStr = "";

                while (backoff < MAXIMUM_BACKOFF_DURATION)
                {
#if NET35
                    watch.Start();

                    try
                    {
                        var response = Encoding.UTF8.GetString(_httpClient.UploadData(uri, "POST", requestData));
                        watch.Stop();

                        Succeed(batch, watch.ElapsedMilliseconds);
                        break;
                    }
                    catch (WebException ex)
                    {
                        watch.Stop();

                        var response = (HttpWebResponse)ex.Response;
                        if (response != null)
                        {
                            statusCode = (int)response.StatusCode;
                            if ((statusCode >= 500 && statusCode <= 600) || statusCode == 429)
                            {
                                // If status code is greater than 500 and less than 600, it indicates server error
                                // Error code 429 indicates rate limited.
                                // Retry uploading in these cases.
                                Thread.Sleep(backoff);
                                backoff *= 2;
                                continue;
                            }
                            else if (statusCode >= 400)
                            {
                                responseStr  = String.Format("Status Code {0}. ", statusCode);
                                responseStr += ex.Message;
                                break;
                            }
                        }
                    }
#else
                    watch.Start();

                    ByteArrayContent content = new ByteArrayContent(requestData);
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    if (_client.Config.CompressRequest)
                    {
                        content.Headers.ContentEncoding.Add("gzip");
                    }

                    var response = await _httpClient.PostAsync(uri, content).ConfigureAwait(false);

                    watch.Stop();

                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        Succeed(batch, watch.ElapsedMilliseconds);
                        break;
                    }
                    else
                    {
                        statusCode = (int)response.StatusCode;
                        if ((statusCode >= 500 && statusCode <= 600) || statusCode == 429)
                        {
                            // If status code is greater than 500 and less than 600, it indicates server error
                            // Error code 429 indicates rate limited.
                            // Retry uploading in these cases.
                            await Task.Delay(backoff);

                            backoff *= 2;
                            continue;
                        }
                        else if (statusCode >= 400)
                        {
                            responseStr  = String.Format("Status Code {0}. ", response.StatusCode);
                            responseStr += await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                            break;
                        }
                    }
#endif
                }

                if (backoff >= MAXIMUM_BACKOFF_DURATION || statusCode != (int)HttpStatusCode.OK)
                {
                    Fail(batch, new APIException("Unexpected Status Code", responseStr), watch.ElapsedMilliseconds);
                }
            }
            catch (System.Exception e)
            {
                watch.Stop();
                Fail(batch, e, watch.ElapsedMilliseconds);
            }
        }
示例#28
0
        /// <summary>
        /// <see cref="INfieldSurveysService.SamplingPointImageAddAsync(string, string, string, byte[])"/>
        /// </summary>
        /// <returns>image file name</returns>
        public Task <string> SamplingPointImageAddAsync(string surveyId, string samplingPointId, string filename, byte[] content)
        {
            var byteArrayContent = new ByteArrayContent(content);

            return(SamplingPointImageAddAsync(surveyId, samplingPointId, filename, byteArrayContent));
        }
        /// <summary>
        /// Gets the handwritten text from the specified image file by using the Computer Vision REST API.
        /// </summary>
        /// <param name="imageFilePath">The image file with handwritten text.</param>
        public async Task <string> ReadHandwrittenTextAsync(string imageFilePath)
        {
            HttpClient client = new HttpClient();
            string     result = "";

            // Request headers.
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", _apiKeys);

            // Request parameter. Set "handwriting" to false for printed text.
            string requestParameters = "handwriting=true";

            // Assemble the URI for the REST API Call.
            string uri = _uri + "/textOperations?" + requestParameters;

            HttpResponseMessage response = null;

            // This operation requrires two REST API calls. One to submit the image for processing,
            // the other to retrieve the text found in the image. This value stores the REST API
            // location to call to retrieve the text.
            string operationLocation = null;

            // Request body. Posts a locally stored JPEG image.
            byte[]           byteData = imageFilePath.GetImageAsByteArray();
            ByteArrayContent content  = new ByteArrayContent(byteData);

            // This example uses content type "application/octet-stream".
            // You can also use "application/json" and specify an image URL.
            content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

            // The first REST call starts the async process to analyze the written text in the image.
            response = await client.PostAsync(uri, content);

            // The response contains the URI to retrieve the result of the process.
            if (response.IsSuccessStatusCode)
            {
                operationLocation = response.Headers.GetValues("Operation-Location").FirstOrDefault();
            }
            else
            {
                // Display the JSON error data.
                Console.WriteLine("\nError:\n");
                var res = await response.Content.ReadAsStringAsync();

                result = res.JsonPrettyPrint();
                Console.WriteLine(result);
                return(result);
            }

            // The second REST call retrieves the text written in the image.
            //
            // Note: The response may not be immediately available. Handwriting recognition is an
            // async operation that can take a variable amount of time depending on the length
            // of the handwritten text. You may need to wait or retry this operation.
            //
            // This example checks once per second for ten seconds.
            string contentString;
            int    i = 0;

            do
            {
                System.Threading.Thread.Sleep(1000);
                response = await client.GetAsync(operationLocation);

                contentString = await response.Content.ReadAsStringAsync();

                ++i;
            }while (i < 10 && contentString.IndexOf("\"status\":\"Succeeded\"") == -1);

            if (i == 10 && contentString.IndexOf("\"status\":\"Succeeded\"") == -1)
            {
                result = "\nTimeout error.\n";
                Console.WriteLine(result);
                return(result);
            }

            // Display the JSON response.
            Console.WriteLine("\nResponse:\n");
            result = contentString.JsonPrettyPrint();
            Console.WriteLine(result);
            return(result);
        }
示例#30
0
        private Task <string> SamplingPointImageAddAsync(string surveyId, string samplingPointId, string filename, ByteArrayContent byteArrayContent)
        {
            var uri = GetSamplingPointImageUri(surveyId, samplingPointId, filename);

            byteArrayContent.Headers.ContentType        = new MediaTypeHeaderValue("application/octet-stream");
            byteArrayContent.Headers.ContentDisposition =
                new ContentDispositionHeaderValue("attachment")
            {
                FileName = filename
            };

            return(Client.PostAsync(uri, byteArrayContent)
                   .ContinueWith(responseMessageTask => responseMessageTask.Result.Content.ReadAsStringAsync().Result)
                   .ContinueWith(stringTask => stringTask.Result.Substring(1, stringTask.Result.Length - 2))
                   .FlattenExceptions());
        }
        private static async Task CreateServerAndPostAsync(HttpClient client, int numBytes, string responseText)
        {
            await LoopbackServer.CreateServerAsync(async (server, url) =>
            {
                var content = new ByteArrayContent(new byte[numBytes]);
                Task<HttpResponseMessage> postAsync = client.PostAsync(url, content);

                await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
                {
                    while (!string.IsNullOrEmpty(await reader.ReadLineAsync().ConfigureAwait(false))) ;
                    for (int i = 0; i < numBytes; i++) Assert.NotEqual(-1, reader.Read());

                    await writer.WriteAsync(responseText).ConfigureAwait(false);
                    await writer.FlushAsync().ConfigureAwait(false);
                    s.Shutdown(SocketShutdown.Send);
                });

                (await postAsync.ConfigureAwait(false)).Dispose();
            });
        }
示例#32
0
        public async Task ReadAsStringAsync_OneSubContentWithHeaders_MatchesExpected(MultipartContentToStringMode mode)
        {
            var subContent = new ByteArrayContent(Encoding.UTF8.GetBytes("This is a ByteArrayContent"));
            subContent.Headers.Add("someHeaderName", "andSomeHeaderValue");
            subContent.Headers.Add("someOtherHeaderName", new[] { "withNotOne", "ButTwoValues" });
            subContent.Headers.Add("oneMoreHeader", new[] { "withNotOne", "AndNotTwo", "butThreeValues" });

            var mc = new MultipartContent("someSubtype", "theBoundary");
            mc.Add(subContent);

            Assert.Equal(
                "--theBoundary\r\n" +
                "someHeaderName: andSomeHeaderValue\r\n" +
                "someOtherHeaderName: withNotOne, ButTwoValues\r\n" +
                "oneMoreHeader: withNotOne, AndNotTwo, butThreeValues\r\n" +
                "\r\n" +
                "This is a ByteArrayContent\r\n" +
                "--theBoundary--\r\n",
                await MultipartContentToStringAsync(mc, mode));
        }