public async Task Serialize_StringContent_Success()
        {
            var content = new MultipartFormDataContent("test_boundary");
            content.Add(new StringContent("Hello World"));

            var output = new MemoryStream();
            await content.CopyToAsync(output);

            output.Seek(0, SeekOrigin.Begin);
            string result = new StreamReader(output).ReadToEnd();

            Assert.Equal(
                "--test_boundary\r\nContent-Type: text/plain; charset=utf-8\r\n"
                + "Content-Disposition: form-data\r\n\r\nHello World\r\n--test_boundary--\r\n",
                result);
        }
        public async Task ReadAsStreamAsync_LargeContent_AllBytesRead()
        {
            var form = new MultipartFormDataContent();

            const long PerContent = 1024 * 1024;
            const long ContentCount = 2048;

            var bytes = new byte[PerContent];
            for (int i = 0; i < ContentCount; i++)
            {
                form.Add(new ByteArrayContent(bytes), "file", Guid.NewGuid().ToString());
            }

            long totalAsyncRead = 0, totalSyncRead = 0;
            int bytesRead;

            using (Stream s = await form.ReadAsStreamAsync())
            {
                s.Position = 0;
                while ((bytesRead = await s.ReadAsync(bytes, 0, bytes.Length)) > 0)
                {
                    totalAsyncRead += bytesRead;
                }

                s.Position = 0;
                while ((bytesRead = s.Read(bytes, 0, bytes.Length)) > 0)
                {
                    totalSyncRead += bytesRead;
                }
            }

            Assert.Equal(totalAsyncRead, totalSyncRead);
            Assert.InRange(totalAsyncRead, PerContent * ContentCount, long.MaxValue); 
        }
        public static async Task <UploadFilesIoFile> UploadFile(HttpClient httpClient, string path)
        {
            int retries    = 0;
            int maxRetries = 5;

            while (retries < maxRetries)
            {
                try
                {
                    string html = await httpClient.GetStringAsync("https://ufile.io");

                    Match regexMatchCSRFToken = new Regex("name=\"csrf_test_name\" value=\"(?<CSRFToken>.*)\"").Match(html);
                    Match regexMatchSessionId = new Regex("<input.*?id=\"session_id\".*?value=\"(?<SessionId>.*)\"").Match(html);

                    if (regexMatchCSRFToken.Success && regexMatchSessionId.Success)
                    {
                        string csrfToken = regexMatchCSRFToken.Groups["CSRFToken"].Value;
                        string sessionId = regexMatchSessionId.Groups["SessionId"].Value;

                        // Create session
                        Dictionary <string, string> postValuesCreateSession = new Dictionary <string, string>
                        {
                            { "csrf_test_name", csrfToken },
                            { "file_size", new FileInfo(path).Length.ToString() }
                        };

                        HttpRequestMessage httpRequestMessageCreateSession = new HttpRequestMessage(HttpMethod.Post, "https://up.ufile.io/v1/upload/create_session")
                        {
                            Content = new FormUrlEncodedContent(postValuesCreateSession)
                        };
                        HttpResponseMessage httpResponseMessageCreateSession = await httpClient.SendAsync(httpRequestMessageCreateSession);

                        JObject resultCreateSession = JObject.Parse(await httpResponseMessageCreateSession.Content.ReadAsStringAsync());

                        string fileId = resultCreateSession["fuid"].Value <string>();

                        if (string.IsNullOrEmpty(fileId))
                        {
                            throw new Exception("Ufile.io error, error creating session");
                        }

                        // Post file
                        using (MultipartFormDataContent multipartFormDataContent = new MultipartFormDataContent($"Upload----{Guid.NewGuid()}"))
                        {
                            multipartFormDataContent.Add(new StringContent("1"), "chunk_index");
                            multipartFormDataContent.Add(new StringContent(fileId), "fuid");
                            multipartFormDataContent.Add(new StreamContent(new FileStream(path, FileMode.Open)), "file", Path.GetFileName(path));

                            using (HttpResponseMessage httpResponseMessage = await httpClient.PostAsync("https://up.ufile.io/v1/upload/chunk", multipartFormDataContent))
                            {
                                httpResponseMessage.EnsureSuccessStatusCode();
                            }
                        }

                        // Finalise
                        Dictionary <string, string> postValuesFinalise = new Dictionary <string, string>
                        {
                            { "csrf_test_name", csrfToken },
                            { "fuid", fileId },
                            { "file_name", Path.GetFileName(path) },
                            { "file_type", Path.GetExtension(path) },
                            { "total_chunks", "1" },
                            { "session_id", sessionId },
                        };

                        HttpRequestMessage httpRequestMessageFinalise = new HttpRequestMessage(HttpMethod.Post, "https://up.ufile.io/v1/upload/finalise")
                        {
                            Content = new FormUrlEncodedContent(postValuesFinalise)
                        };
                        HttpResponseMessage httpResponseMessageFinalise = await httpClient.SendAsync(httpRequestMessageFinalise);

                        return(JsonConvert.DeserializeObject <UploadFilesIoFile>(await httpResponseMessageFinalise.Content.ReadAsStringAsync()));
                    }

                    retries++;
                }
                catch (Exception)
                {
                    retries++;
                    Logger.Error($"Error uploading file... Retry in 5 seconds!!!");
                    await Task.Delay(TimeSpan.FromSeconds(5));
                }
            }

            throw new FriendlyException("Error uploading URLs");
        }
Beispiel #4
0
        private async void btnyes_Clicked(object sender, EventArgs e)
        {
            var btn  = sender as Button;
            var text = btn.Text;

            try
            {
                Alogin.IsRunning = true;
                Alogin.IsVisible = true;


                if (text == "Publish")
                {
                    btnyes.BackgroundColor = Color.FromHex("#f24245");
                }
                else if (text == "Save")
                {
                    btnyes1.BackgroundColor = Color.FromHex("#f24245");
                }

                memberDatabase = new MemberDatabase();
                var members = memberDatabase.GetUserDetail();

                UserDetail userin = (from blog in members
                                     select blog).FirstOrDefault();

                storeUId = userin.StoreUId;

                //var byteArray = System.Convert.FromBase64String(ImageString);
                //ImageName2 = await AzureStorage.UploadFileAsync(ContainerType.Image, new MemoryStream(byteArray.ToArray()));
                var Filepath2 = System.IO.Path.GetDirectoryName(FilePath);
                var content   = new MultipartFormDataContent();
                await Task.Delay(TimeSpan.FromSeconds(0.01));

                var fileName = FilePath.Substring(FilePath.LastIndexOf("/") + 1);

                IFolder rootFolder = await FileSystem.Current.GetFolderFromPathAsync(Filepath2);

                var filee = await rootFolder.GetFileAsync(fileName);

                Stream stream = await filee.OpenAsync(FileAccess.Read);

                // image.Source = ImageSource.FromStream(() => stream);

                content.Add(new StreamContent(stream),
                            "\"filee\"",
                            $"\"{filee.Path}\"");

                var httpClient = new System.Net.Http.HttpClient();
                var uploadServiceBaseAddress = "http://elixirct.in/ShopRConservicePublish/api/Files/Upload";
                var httpResponseMessage      = await httpClient.PostAsync(uploadServiceBaseAddress, content);

                if (httpResponseMessage.ReasonPhrase.Equals("OK"))
                {
                    if (text == "Publish")
                    {
                        string Inputs = "StoreUId=" + storeUId + "&Img=" + fileName + "&Description=" + Offer1 + "&ValidTo=" + ValidTo + "&ValidFrom=" + ValidFrom + "&OfferTnC=" + TnC +
                                        "&ScreenName=" + "Insertoffer" + "&OfferStatus=" + "Publish" + "&OfferId=" + "0";

                        string resp = await RestService.UploadOffer(Inputs);

                        var result = Newtonsoft.Json.JsonConvert.DeserializeObject <string>(resp);
                        if (result != "0")
                        {
                            string imagename = fileName;
                            string url       = "http://elixirct.in/ShopRConservicePublish/Uploads/" + imagename;
                            DependencyService.Get <IFileService>().DownloadFile(url, getGalleryPath());
                            //  DependencyService.Get<IFileService>().SavePicture(fileName, stream, getGalleryPath());
                            // var images = DependencyService.Get<IFileService>().GetPictureFromDisk(fileName, getGalleryPath());
                            //offerdetails = new OfferDetail();
                            //memberDatabase = new MemberDatabase();
                            //offerdetails.Imagename = imagestore2;
                            //offerdetails.ofer = Offer1;
                            //memberDatabase.AddOfferDetail(offerdetails);
                            await DisplayAlert("Alert", "Offer Upload Successfully..!", "Ok");

                            await Navigation.PopAllPopupAsync();

                            //await Navigation.PushAsync(new Offer());
                            await Navigation.PopAsync();
                        }
                    }
                    else if (text == "Save")
                    {
                        string Inputs = "StoreUId=" + storeUId + "&Img=" + fileName + "&Description=" + Offer1 + "&ValidTo=" + ValidTo + "&ValidFrom=" + ValidFrom + "&OfferTnC=" + TnC +
                                        "&ScreenName=" + "Insertoffer" + "&OfferStatus=" + "Save" + "&OfferId=" + "0";
                        string resp = await RestService.UploadOffer(Inputs);

                        var result = Newtonsoft.Json.JsonConvert.DeserializeObject <string>(resp);
                        if (result != "0")
                        {
                            string imagename = fileName;
                            string url       = "http://elixirct.in/ShopRConservicePublish/Uploads/" + imagename;
                            DependencyService.Get <IFileService>().DownloadFile(url, getGalleryPath());
                            // DependencyService.Get<IFileService>().SavePicture(fileName, stream, getGalleryPath());
                            //var images = DependencyService.Get<IFileService>().GetPictureFromDisk(imagestore2, getGalleryPath());

                            //offerdetails = new OfferDetail();
                            //memberDatabase = new MemberDatabase();
                            //offerdetails.Imagename = imagestore2;
                            //offerdetails.ofer = Offer1;
                            //memberDatabase.AddOfferDetail(offerdetails);
                            await DisplayAlert("Alert", "Offer Upload Successfully..!", "Ok");

                            await Navigation.PopAllPopupAsync();

                            //await Navigation.PushAsync(new Offer());
                            await Navigation.PopAsync();
                        }
                    }
                }
                Alogin.IsRunning = false;
                Alogin.IsVisible = false;
            }
            catch (Exception ex)
            {
                // await DisplayAlert("Alert", "Offer is not ", "OK");
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }
        /// <summary>
        /// Add images.
        ///
        /// Add images to a collection by URL, by file, or both.
        ///
        /// Encode the image and .zip file names in UTF-8 if they contain non-ASCII characters. The service assumes
        /// UTF-8 encoding if it encounters non-ASCII characters.
        /// </summary>
        /// <param name="collectionId">The identifier of the collection.</param>
        /// <param name="imagesFile">An array of image files (.jpg or .png) or .zip files with images.
        /// - Include a maximum of 20 images in a request.
        /// - Limit the .zip file to 100 MB.
        /// - Limit each image file to 10 MB.
        ///
        /// You can also include an image with the **image_url** parameter. (optional)</param>
        /// <param name="imageUrl">The array of URLs of image files (.jpg or .png).
        /// - Include a maximum of 20 images in a request.
        /// - Limit each image file to 10 MB.
        /// - Minimum width and height is 30 pixels, but the service tends to perform better with images that are at
        /// least 300 x 300 pixels. Maximum is 5400 pixels for either height or width.
        ///
        /// You can also include images with the **images_file** parameter. (optional)</param>
        /// <param name="trainingData">Training data for a single image. Include training data only if you add one image
        /// with the request.
        ///
        /// The `object` property can contain alphanumeric, underscore, hyphen, space, and dot characters. It cannot
        /// begin with the reserved prefix `sys-` and must be no longer than 32 characters. (optional)</param>
        /// <returns><see cref="ImageDetailsList" />ImageDetailsList</returns>
        public DetailedResponse <ImageDetailsList> AddImages(string collectionId, List <FileWithMetadata> imagesFile = null, List <string> imageUrl = null, string trainingData = null)
        {
            if (string.IsNullOrEmpty(collectionId))
            {
                throw new ArgumentNullException("`collectionId` is required for `AddImages`");
            }
            else
            {
                collectionId = Uri.EscapeDataString(collectionId);
            }

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

            DetailedResponse <ImageDetailsList> result = null;

            try
            {
                var formData = new MultipartFormDataContent();

                if (imagesFile != null)
                {
                    foreach (FileWithMetadata item in imagesFile)
                    {
                        var imagesFileContent = new ByteArrayContent(item.Data.ToArray());
                        System.Net.Http.Headers.MediaTypeHeaderValue contentType;
                        System.Net.Http.Headers.MediaTypeHeaderValue.TryParse(item.ContentType, out contentType);
                        imagesFileContent.Headers.ContentType = contentType;
                        formData.Add(imagesFileContent, "images_file", item.Filename);
                    }
                }

                if (imageUrl != null)
                {
                    foreach (string item in imageUrl)
                    {
                        var imageUrlContent = new StringContent(item, Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                        imageUrlContent.Headers.ContentType = null;
                        formData.Add(imageUrlContent, "image_url");
                    }
                }

                if (trainingData != null)
                {
                    var trainingDataContent = new StringContent(trainingData, Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    trainingDataContent.Headers.ContentType = null;
                    formData.Add(trainingDataContent, "training_data");
                }

                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.PostAsync($"{this.Endpoint}/v4/collections/{collectionId}/images");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");
                restRequest.WithBodyContent(formData);

                restRequest.WithHeaders(Common.GetSdkHeaders("watson_vision_combined", "v4", "AddImages"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

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

            return(result);
        }
Beispiel #6
0
        private async Task <CustomHttpResponse <string> > ProcessRequest(RextOptions options)
        {
            if (this.Client == null)
            {
                throw new ArgumentNullException("HttpClient object cannot be null");
            }

            // validate essential params
            if (string.IsNullOrEmpty(options.Url))
            {
                if (string.IsNullOrEmpty(ConfigurationBundle.HttpConfiguration.BaseUrl))
                {
                    throw new ArgumentNullException(nameof(options.Url), $"{nameof(options.Url)} is required. Provide fully qualified api endpoint.");
                }
                else
                {
                    throw new ArgumentNullException(nameof(options.Url), $"{nameof(options.Url)} is required. Provide the other part of api endpoint to match the BaseUrl.");
                }
            }

            if (options.Method == null)
            {
                throw new ArgumentNullException(nameof(options.Method), $"{nameof(options.Method)} is required. Use GET, POST etc..");
            }

            if (string.IsNullOrEmpty(options.ContentType))
            {
                throw new ArgumentNullException(nameof(options.ContentType), $"{nameof(options.ContentType) } is required. Use application/json, text.plain etc..");
            }

            if (string.IsNullOrEmpty(options.ExpectedResponseFormat))
            {
                throw new ArgumentNullException(nameof(options.ExpectedResponseFormat), $"{nameof(options.ExpectedResponseFormat)} is required. Use application/json, text.plain etc..");
            }


            // execute all user actions pre-call
            ConfigurationBundle.BeforeCall?.Invoke();

            var    rsp            = new CustomHttpResponse <string>();
            var    response       = new HttpResponseMessage();
            string responseString = string.Empty;

            try
            {
                Uri uri = options.CreateUri(ConfigurationBundle.HttpConfiguration.BaseUrl);
                if (uri == null)
                {
                    throw new UriFormatException("Invalid request Uri");
                }

                var requestMsg = new HttpRequestMessage(options.Method, uri);

                // set header if object has value
                if (this.Headers != null)
                {
                    requestMsg.SetHeader(this.Headers);
                }

                if (options.Header != null)
                {
                    requestMsg.SetHeader(options.Header);
                }

                if (ConfigurationBundle.HttpConfiguration.Header != null)
                {
                    requestMsg.SetHeader(ConfigurationBundle.HttpConfiguration.Header);
                }

                if (!string.IsNullOrEmpty(options.ContentType))
                {
                    requestMsg.SetHeader("Accept", options.ExpectedResponseFormat);
                }

                // POST request
                if (options.Method != HttpMethod.Get && options.Payload != null)
                {
                    string strPayload = string.Empty;

                    if (options.IsForm)
                    {
                        strPayload = options.Payload.ToQueryString()?.TrimStart('?');

                        // form-data content post
                        if (!options.IsUrlEncoded)
                        {
                            // handle multipart/form-data
                            var formData      = strPayload.Split('&');
                            var mpfDataBucket = new MultipartFormDataContent();

                            foreach (var i in formData)
                            {
                                var row = i.Split('=');
                                if (row.Length == 2) // check index to avoid null
                                {
                                    mpfDataBucket.Add(new StringContent(row[1]), row[0]);
                                }
                            }

                            requestMsg.Content = mpfDataBucket;
                        }
                        else
                        {
                            // handle application/x-www-form-urlencoded
                            requestMsg.Content = new StringContent(strPayload, Encoding.UTF8, "application/x-www-form-urlencoded");
                        }
                    }
                    else
                    {
                        // convert object to specified content-type
                        if (options.ContentType == ContentType.Application_JSON)
                        {
                            strPayload = options.Payload.ToJson();
                        }
                        else if (options.ContentType == ContentType.Application_XML)
                        {
                            strPayload = options.Payload.ToXml();
                        }
                        else
                        {
                            strPayload = options.Payload.ToString();
                        }

                        requestMsg.Content = new StringContent(strPayload, Encoding.UTF8, options.ContentType);
                    }
                }

                // use stopwatch to monitor httpcall duration
                if (ConfigurationBundle.EnableStopwatch)
                {
                    Stopwatch = new Stopwatch();
                    Stopwatch.Start();
                }

                // check if HttpCompletionOption option is used
                HttpCompletionOption httpCompletionOption = ConfigurationBundle.HttpConfiguration.HttpCompletionOption;
                if (options.HttpCompletionOption.HasValue)
                {
                    if (ConfigurationBundle.HttpConfiguration.HttpCompletionOption != options.HttpCompletionOption.Value)
                    {
                        httpCompletionOption = options.HttpCompletionOption.Value;
                    }
                }

                response = await this.Client.SendAsync(requestMsg, httpCompletionOption, CancellationToken.None).ConfigureAwait(false);

                // set watch value to public member
                if (ConfigurationBundle.EnableStopwatch)
                {
                    Stopwatch.Stop();
                }

                rsp.StatusCode = response.StatusCode;

                if (options.IsStreamResponse)
                {
                    var stream = await response.Content.ReadAsStreamAsync();

                    if (stream.Length > 0)
                    {
                        using (var rd = new StreamReader(stream))
                            responseString = rd.ReadToEnd();
                    }
                }
                else
                {
                    responseString = await response.Content.ReadAsStringAsync();
                }

                if (response.IsSuccessStatusCode)
                {
                    rsp.Content = responseString;
                    rsp.Message = "Http call successful";
                }
                else
                {
                    // this will always run before custom error-code actions
                    // always set ThrowExceptionIfNotSuccessResponse=false if you will use custom error-code actions
                    // perform checks for neccessary override
                    bool throwExIfNotSuccessRsp = options.ThrowExceptionIfNotSuccessResponse ?? ConfigurationBundle.HttpConfiguration.ThrowExceptionIfNotSuccessResponse;
                    if (throwExIfNotSuccessRsp)
                    {
                        throw new RextException($"Server response is {rsp.StatusCode}");
                    }

                    if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
                    {
                        rsp.Content = $"Url not found: {requestMsg.RequestUri}";
                    }
                    else
                    {
                        rsp.Content = responseString;
                    }
                    rsp.Message = "Http call completed but not successful";

                    // handle code specific error from user
                    int code = (int)response.StatusCode;
                    if (code > 0 && ConfigurationBundle.StatusCodesToHandle != null && ConfigurationBundle.StatusCodesToHandle.Contains(code))
                    {
                        ConfigurationBundle.OnStatusCode?.Invoke(ReturnStatusCode);
                    }
                }

                // execute all user actions post-call
                ConfigurationBundle.AfterCall?.Invoke();
                return(rsp);
            }
            catch (Exception ex)
            {
                // execute all user actions on error
                ConfigurationBundle.OnError?.Invoke();

                if (ConfigurationBundle.SuppressRextExceptions)
                {
                    if (ex?.Message.ToLower().Contains("a socket operation was attempted to an unreachable host") == true)
                    {
                        rsp.Message = "Network connection error";
                    }
                    else if (ex?.Message.ToLower().Contains("the character set provided in contenttype is invalid") == true)
                    {
                        rsp.Message = "Invald response ContentType. If you are expecting a Stream response then set RextOptions.IsStreamResponse=true";
                    }
                    else
                    {
                        rsp.Message = ex?.Message; //{ex?.InnerException?.Message ?? ex?.InnerException?.Message}";
                    }
                    return(rsp);
                }
                else
                {
                    throw ex;
                }
            }
        }
Beispiel #7
0
        private async Task <HttpResponseMessage> HttpResponseMessage(HttpRequest request)
        {
            HttpRequestMessage requestMessage = new HttpRequestMessage
            {
                RequestUri = new Uri(request.QueryUrl),
                Method     = request.HttpMethod,
            };

            foreach (var headers in request.Headers)
            {
                requestMessage.Headers.TryAddWithoutValidation(headers.Key, headers.Value);
            }


            if (!string.IsNullOrEmpty(request.Username))
            {
                var byteArray = Encoding.UTF8.GetBytes(request.Username + ":" + request.Password);
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Basic",
                                                                                     Convert.ToBase64String(byteArray));
            }

            if (request.HttpMethod.Equals(HttpMethod.Delete) || request.HttpMethod.Equals(HttpMethod.Post) || request.HttpMethod.Equals(HttpMethod.Put) || request.HttpMethod.Equals(new HttpMethod("PATCH")))
            {
                requestMessage.Content = new StringContent(string.Empty);
                if (request.Body != null)
                {
                    if (request.Body is FileStreamInfo)
                    {
                        var file = ((FileStreamInfo)request.Body);
                        requestMessage.Content = new StreamContent(file.FileStream);
                        if (!string.IsNullOrWhiteSpace(file.ContentType))
                        {
                            requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(file.ContentType);
                        }
                        else
                        {
                            requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                        }
                    }
                    else if (request.Headers.Any(f => f.Key == "content-type" && f.Value == "application/json; charset=utf-8"))
                    {
                        requestMessage.Content = new StringContent((string)request.Body ?? string.Empty, Encoding.UTF8,
                                                                   "application/json");
                    }
                    else
                    {
                        requestMessage.Content = new StringContent(request.Body.ToString() ?? string.Empty, Encoding.UTF8,
                                                                   "text/plain");
                    }
                }
                else if (request.FormParameters != null && request.FormParameters.Any(f => f.Value is FileStreamInfo))
                {
                    MultipartFormDataContent formContent = new MultipartFormDataContent();
                    foreach (var param in request.FormParameters)
                    {
                        if (param.Value is FileStreamInfo)
                        {
                            FileStreamInfo fileInfo    = (FileStreamInfo)param.Value;
                            var            fileContent = new StreamContent(fileInfo.FileStream);
                            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                            {
                                Name     = param.Key,
                                FileName = fileInfo.FileName
                            };
                            if (!string.IsNullOrWhiteSpace(fileInfo.ContentType))
                            {
                                fileContent.Headers.ContentType = new MediaTypeHeaderValue(fileInfo.ContentType);
                            }
                            else
                            {
                                fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                            }
                            formContent.Add(fileContent, param.Key);
                        }
                        else
                        {
                            formContent.Add(new StringContent(param.Value.ToString()), param.Key);
                        }
                    }
                    requestMessage.Content = formContent;
                }
                else if (request.FormParameters != null)
                {
                    var parameters = new List <KeyValuePair <string, string> >();
                    foreach (var param in request.FormParameters)
                    {
                        parameters.Add(new KeyValuePair <string, string>(param.Key, param.Value.ToString()));
                    }
                    requestMessage.Content = new FormUrlEncodedContent(parameters);
                }
            }
            return(await _client.SendAsync(requestMessage).ConfigureAwait(false));
        }
Beispiel #8
0
        public ActionResult Apply([Bind(Include = "JobId,Message,CV")] ApplyForJob ApplyJob, HttpPostedFileBase CV)
        {
            //-- Validate the uploaded file.
            if (CV != null)
            {
                string fileExtension = Path.GetExtension(CV.FileName);
                if (fileExtension.ToLower() == ".pdf" || fileExtension.ToLower() == ".doc" || fileExtension.ToLower() == ".docx")
                {
                    int fileSize = CV.ContentLength / 1024 / 1024;
                    if (fileSize > 2)
                    {
                        ModelState.AddModelError("CV", "The Uploaded CV must be less than or equal 2 MB.");
                    }
                }
                else
                {
                    ModelState.AddModelError("CV", "The Uploaded CV must be one of that format (pdf, doc, docx).");
                }
            }
            //--

            if (!ModelState.IsValid)
            {
                return(View(ApplyJob));
            }

            using (var formData = new MultipartFormDataContent())
            {
                //--- Read The Image File in byte[].
                byte[] cvData;

                using (var reader = new BinaryReader(CV.InputStream))
                {
                    cvData = reader.ReadBytes(CV.ContentLength);
                }
                //--

                //-- Get the other job properties.
                Dictionary <string, string> formFields = new Dictionary <string, string>();
                formFields.Add("JobId", ApplyJob.JobId.ToString());
                formFields.Add("Message", ApplyJob.Message);

                FormUrlEncodedContent formFieldsContent = new FormUrlEncodedContent(formFields);
                //--

                formData.Add(new ByteArrayContent(cvData), "CV", CV.FileName);
                formData.Add(formFieldsContent, "ApplyJob");

                if (Request.Cookies["BearerToken"] != null)
                {
                    var token = Request.Cookies["BearerToken"].Value;
                    httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
                }

                var ResponseTask = httpClient.PostAsync("Applicants/Apply", formData);
                ResponseTask.Wait();

                var response = ResponseTask.Result;
                if (response.IsSuccessStatusCode)
                {
                    ViewBag.Result = "You Applied Successfully To This Job. You will be redirect to the Home Pgae after 3 Seconds.";
                    return(View(ApplyJob));
                }
                else if (response.StatusCode == HttpStatusCode.Found) // Aleady Applied to that job
                {
                    return(RedirectToAction("Details", "Jobs", new { id = ApplyJob.JobId }));
                }
                else
                {
                    ModelState.AddModelError("", response.Content.ReadAsStringAsync().Result);
                    return(View(ApplyJob));
                }
            }
        }
Beispiel #9
0
        public ActionResult EditApply([Bind(Include = "Id,Message,CV")] ApplyForJob ApplyJob, HttpPostedFileBase CV)
        {
            ModelState.Remove("CV"); // To remove the error CV is required if we didn't upload a new cv
            //-- if we upload a new CV, then Validate the uploaded file.
            if (CV != null)
            {
                string fileExtension = Path.GetExtension(CV.FileName);
                if (fileExtension.ToLower() == ".pdf" || fileExtension.ToLower() == ".doc" || fileExtension.ToLower() == ".docx")
                {
                    int fileSize = CV.ContentLength / 1024 / 1024;
                    if (fileSize > 2)
                    {
                        ModelState.AddModelError("CV", "The Uploaded CV must be less than or equal 2 MB.");
                    }
                }
                else
                {
                    ModelState.AddModelError("CV", "The Uploaded CV must be one of that format (pdf, doc, docx).");
                }
            }
            //--


            if (!ModelState.IsValid)
            {
                return(View(ApplyJob));
            }

            using (var formData = new MultipartFormDataContent())
            {
                //1-- Check if the Applicant post a new CV
                if (CV != null)
                {
                    // Read The CV File in byte[].
                    byte[] cvData;

                    using (var reader = new BinaryReader(CV.InputStream))
                    {
                        cvData = reader.ReadBytes(CV.ContentLength);
                    }
                    formData.Add(new ByteArrayContent(cvData), "CV", CV.FileName);
                }
                //--

                //2-- Get the other ApplyJob properties.
                Dictionary <string, string> formFields = new Dictionary <string, string>();
                formFields.Add("Id", ApplyJob.Id.ToString());
                formFields.Add("Message", ApplyJob.Message);

                FormUrlEncodedContent formFieldsContent = new FormUrlEncodedContent(formFields);
                formData.Add(formFieldsContent, "ApplyJob");
                //--


                if (Request.Cookies["BearerToken"] != null)
                {
                    var token = Request.Cookies["BearerToken"].Value;
                    httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
                }

                var ResponseTask = httpClient.PutAsync("Applicants/EditApply", formData);
                ResponseTask.Wait();

                var response = ResponseTask.Result;
                if (response.IsSuccessStatusCode)
                {
                    return(RedirectToAction("JobsThatAppliedTo"));
                }
                else if (response.StatusCode == HttpStatusCode.NotFound)
                {
                    return(HttpNotFound());
                }
                else
                {
                    ModelState.AddModelError("", response.Content.ReadAsStringAsync().Result);
                    return(View(ApplyJob));
                }
            }
        }
        public async Task <SketchfabUploadResponse> UploadModelAsync(UploadModelRequest request, string sketchFabToken)
        {
            SketchfabUploadResponse sfResponse = new SketchfabUploadResponse();

            try
            {
                _logger.LogInformation($"Uploading model [{request.FilePath}].");
                if (string.IsNullOrWhiteSpace(request.FilePath))
                {
                    throw new ArgumentNullException(nameof(request.FilePath));
                }

                if (!File.Exists(request.FilePath))
                {
                    throw new FileNotFoundException($"File [{request.FilePath}] not found.");
                }
                HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, $"{SketchfabApiUrl}/models");
                httpRequestMessage.AddAuthorizationHeader(sketchFabToken, request.TokenType);
                using var form                  = new MultipartFormDataContent();
                using var fileContent           = new ByteArrayContent(await File.ReadAllBytesAsync(request.FilePath));
                fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
                form.Add(fileContent, "modelFile", Path.GetFileName(request.FilePath));
                if (!string.IsNullOrWhiteSpace(request.Source))
                {
                    form.Add(new StringContent(request.Source), "source");
                }
                else
                {
                    _logger.LogWarning("Sketchfab upload has no source configured. It's better to set one to uniquely identify all the models generated by the exporter, see https://Sketchfab.com/developers/guidelines#source");
                }

                AddCommonModelFields(form, request);

                httpRequestMessage.Content = form;


                var httpClient = _httpClientFactory.CreateClient();
                var response   = await httpClient.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseContentRead);

                _logger.LogInformation($"{nameof(UploadModelAsync)} responded {response.StatusCode}");

                if (response.IsSuccessStatusCode)
                {
                    var uuid = response.Headers.GetValues("Location").FirstOrDefault();
                    sfResponse.ModelId    = uuid;
                    sfResponse.StatusCode = response.StatusCode;
                    sfResponse.Message    = response.ReasonPhrase;
                    request.ModelId       = uuid;
                    _logger.LogInformation("Uploading is complete. Model uuid is " + uuid);
                }
                else
                {
                    _logger.LogError($"Error in Sketchfab upload: {response.StatusCode} {response.ReasonPhrase}");
                    sfResponse.StatusCode = response.StatusCode;
                    sfResponse.Message    = response.ReasonPhrase;
                }

                return(sfResponse);
            }
            catch (Exception ex)
            {
                _logger.LogError($"Sketchfab upload error: {ex.Message}");
                throw;
            }
        }
Beispiel #11
0
        public bool AttachResources(oM.Inspection.Issue bhomIssue, string tdrepoIssueId, PushConfig pushConfig, bool raiseErrors = true)
        {
            bool success = true;

            if (!bhomIssue.Media?.Any() ?? true)
            {
                return(true);
            }

            CheckMediaPath(pushConfig);

            // // - The media needs to be attached as a "Resource" of the issue.
            // // - This requires a MultipartFormData request. See https://3drepo.github.io/3drepo.io/#api-Issues-attachResource
            using (HttpClient httpClient = new HttpClient())
            {
                string issueResourceEndpoint = $"{m_host}/{m_teamspace}/{m_modelId}/issues/{tdrepoIssueId}/resources?key={m_userAPIKey}";

                foreach (string mediaPath in bhomIssue.Media)
                {
                    // Remember that BHoMIssues have media attached as a partial file path.
                    string fullMediaPath = System.IO.Path.Combine(pushConfig.MediaDirectory ?? "C:\\temp\\", mediaPath);
                    var    f             = System.IO.File.OpenRead(fullMediaPath);

                    StreamContent            imageContent = new StreamContent(f);
                    MultipartFormDataContent mpcontent    = new MultipartFormDataContent();
                    mpcontent.Add(imageContent, "file", mediaPath);
                    StringContent nameContent = new StringContent(Path.GetFileNameWithoutExtension(mediaPath));
                    mpcontent.Add(nameContent, "names");

                    // POST request
                    HttpResponseMessage respMessage = null;
                    try
                    {
                        respMessage = httpClient.PostAsync(issueResourceEndpoint, mpcontent).Result;
                    }
                    catch (AggregateException e)
                    {
                        string errors = $"Error(s) attaching multiple resources (media) for issue `{tdrepoIssueId}` named `{bhomIssue.Name}`:";

                        foreach (var innerException in e.Flatten().InnerExceptions)
                        {
                            errors += $"\n\t{innerException.Message}\n{innerException.InnerException}";
                        }

                        if (raiseErrors)
                        {
                            BH.Engine.Reflection.Compute.RecordError(errors);
                        }

                        return(false);
                    }
                    finally
                    {
                        f.Close();
                    }

                    // Process response
                    string fullResponse = respMessage?.Content.ReadAsStringAsync().Result;

                    if (respMessage != null && !respMessage.IsSuccessStatusCode)
                    {
                        fullResponse = fullResponse.GetResponseBody();

                        BH.Engine.Reflection.Compute.RecordWarning($"While attaching multiple resources (media) for issue `{tdrepoIssueId}` named `{bhomIssue.Name}`," +
                                                                   $"\nthe server returned a '{respMessage.StatusCode}' error for media `{mediaPath}`:\n ==>" + fullResponse);
                        success = false;
                    }
                }
            }

            return(success);
        }
Beispiel #12
0
        public static async Task <byte[]> postWrapper(List <string> qparams, List <Tuple <byte[], string, string> > files, string controller, HttpClient client)
        {
            var message = new HttpRequestMessage();
            var content = new MultipartFormDataContent();

            // build the qparams
            string urlParams = "";

            for (int i = 0; i < qparams.Count; i += 2)
            {
                String elem = $"{qparams[i]}={qparams[i + 1]}";
                if (i == 0)
                {
                    urlParams += elem;
                }
                else
                {
                    urlParams += $"&{elem}";
                }
            }

            string uriAddon = $"{controller}";

            if (urlParams != "")
            {
                uriAddon += $"?{urlParams}";
            }

            MemoryStream[] ms = new MemoryStream[files.Count];
            try
            {
                // prepare memoryStreams for file uploads
                for (int i = 0; i < files.Count; i++)
                {
                    ms[i] = new MemoryStream(files[i].Item1);
                    int temp = i + 1;
                    content.Add(new StreamContent(ms[i]), files[i].Item2, files[i].Item3);
                }

                // prepare request
                message.Method     = HttpMethod.Post;
                message.Content    = content;
                message.RequestUri = new Uri($"{client.BaseAddress.AbsoluteUri}{uriAddon}");

                // send request
                var res = await client.SendAsync(message).ConfigureAwait(false);

                // check response
                int statusCode = (int)res.StatusCode;
                if (statusCode == 500)
                {
                    var error_message = await res.Content.ReadAsStringAsync();

                    throw new Pdf4meBackendException($"HTTP 500: {res.ReasonPhrase} : {error_message}");
                }
                else if (statusCode != 200 && statusCode != 204)
                {
                    var error_message = await res.Content.ReadAsStringAsync();

                    throw new Pdf4meBackendException($"HTTP {statusCode}: {res.ReasonPhrase}: {error_message}");
                }

                // extract response
                return(await res.Content.ReadAsByteArrayAsync());
            }
            finally
            {
                // Dispose of all MemoryStreams
                for (int i = 0; i < ms.Length; i++)
                {
                    if (ms[i] != null)
                    {
                        ms[i].Dispose();
                    }
                }
            }
        }
        private static bool SendCrashDump(string path, string name)
        {
            // Get machine UUID or generate one if not valid
            string uuidString = Api.IcepickRegistry.ReadMachineUUID();

            Guid uuid;

            if (!Guid.TryParse(uuidString, out uuid))
            {
                uuid       = Guid.NewGuid();
                uuidString = uuid.ToString();
                Api.IcepickRegistry.WriteMachineUUID(uuidString);
            }

            // Attempt to get version from TTF2SDK.dll
            string versionString = "unknown";

            try
            {
                FileVersionInfo sdkVersionInfo = FileVersionInfo.GetVersionInfo(Mods.SDKInjector.SDKDllName);
                if (sdkVersionInfo.Comments != "")
                {
                    versionString = sdkVersionInfo.Comments;
                }
            }
            catch (Exception) { }

            // Get memory information
            ulong          totalMemory = 0;
            ulong          freeMemory  = 0;
            MEMORYSTATUSEX memStatus   = new MEMORYSTATUSEX();

            if (GlobalMemoryStatusEx(memStatus))
            {
                totalMemory = memStatus.ullTotalPhys;
                freeMemory  = memStatus.ullAvailPhys;
            }

            // Get disk space information
            string rootPath    = Path.GetPathRoot(AppDomain.CurrentDomain.BaseDirectory);
            ulong  freeStorage = 0;
            ulong  storageSize = 0;
            ulong  dummy;

            GetDiskFreeSpaceEx(rootPath, out freeStorage, out storageSize, out dummy);

            // Get a handle on the file
            FileStream stream = null;

            for (int i = 0; i < 10; i++)
            {
                try
                {
                    stream = new FileStream(path, FileMode.Open, FileAccess.Read);
                    break;
                }
                catch (IOException)
                {
                    System.Threading.Thread.Sleep(500);
                }
            }

            if (stream == null)
            {
                return(false);
            }

            // Send request to sentry
            HttpContent memorySizeParam   = new StringContent(totalMemory.ToString());
            HttpContent freeMemoryParam   = new StringContent(freeMemory.ToString());
            HttpContent storageSizeParam  = new StringContent(storageSize.ToString());
            HttpContent freeStorageParam  = new StringContent(freeStorage.ToString());
            HttpContent sdkNameParam      = new StringContent("Icepick");
            HttpContent sdkVersionParam   = new StringContent(Version.Current);
            HttpContent releaseParam      = new StringContent(versionString);
            HttpContent userIdParam       = new StringContent(uuidString);
            HttpContent fileStreamContent = new StreamContent(stream);

            using (var client = new HttpClient())
            {
                using (var formData = new MultipartFormDataContent())
                {
                    formData.Add(memorySizeParam, "sentry[contexts][device][memory_size]");
                    formData.Add(freeMemoryParam, "sentry[contexts][device][free_memory]");
                    formData.Add(storageSizeParam, "sentry[contexts][device][storage_size]");
                    formData.Add(freeStorageParam, "sentry[contexts][device][free_storage]");
                    formData.Add(sdkNameParam, "sentry[sdk][name]");
                    formData.Add(sdkVersionParam, "sentry[sdk][version]");
                    formData.Add(releaseParam, "sentry[release]");
                    formData.Add(userIdParam, "sentry[user][id]");
                    formData.Add(fileStreamContent, "upload_file_minidump", name);

                    var task = client.PostAsync(SentryEndpoint, formData);
                    task.Wait();
                    return(task.Result.StatusCode == System.Net.HttpStatusCode.OK);
                }
            }
        }
Beispiel #14
0
        /// <summary>
        /// Request install to package manager
        /// </summary>
        /// <param name="device">Jedi device</param>
        /// <param name="hpkfile">Hpk file information</param>
        /// <returns></returns>
        public bool InstallPackage(JediDevice device, HpkFileInfo hpkfile)
        {
            Uri install_packages_uri = new Uri($"https://{device.Address}/hp/device/webservices/ext/pkgmgt/installer/install?clientId=ciJamc&installSource=isStandardRepository&forceInstall=true&acceptPermissions=true");

            ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };
            HttpClientHandler httphandler = new HttpClientHandler();

            httphandler.Credentials     = new NetworkCredential("admin", device.AdminPassword);
            httphandler.PreAuthenticate = true;
            var client = new HttpClient(httphandler);

            client.Timeout = TimeSpan.FromSeconds(110);
            client.DefaultRequestHeaders.ExpectContinue = false;
            client.DefaultRequestHeaders.Connection.Clear();
            client.DefaultRequestHeaders.ConnectionClose = true;  // true = keepalive off

            ByteArrayContent fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(hpkfile.FilePath));

            fileContent.Headers.ContentDisposition          = new ContentDispositionHeaderValue("form-data");
            fileContent.Headers.ContentDisposition.Name     = "\"file\"";
            fileContent.Headers.ContentDisposition.FileName = "\"" + hpkfile.PackageName + "\"";
            fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.hp.package-archive");

            MultipartFormDataContent content = new MultipartFormDataContent();

            content.Add(fileContent);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, install_packages_uri);

            request.Content = content;

            try
            {
                using (HttpResponseMessage message = client.SendAsync(request).Result)
                {
                    //string s = message.Content.ReadAsStringAsync().Result;
                    string s = message.Headers.Location.ToString();
                    if (s.Contains(hpkfile.Uuid))
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
            }

            catch (WebException ex)
            {
                Logger.LogError(ex.Message + $"Device : {device.Address}");
                return(false);
            }

            catch (HttpRequestException ex)
            {
                Logger.LogError(ex.Message + $"Device : {device.Address}");
                return(false);
            }

            catch (SocketException ex)
            {
                Logger.LogError(ex.Message + $"Device : {device.Address}");
                return(false);
            }

            catch (AggregateException ex)
            {
                Logger.LogError(ex.Message + $"Device : {device.Address}");
                return(false);
            }

            catch (Exception ex)
            {
                Logger.LogError($"InstallPackage Error : {hpkfile.PackageName}, {ex.Message}");
                _failedSettings.AppendLine($"InstallPackage Error: {hpkfile.PackageName}, {ex.Message}");
                throw ex;
            }
        }
        public async Task Serialize_InvalidNamedFileName_Encoded()
        {
            var content = new MultipartFormDataContent("test_boundary");
            content.Add(new StringContent("Hello World"), "testク\r\n namé", "fileク\r\n namé");

            MemoryStream output = new MemoryStream();
            await content.CopyToAsync(output);

            output.Seek(0, SeekOrigin.Begin);
            string result = new StreamReader(output).ReadToEnd();

            Assert.Equal(
                "--test_boundary\r\nContent-Type: text/plain; charset=utf-8\r\n"
                + "Content-Disposition: form-data; name=\"=?utf-8?B?dGVzdOOCrw0KIG5hbcOp?=\";"
                + " filename=\"=?utf-8?B?ZmlsZeOCrw0KIG5hbcOp?=\"; filename*=utf-8\'\'file%E3%82%AF%0D%0A%20nam%C3%A9" 
                + "\r\n\r\nHello World\r\n--test_boundary--\r\n",
                result);
        }
Beispiel #16
0
 /// <summary>
 /// このユーザーからAPIにリクエストします。
 /// </summary>
 /// <param name="endpoint">エンドポイント名</param>
 /// <param name="ps">パラメーター</param>
 /// <returns>レスポンス</returns>
 public async Task <dynamic> RequestWithBinary(string endpoint, MultipartFormDataContent ps)
 {
     ps.Add(new StringContent(this.Token), "i");
     return(await Core.RequestWithBinary(this.Host, endpoint, ps));
 }
 public void Add_NullName_ThrowsArgumentException()
 {
     var content = new MultipartFormDataContent();
     Assert.Throws<ArgumentException>(() => content.Add(new StringContent("Hello world"), null));
 }
        static async Task <Result> send_eligibility_request(string path, string filename, string accountkey)
        {
            string     url = "https://www.claim.md/services/elig/";
            HttpClient c   = new HttpClient();

            byte[] file_bytes = File.ReadAllBytes(path);

            // build request
            var accountKeyContent = new StringContent(accountkey);

            accountKeyContent.Headers.Add("Content-Disposition", "form-data; name=\"AccountKey\"");

            var fileContent = new ByteArrayContent(file_bytes);

            fileContent.Headers.Add("Content-Disposition", $"form-data; name=\"File\"; filename=\"{filename}\"");
            fileContent.Headers.Add("Content-Type", "text/plain");

            MultipartFormDataContent content = new MultipartFormDataContent();

            content.Add(accountKeyContent);
            content.Add(fileContent);
            using (var response = await c.PostAsync(url, content))
            {
                {
                    //Console.WriteLine("waiting on response");
                    string resultString = await response.Content.ReadAsStringAsync();

                    Console.WriteLine("-----");
                    Console.WriteLine(resultString);
                    Console.WriteLine("-----");
                    Result result = new Result();
                    using (StringReader sr = new StringReader(resultString))
                    {
                        XmlTextReader xmlReader = new XmlTextReader(sr);
                        while (xmlReader.Read())
                        {
                            if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "result"))
                            {
                                if (xmlReader.HasAttributes)
                                {
                                    //Console.WriteLine(xmlReader.GetAttribute("messages"));
                                    Console.WriteLine("found result");
                                    result.Messages = xmlReader.GetAttribute("messages");
                                }
                            }

                            if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "error"))
                            {
                                if (xmlReader.HasAttributes)
                                {
                                    result.Error            = new Error();
                                    result.Error.ErrorCode  = xmlReader.GetAttribute("error_code");
                                    result.Error.Error_Mesg = xmlReader.GetAttribute("error_mesg");
                                }
                            }

                            if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "eligibility"))
                            {
                                if (xmlReader.HasAttributes)
                                {
                                    result.Eligibility        = new Eligibility();
                                    result.Eligibility.Data   = xmlReader.GetAttribute("data");
                                    result.Eligibility.EligId = xmlReader.GetAttribute("eligid");
                                }
                            }
                        }
                        return(result);
                    }
                }
            }
        }
Beispiel #19
0
        public static Result <Message> sendVideo(long chat_id, Stream content, string fileName, string caption, string parse_mode = "markdown",
                                                 int duration = 0, int width = 0, int height = 0, string thumb = "", bool supports_streaming = false,
                                                 bool disable_notification = false, int reply_to_message_id = 0, InlineKeyboardMarkup keyboard = null)

        {
            using (MultipartFormDataContent form = new MultipartFormDataContent())
            {
                form.Add(new StringContent(chat_id.ToString(), Encoding.UTF8), "chat_id");
                fileName = fileName ?? "video";
                string      contentDisposision = $@"form-data; name=""video""; filename=""{fileName}""";
                HttpContent mediaPartContent   = new StreamContent(content)
                {
                    Headers =
                    {
                        { "Content-Type",        "application/octet-stream" },
                        { "Content-Disposition", contentDisposision         }
                    }
                };

                form.Add(mediaPartContent, "video");
                if (duration != 0)
                {
                    form.Add(new StringContent(duration.ToString(), Encoding.UTF8), "duration");
                }
                if (width != 0)
                {
                    form.Add(new StringContent(width.ToString(), Encoding.UTF8), "width");
                }
                if (height != 0)
                {
                    form.Add(new StringContent(height.ToString(), Encoding.UTF8), "height");
                }
                if (caption != null)
                {
                    form.Add(new StringContent(caption.ToString(), Encoding.UTF8), "caption");
                }
                if (!string.IsNullOrEmpty(thumb))
                {
                    form.Add(new StringContent(thumb.ToString(), Encoding.UTF8), "thumb");
                }
                if (parse_mode != null)
                {
                    form.Add(new StringContent(parse_mode.ToString(), Encoding.UTF8), "parse_mode");
                }
                if (supports_streaming)
                {
                    form.Add(new StringContent(supports_streaming.ToString(), Encoding.UTF8), "supports_streaming");
                }
                if (disable_notification)
                {
                    form.Add(new StringContent(disable_notification.ToString(), Encoding.UTF8), "disable_notification");
                }
                if (reply_to_message_id != 0)
                {
                    form.Add(new StringContent(reply_to_message_id.ToString(), Encoding.UTF8), "reply_to_message_id");
                }
                if (keyboard != null)
                {
                    form.Add(new StringContent(buildRequest <InlineKeyboardMarkup>(keyboard), Encoding.UTF8), "reply_markup");
                }
                Result <Message> result = sendRequest <Message>(Method.sendVideo, "", "", form);
                return(result);
            }
        }
        /// <inheritdoc />
        public override HttpContent GetHttpContent()
        {
            // Save & restore the stream position on each GetHttpContent call.
            switch (status)
            {
            case STATUS_CREATED:
                IDictionary <Stream, long>?sps = null;
                foreach (var p in fields)
                {
                    if (p.Value is Stream s)
                    {
                        if (s.CanSeek)
                        {
                            if (sps == null)
                            {
                                sps = new Dictionary <Stream, long>();
                            }
                            sps[s] = s.Position;
                        }
                        else
                        {
                            status = STATUS_UNRECOVERABLE;
                            goto MAIN;
                        }
                    }
                }
                streamPositions = sps;
                status          = STATUS_RECOVERABLE;
                break;

            case STATUS_RECOVERABLE:
                sps = streamPositions;
                if (sps != null)
                {
                    foreach (var p in fields)
                    {
                        if (p.Value is Stream s)
                        {
                            s.Position = sps[s];
                        }
                    }
                }
                break;

            case STATUS_UNRECOVERABLE:
                throw new InvalidOperationException(Prompts.ExceptionMediaWikiFormCannotRecoverState);
            }
MAIN:
            if (AsMultipartFormData)
            {
                var content = new MultipartFormDataContent();
                foreach (var p in fields)
                {
                    switch (p.Value)
                    {
                    case string s:
                        content.Add(new StringContent(s), p.Key);
                        break;

                    case Stream stream:
                        content.Add(new StreamContent(stream), p.Key, "dummy");
                        break;

                    case null:
                        // Ignore null entries.
                        break;

                    default:
                        var stringValue = Utility.ToWikiQueryValue(p.Value);
                        if (stringValue != null)
                        {
                            content.Add(new StringContent(stringValue), p.Key);
                        }
                        break;
                    }
                }
                return(content);
            }
            else
            {
                return(new FormLongUrlEncodedContent(Utility.ToWikiStringValuePairs(fields)
                                                     .Where(p => p.Value != null)));
            }
        }
        public MainPageViewModel(INavigationService navigationService, IPageDialogService dialogService)
        {
            this.navigationService = navigationService;
            this.dialogService     = dialogService;
            TakePhotoCommand       = new DelegateCommand(async() =>
            {
                // 進行 Plugin.Media 套件的初始化動作
                await Plugin.Media.CrossMedia.Current.Initialize();

                // 確認這個裝置是否具有拍照的功能
                if (!Plugin.Media.CrossMedia.Current.IsCameraAvailable || !Plugin.Media.CrossMedia.Current.IsTakePhotoSupported)
                {
                    await dialogService.DisplayAlertAsync("No Camera", ":( No camera available.", "OK");
                    return;
                }

                // 啟動拍照功能,並且儲存到指定的路徑與檔案中
                var file = await Plugin.Media.CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
                {
                    Directory = "Sample",
                    Name      = "Sample.jpg",
                    //CompressionQuality = 90,
                    //PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,
                    //DefaultCamera = Plugin.Media.Abstractions.CameraDevice.Rear,
                });

                if (file == null)
                {
                    return;
                }

                imagePath = file.Path;

                // 讀取剛剛拍照的檔案內容,轉換成為 ImageSource,如此,就可以顯示到螢幕上了
                MyImageSource = ImageSource.FromStream(() =>
                {
                    var stream = file.GetStream();
                    file.Dispose();
                    return(stream);
                });
            });
            UploadPhotoCommand = new DelegateCommand(async() =>
            {
                UploadImageUrl = "";
                // 取得剛剛拍照完成的照片檔案名稱與完整路徑名稱
                string fileName      = Path.GetFileName(imagePath);
                string imageFileName = imagePath;

                // 建立 HttpClient 物件
                HttpClient client = new HttpClient();
                string url        = $"http://lobworkshop.azurewebsites.net/api/UploadImage";
                #region 將圖片檔案,上傳到網路伺服器上(使用 Multipart 的規範)
                // 規格說明請參考 https://www.w3.org/Protocols/rfc1341/7_2_Multipart.html

                //建立 MultipartFormDataContent 物件,並把圖片檔案 Stream 放入 StreamContent 物件
                using (var content = new MultipartFormDataContent())
                {
                    // 開啟這個圖片檔案,並且讀取其內容
                    using (var fs = File.Open(imageFileName, FileMode.Open))
                    {
                        var streamContent = new StreamContent(fs);
                        streamContent.Headers.Add("Content-Type", "application/octet-stream");
                        streamContent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"" + fileName + "\"");
                        content.Add(streamContent, "file", fileName);

                        // 上傳到遠端伺服器上
                        HttpResponseMessage response = await client.PostAsync(url, content);

                        if (response != null)
                        {
                            if (response.IsSuccessStatusCode == true)
                            {
                                // 取得呼叫完成 API 後的回報內容
                                String strResult    = await response.Content.ReadAsStringAsync();
                                APIResult apiResult = JsonConvert.DeserializeObject <APIResult>(strResult, new JsonSerializerSettings {
                                    MetadataPropertyHandling = MetadataPropertyHandling.Ignore
                                });
                                if (apiResult?.Status == true)
                                {
                                    // 得到上傳圖片 API 回傳內容
                                    UploadImageResponseDTO uploadImageResponseDTO = JsonConvert.DeserializeObject <UploadImageResponseDTO>(apiResult.Payload.ToString());
                                    UploadImageUrl = uploadImageResponseDTO.ImageUrl;
                                }
                            }
                        }
                    }
                }
                #endregion
            });
        }
        public static IEnumerable <object[]> PostAsync_Cancel_CancellationTokenPassedToContent_MemberData()
        {
            // Note: For HTTP2, the actual token will be a linked token and will not be an exact match for the original token.
            // Verify that it behaves as expected by cancelling it and validating that cancellation propagates.

            // StreamContent
            {
                CancellationTokenSource tokenSource = new CancellationTokenSource();
                var  actualToken = new StrongBox <CancellationToken>();
                bool called      = false;
                var  content     = new StreamContent(new DelegateStream(
                                                         canReadFunc: () => true,
                                                         readAsyncFunc: (buffer, offset, count, cancellationToken) =>
                {
                    int result = 1;
                    if (called)
                    {
                        result = 0;
                        Assert.False(cancellationToken.IsCancellationRequested);
                        tokenSource.Cancel();
                        Assert.True(cancellationToken.IsCancellationRequested);
                    }

                    called = true;
                    return(Task.FromResult(result));
                }
                                                         ));
                yield return(new object[] { content, tokenSource });
            }

            // MultipartContent
            {
                CancellationTokenSource tokenSource = new CancellationTokenSource();
                var  actualToken = new StrongBox <CancellationToken>();
                bool called      = false;
                var  content     = new MultipartContent();
                content.Add(new StreamContent(new DelegateStream(
                                                  canReadFunc: () => true,
                                                  canSeekFunc: () => true,
                                                  lengthFunc: () => 1,
                                                  positionGetFunc: () => 0,
                                                  positionSetFunc: _ => {},
                                                  readAsyncFunc: (buffer, offset, count, cancellationToken) =>
                {
                    int result = 1;
                    if (called)
                    {
                        result = 0;
                        Assert.False(cancellationToken.IsCancellationRequested);
                        tokenSource.Cancel();
                        Assert.True(cancellationToken.IsCancellationRequested);
                    }

                    called = true;
                    return(Task.FromResult(result));
                }
                                                  )));
                yield return(new object[] { content, tokenSource });
            }

            // MultipartFormDataContent
            {
                CancellationTokenSource tokenSource = new CancellationTokenSource();
                var  actualToken = new StrongBox <CancellationToken>();
                bool called      = false;
                var  content     = new MultipartFormDataContent();
                content.Add(new StreamContent(new DelegateStream(
                                                  canReadFunc: () => true,
                                                  canSeekFunc: () => true,
                                                  lengthFunc: () => 1,
                                                  positionGetFunc: () => 0,
                                                  positionSetFunc: _ => {},
                                                  readAsyncFunc: (buffer, offset, count, cancellationToken) =>
                {
                    int result = 1;
                    if (called)
                    {
                        result = 0;
                        Assert.False(cancellationToken.IsCancellationRequested);
                        tokenSource.Cancel();
                        Assert.True(cancellationToken.IsCancellationRequested);
                    }

                    called = true;
                    return(Task.FromResult(result));
                }
                                                  )));
                yield return(new object[] { content, tokenSource });
            }
        }
        private async Task <HttpResponseMessage> HttpResponseMessage(
            HttpRequest request,
            CancellationToken cancellationToken)
        {
            var queryBuilder = new StringBuilder(request.QueryUrl);

            if (request.QueryParameters != null)
            {
                ApiHelper.AppendUrlWithQueryParameters(queryBuilder, request.QueryParameters, this.arrayDeserializationFormat, parameterSeparator);
            }

            // validate and preprocess url.
            string queryUrl = ApiHelper.CleanUrl(queryBuilder);

            HttpRequestMessage requestMessage = new HttpRequestMessage
            {
                RequestUri = new Uri(queryUrl),
                Method     = request.HttpMethod,
            };

            if (request.Headers != null)
            {
                foreach (var headers in request.Headers)
                {
                    requestMessage.Headers.TryAddWithoutValidation(headers.Key, headers.Value);
                }
            }

            if (!string.IsNullOrEmpty(request.Username))
            {
                var byteArray = Encoding.UTF8.GetBytes(request.Username + ":" + request.Password);
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue(
                    "Basic",
                    Convert.ToBase64String(byteArray));
            }

            if (request.HttpMethod.Equals(HttpMethod.Delete) || request.HttpMethod.Equals(HttpMethod.Post) || request.HttpMethod.Equals(HttpMethod.Put) || request.HttpMethod.Equals(new HttpMethod("PATCH")))
            {
                bool multipartRequest = request.FormParameters != null &&
                                        (request.FormParameters.Any(f => f.Value is MultipartContent) || request.FormParameters.Any(f => f.Value is FileStreamInfo));

                if (request.Body != null)
                {
                    if (request.Body is FileStreamInfo file)
                    {
                        file.FileStream.Position = 0;
                        requestMessage.Content   = new StreamContent(file.FileStream);
                        if (!string.IsNullOrWhiteSpace(file.ContentType))
                        {
                            requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(file.ContentType);
                        }
                        else if (request.Headers.Any(h => h.Key.Equals("content-type", StringComparison.OrdinalIgnoreCase)))
                        {
                            requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(
                                request.Headers.First(h =>
                                                      h.Key.Equals("content-type", StringComparison.OrdinalIgnoreCase)).Value);
                        }
                        else
                        {
                            requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                        }
                    }
                    else if (request.Headers.ContainsKey("content-type") && string.Equals(
                                 request.Headers["content-type"],
                                 "application/json; charset=utf-8",
                                 StringComparison.OrdinalIgnoreCase))
                    {
                        requestMessage.Content = new StringContent((string)request.Body ?? string.Empty, Encoding.UTF8, "application/json");
                    }
                    else if (request.Headers.ContainsKey("content-type"))
                    {
                        byte[] bytes = null;

                        if (request.Body is Stream)
                        {
                            Stream s = (Stream)request.Body;
                            s.Position = 0;
                            using (BinaryReader br = new BinaryReader(s))
                            {
                                bytes = br.ReadBytes((int)s.Length);
                            }
                        }
                        else if (request.Body is byte[])
                        {
                            bytes = (byte[])request.Body;
                        }
                        else
                        {
                            bytes = Encoding.UTF8.GetBytes((string)request.Body);
                        }

                        requestMessage.Content = new ByteArrayContent(bytes ?? Array.Empty <byte>());

                        try
                        {
                            requestMessage.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(request.Headers["content-type"]);
                        }
                        catch (Exception)
                        {
                            requestMessage.Content.Headers.TryAddWithoutValidation("content-type", request.Headers["content-type"]);
                        }
                    }
                    else
                    {
                        requestMessage.Content = new StringContent(request.Body.ToString() ?? string.Empty, Encoding.UTF8, "text/plain");
                    }
                }
                else if (multipartRequest)
                {
                    MultipartFormDataContent formContent = new MultipartFormDataContent();

                    foreach (var param in request.FormParameters)
                    {
                        if (param.Value is FileStreamInfo fileParam)
                        {
                            var fileContent = new MultipartFileContent(fileParam);
                            fileContent.Rewind();
                            formContent.Add(fileContent.ToHttpContent(param.Key));
                        }
                        else if (param.Value is MultipartContent wrapperObject)
                        {
                            wrapperObject.Rewind();
                            formContent.Add(wrapperObject.ToHttpContent(param.Key));
                        }
                        else
                        {
                            formContent.Add(new StringContent(param.Value.ToString()), param.Key);
                        }
                    }

                    requestMessage.Content = formContent;
                }
                else if (request.FormParameters != null)
                {
                    var parameters = new List <KeyValuePair <string, string> >();
                    foreach (var param in request.FormParameters)
                    {
                        parameters.Add(new KeyValuePair <string, string>(param.Key, param.Value.ToString()));
                    }

                    requestMessage.Content = new FormUrlEncodedContent(parameters);
                }
            }

            return(await this.client.SendAsync(requestMessage, cancellationToken).ConfigureAwait(false));
        }
Beispiel #24
0
        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)}");
            }

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

                if (string.IsNullOrEmpty(sessionId))
                {
                    request =
                        RepositoryClient.WithAuthentication(ApiKeys.SpeechToTextUsername, ApiKeys.SpeechToTextPassword)
                        .PostAsync($"{ApiKeys.SpeechToTextEndpoint}{recognizeUrl}");
                }
                else
                {
                    request =
                        RepositoryClient.WithAuthentication(ApiKeys.SpeechToTextUsername, ApiKeys.SpeechToTextPassword)
                        .PostAsync($"{ApiKeys.SpeechToTextEndpoint}{sessionsUrl}{sessionId}/{recognizeUrl}")
                        .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);
                }

                var result =
                    request.As <SpeechRecognitionEvent>()
                    .Result;

                return(result);
            }
            catch (AggregateException ae)
            {
                throw ae.InnerException as ServiceResponseException;
            }
        }
        /// <summary>
        /// Analyze images.
        ///
        /// Analyze images by URL, by file, or both against your own collection. Make sure that
        /// **training_status.objects.ready** is `true` for the feature before you use a collection to analyze images.
        ///
        /// Encode the image and .zip file names in UTF-8 if they contain non-ASCII characters. The service assumes
        /// UTF-8 encoding if it encounters non-ASCII characters.
        /// </summary>
        /// <param name="collectionIds">The IDs of the collections to analyze.</param>
        /// <param name="features">The features to analyze.</param>
        /// <param name="imagesFile">An array of image files (.jpg or .png) or .zip files with images.
        /// - Include a maximum of 20 images in a request.
        /// - Limit the .zip file to 100 MB.
        /// - Limit each image file to 10 MB.
        ///
        /// You can also include an image with the **image_url** parameter. (optional)</param>
        /// <param name="imageUrl">An array of URLs of image files (.jpg or .png).
        /// - Include a maximum of 20 images in a request.
        /// - Limit each image file to 10 MB.
        /// - Minimum width and height is 30 pixels, but the service tends to perform better with images that are at
        /// least 300 x 300 pixels. Maximum is 5400 pixels for either height or width.
        ///
        /// You can also include images with the **images_file** parameter. (optional)</param>
        /// <param name="threshold">The minimum score a feature must have to be returned. (optional)</param>
        /// <returns><see cref="AnalyzeResponse" />AnalyzeResponse</returns>
        public DetailedResponse <AnalyzeResponse> Analyze(List <string> collectionIds, List <string> features, List <FileWithMetadata> imagesFile = null, List <string> imageUrl = null, float?threshold = null)
        {
            if (collectionIds == null || collectionIds.Count == 0)
            {
                throw new ArgumentNullException("`collectionIds` is required for `Analyze`");
            }
            if (features == null || features.Count == 0)
            {
                throw new ArgumentNullException("`features` is required for `Analyze`");
            }

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

            DetailedResponse <AnalyzeResponse> result = null;

            try
            {
                var formData = new MultipartFormDataContent();

                if (collectionIds != null)
                {
                    var collectionIdsContent = new StringContent(string.Join(",", collectionIds.ToArray()), Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    collectionIdsContent.Headers.ContentType = null;
                    formData.Add(collectionIdsContent, "collection_ids");
                }

                if (features != null)
                {
                    var featuresContent = new StringContent(string.Join(",", features.ToArray()), Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    featuresContent.Headers.ContentType = null;
                    formData.Add(featuresContent, "features");
                }

                if (imagesFile != null)
                {
                    foreach (FileWithMetadata item in imagesFile)
                    {
                        var imagesFileContent = new ByteArrayContent(item.Data.ToArray());
                        System.Net.Http.Headers.MediaTypeHeaderValue contentType;
                        System.Net.Http.Headers.MediaTypeHeaderValue.TryParse(item.ContentType, out contentType);
                        imagesFileContent.Headers.ContentType = contentType;
                        formData.Add(imagesFileContent, "images_file", item.Filename);
                    }
                }

                if (imageUrl != null)
                {
                    foreach (string item in imageUrl)
                    {
                        var imageUrlContent = new StringContent(item, Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                        imageUrlContent.Headers.ContentType = null;
                        formData.Add(imageUrlContent, "image_url");
                    }
                }

                if (threshold != null)
                {
                    var thresholdContent = new StringContent(threshold.ToString(), Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    thresholdContent.Headers.ContentType = null;
                    formData.Add(thresholdContent, "threshold");
                }

                IClient client = this.Client;
                SetAuthentication();

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

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");
                restRequest.WithBodyContent(formData);

                restRequest.WithHeaders(Common.GetSdkHeaders("watson_vision_combined", "v4", "Analyze"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

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

            return(result);
        }
Beispiel #26
0
        /// <summary>
        /// Gets access token
        /// </summary>
        /// <param name='clientId'>
        /// </param>
        /// <param name='clientSecret'>
        /// </param>
        /// <param name='grantType'>
        /// </param>
        /// <param name='scope'>
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="HttpOperationException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <AccessToken> > PostWithHttpMessagesAsync(string clientId = default(string), string clientSecret = default(string), string grantType = default(string), string scope = default(string), Dictionary <string, List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("clientId", clientId);
                tracingParameters.Add("clientSecret", clientSecret);
                tracingParameters.Add("grantType", grantType);
                tracingParameters.Add("scope", scope);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Post", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/auth/oauth/token").ToString();
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            MultipartFormDataContent _multiPartContent = new MultipartFormDataContent();

            if (clientId != null)
            {
                StringContent _clientId = new StringContent(clientId, System.Text.Encoding.UTF8);
                _multiPartContent.Add(_clientId, "client_id");
            }
            if (clientSecret != null)
            {
                StringContent _clientSecret = new StringContent(clientSecret, System.Text.Encoding.UTF8);
                _multiPartContent.Add(_clientSecret, "client_secret");
            }
            if (grantType != null)
            {
                StringContent _grantType = new StringContent(grantType, System.Text.Encoding.UTF8);
                _multiPartContent.Add(_grantType, "grant_type");
            }
            if (scope != null)
            {
                StringContent _scope = new StringContent(scope, System.Text.Encoding.UTF8);
                _multiPartContent.Add(_scope, "scope");
            }
            _httpRequest.Content = _multiPartContent;
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200 && (int)_statusCode != 500)
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                if (_httpResponse.Content != null)
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                else
                {
                    _responseContent = string.Empty;
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <AccessToken>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <AccessToken>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
        public static void PostUploadFile
        (
            string file
            , string url
            , Action
            <
                HttpClient
                , bool
                , HttpProgressEventArgs
            >
            onProgressProcessAction = null
            , bool reThrowException = false
            , Func <Exception, Exception, string, bool> onCaughtExceptionProcessFunc = null
            , Action <bool, Exception, Exception, string> onFinallyProcessAction     = null
            , int httpClientTimeOutInSeconds = 200
            , int bufferSize = 1024
        )
        {
            HttpClient httpClient = null;

            using
            (
                var httpClientHandler
                    = new HttpClientHandler()
            {
                UseDefaultCredentials = true
            }
            )
            {
                ProgressMessageHandler progressMessageHandler = null;
                if (onProgressProcessAction != null)
                {
                    progressMessageHandler = new ProgressMessageHandler(httpClientHandler);
                    progressMessageHandler
                    .HttpSendProgress
                        +=
                            (sender, httpProgressEventArgs) =>
                        {
                        onProgressProcessAction
                        (
                            httpClient
                            , true
                            , httpProgressEventArgs
                        );
                        };
                    progressMessageHandler
                    .HttpReceiveProgress
                        +=
                            (sender, httpProgressEventArgs) =>
                        {
                        onProgressProcessAction
                        (
                            httpClient
                            , false
                            , httpProgressEventArgs
                        );
                        };
                }
                using
                (
                    httpClient = new HttpClient(httpClientHandler)
                {
                    Timeout = TimeSpan
                              .FromSeconds
                              (
                        httpClientTimeOutInSeconds
                              )
                }
                )
                {
                    try
                    {
                        HttpResponseMessage response = null;
                        using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, true))
                        {
                            // Create a stream content for the file
                            StreamContent content = new StreamContent(fileStream, bufferSize);

                            // Create Multipart form data content, add our submitter data and our stream content
                            MultipartFormDataContent formData = new MultipartFormDataContent();
                            formData.Add(new StringContent("Me"), "submitter");
                            formData.Add(content, "filename", file);

                            // Post the MIME multipart form data upload with the file
                            Uri address = new Uri(url);
                            response = httpClient.PostAsync(address, formData).Result;

                            //FileResult result = await response.Content.ReadAsAsync<FileResult>();
                            //Console.WriteLine("{0}Result:{0}  Filename:  {1}{0}  Submitter: {2}", Environment.NewLine, result.FileNames.FirstOrDefault(), result.Submitter);
                        }



                        //Console.WriteLine("await ed");
                        response.EnsureSuccessStatusCode();
                    }
                    catch (Exception e)
                    {
                        var innerExceptionMessage = "Caught Exception";
                        var newException          = new Exception
                                                    (
                            innerExceptionMessage
                            , e
                                                    );
                        if (onCaughtExceptionProcessFunc != null)
                        {
                            reThrowException = onCaughtExceptionProcessFunc(e, newException, innerExceptionMessage);
                        }
                        if (reThrowException)
                        {
                            throw
                                newException;
                        }
                    }
                }
            }
        }
Beispiel #28
0
        private void PrepareRequestContent(ref HttpRequestMessage request, SortedDictionary <string, object> parameters, FileDescription file, Dictionary <string, string> extraHeaders = null)
        {
            //HttpRequestMessage req = (HttpRequestMessage) request;
            var content = new MultipartFormDataContent(HTTP_BOUNDARY);

            if (extraHeaders != null)
            {
                foreach (var header in extraHeaders)
                {
                    content.Headers.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            if (!parameters.ContainsKey("unsigned") || parameters["unsigned"].ToString() == "false")
            {
                FinalizeUploadParameters(parameters);
            }
            else
            {
                if (parameters.ContainsKey("removeUnsignedParam"))
                {
                    parameters.Remove("unsigned");
                    parameters.Remove("removeUnsignedParam");
                }
            }

            foreach (var param in parameters)
            {
                if (param.Value != null)
                {
                    if (param.Value is IEnumerable <string> )
                    {
                        foreach (var item in (IEnumerable <string>)param.Value)
                        {
                            content.Add(new StringContent(item), String.Format("\"{0}\"", string.Concat(param.Key, "[]")));
                        }
                    }
                    else
                    {
                        content.Add(new StringContent(param.Value.ToString()), String.Format("\"{0}\"", param.Key));
                    }
                }
            }

            if (file != null)
            {
                if (file.IsRemote && file.Stream == null)
                {
                    StringContent strContent = new StringContent(file.FilePath);
                    strContent.Headers.Add("Content-Disposition", string.Format("form-data; name=\"{0}\"", "file"));
                    content.Add(strContent);
                }
                else
                {
                    Stream stream = null;

                    if (file.Stream != null)
                    {
                        stream = file.Stream;
                    }
                    else
                    {
                        stream = File.OpenRead(file.FilePath);
                    }

                    string fileName = string.IsNullOrWhiteSpace(file.FilePath) ? file.FileName : Path.GetFileName(file.FilePath);

                    var streamContent = new StreamContent(stream);
                    streamContent.Headers.Add("Content-Type", "application/octet-stream");
                    streamContent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"" + fileName + "\"");
                    content.Add(streamContent, "file", fileName);
                }
            }

            request.Content = content;
        }
        private async Task <bool> sendToApi()
        {
            try
            {
                string isAgeshow, isDistanceShow;
                var    client = new HttpClient();
                var    form   = new MultipartFormDataContent();
                MultipartFormDataContent content = new MultipartFormDataContent();
                content.Add(new StringContent(userModel.id), "id");

                if (!string.IsNullOrWhiteSpace(aboutEntry.Text))
                {
                    content.Add(new StringContent(userModel.about), "about");
                }
                if (!string.IsNullOrWhiteSpace(schoolEntry.Text))
                {
                    content.Add(new StringContent(userModel.school), "school");
                }
                if (!string.IsNullOrWhiteSpace(companyEntry.Text))
                {
                    content.Add(new StringContent(userModel.company), "company");
                }
                if (!string.IsNullOrWhiteSpace(jobEntry.Text))
                {
                    content.Add(new StringContent(userModel.job_title), "job_title");
                }
                if (ageSwitch.IsToggled)
                {
                    isAgeshow = "1";
                }
                else
                {
                    isAgeshow = "0";
                }

                content.Add(new StringContent(isAgeshow), "show_age");

                if (distanceSwitch.IsToggled)
                {
                    isDistanceShow = "1";
                }
                else
                {
                    isDistanceShow = "0";
                }

                content.Add(new StringContent(isDistanceShow), "show_distance");
                content.Add(new StringContent(userModel.location), "location");
                content.Add(new StringContent(userModel.interest), "interest");
                userModel.height = heightEntry.SelectedIndex < 0 ? "" : heightEntry.Items[heightEntry.SelectedIndex].ToString();
                userModel.weight = weightEntry.SelectedIndex < 0 ? "" : weightEntry.Items[weightEntry.SelectedIndex].ToString();
                content.Add(new StringContent(userModel.height), "height");
                content.Add(new StringContent(userModel.weight), "weight");
                content.Add(new StringContent(userModel.hobby == null ? "" : userModel.hobby), "hobby");

                var request = await client.PostAsync("http://" + ApiConnection.Url + "/apier/api/test_api.php?action=updateUser", content);

                request.EnsureSuccessStatusCode();
                var response = await request.Content.ReadAsStringAsync();

                if (response.Length > 0)
                {
                    return(true);
                }
                else
                {
                    return(true);
                }
            }
            catch (Exception ex)
            {
                await DisplayAlert("Connection Error", ex.ToString(), "Okay");

                return(false);
            }
        }
Beispiel #30
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);
                                string FullPath = amdocs.ginger.GingerCoreNET.WorkSpace.Instance.SolutionRepository.ConvertSolutionRelativePath(path);

                                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;
                }
            }
        }
        public async Task Serialize_InvalidQuotedName_Encoded()
        {
            var content = new MultipartFormDataContent("test_boundary");
            content.Add(new StringContent("Hello World"), "\"testク\r\n namé\"");

            var output = new MemoryStream();
            await content.CopyToAsync(output);

            output.Seek(0, SeekOrigin.Begin);
            string result = new StreamReader(output).ReadToEnd();

            Assert.Equal(
                "--test_boundary\r\nContent-Type: text/plain; charset=utf-8\r\n"
                + "Content-Disposition: form-data; name=\"=?utf-8?B?dGVzdOOCrw0KIG5hbcOp?=\""
                + "\r\n\r\nHello World\r\n--test_boundary--\r\n",
                result);
        }
Beispiel #32
0
        public async Task <UploadedFile> UploadFileAsync(string path, CancellationToken cancellationToken, IProgress <double> progressCallback = null)
        {
            var handler = new HttpClientHandler
            {
                Proxy                 = WebHelper.GetProxy(),
                PreAuthenticate       = true,
                UseDefaultCredentials = false,
            };

            using (var client = new HttpClient(handler))
            {
                using (var res = await client.PostAsync(@"https://api.gfycat.com/v1/gfycats", null, cancellationToken))
                {
                    var result = await res.Content.ReadAsStringAsync();

                    //{"isOk":true,"gfyname":"ThreeWordCode","secret":"15alphanumerics","uploadType":"filedrop.gfycat.com"}

                    var ser = new JavaScriptSerializer();

                    if (!(ser.DeserializeObject(result) is Dictionary <string, object> thing))
                    {
                        throw new Exception("It was not possible to get the gfycat name: " + res);
                    }

                    var name = thing["gfyname"] as string;

                    using (var content = new MultipartFormDataContent())
                    {
                        content.Add(new StringContent(name), "key");
                        content.Add(new ByteArrayContent(File.ReadAllBytes(path)), "file", name);

                        using (var res2 = await client.PostAsync("https://filedrop.gfycat.com", content, cancellationToken))
                        {
                            if (!res2.IsSuccessStatusCode)
                            {
                                throw new Exception("It was not possible to get the gfycat upload result: " + res2);
                            }

                            //{"task": "complete", "gfyname": "ThreeWordCode"}
                            //{"progress": "0.03", "task": "encoding", "time": 10}

                            //If the task is not yet completed, try waiting.

                            var input2 = "";

                            while (!input2.Contains("complete"))
                            {
                                using (var res3 = await client.GetAsync("https://api.gfycat.com/v1/gfycats/fetch/status/" + name, cancellationToken))
                                {
                                    input2 = await res3.Content.ReadAsStringAsync();

                                    if (!res3.IsSuccessStatusCode)
                                    {
                                        throw new UploadingException("It was not possible to get the gfycat upload status: " + res3);
                                    }
                                }

                                if (!input2.Contains("complete"))
                                {
                                    Thread.Sleep(1000);
                                }
                            }

                            if (res2.IsSuccessStatusCode)
                            {
                                return new UploadedFile {
                                           Link = "https://gfycat.com/" + name
                                }
                            }
                            ;
                        }
                    }
                }
            }

            throw new UploadingException("Unknown error");
        }
    }
 public void Add_NullContent_ThrowsArgumentNullException()
 {
     var content = new MultipartFormDataContent();
     Assert.Throws<ArgumentNullException>(() => content.Add(null));
 }
Beispiel #34
0
        /*void CheckImage()
         * {
         *  // Instantiate the reader
         *  Debug.Assert(!string.IsNullOrEmpty(_pathFileInput));
         *
         *  var nameExtension = Path.GetExtension(_pathFileInput);
         *  if (nameExtension != ".jpeg" && nameExtension != ".jpg") return;
         *
         *  using (ExifReader reader = new ExifReader(_pathFileInput))
         *  {
         *      // Extract the tag data using the ExifTags enumeration
         *      //if (reader.GetTagValue<decimal>(ExifTags.Orientation,
         *      //    out var orientation))
         *      //{
         *      //    ValueOrientation = (int) orientation;
         *      //}
         *
         *      DateTime datePictureTaken;
         *      if (reader.GetTagValue<DateTime>(ExifTags.DateTimeDigitized,
         *          out datePictureTaken))
         *      {
         *          // Do whatever is required with the extracted information
         *          MessageBox.Show(this, string.Format("The picture was taken on {0}",
         *              datePictureTaken), "Image information", MessageBoxButtons.OK);
         *      }
         *  }
         * }*/

        private async void button2_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_pathFileInput) && string.IsNullOrEmpty(PdfPath))
            {
                return;
            }

            //pictureBoxNormilized.Text = "";

            button1.Enabled = false;
            button2.Enabled = false;
            btnPDF.Enabled  = false;

            try
            {
                HttpClient httpClient = new HttpClient {
                    Timeout = new TimeSpan(1, 1, 1)
                };


                MultipartFormDataContent form = new MultipartFormDataContent
                {
                    { new StringContent("a1aeb2404288957"), "apikey" },
                    { new StringContent(GetSelectedLanguage()), "language" },
                    { new StringContent("true"), "detectOrientation" }
                };


                byte[] imageData = null;
                if (string.IsNullOrEmpty(_pathFileInput) == false)
                {
                    imageData = File.ReadAllBytes(_pathFileInput);
                    form.Add(new ByteArrayContent(imageData, 0, imageData.Length), "image", "image.jpg");
                }
                else
                {
                    throw  new Exception("Отсутствует параметр входящей строки");
                }

                HttpResponseMessage response = await httpClient.PostAsync("https://api.ocr.space/Parse/Image", form);

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

                RootObject ocrResult = JsonConvert.DeserializeObject <RootObject>(strContent);

                // UPDATE добавить проверку распознанного и предупредить, если не распозналось (сохранить в отдельную папку)

                if (ocrResult.OcrExitCode == 1)
                {
                    for (var i = 0; i < ocrResult.ParsedResults.Count(); i++)
                    {
                        var orientation = ocrResult.ParsedResults[i].TextOrientation;
                        int.TryParse(orientation, out var vRotateAngle);

                        // редактируем изображение на основе полученных данных
                        // поворот и смена разрешения (dpi)
                        imageData = CorrectImage(imageData, ValueResolutionInput, vRotateAngle);

                        // сохраняем полученную картинку
                        SaveImageOnDisk(imageData);

                        pictureBoxNormilized.Text           += ocrResult.ParsedResults[i].ParsedText;
                        pictureBoxNormilized.BackgroundImage = Image.FromFile(_pathFileOutput);
                    }
                }
                else
                {
                    MessageBox.Show(@"OCR Error: " + strContent);
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(@"Error: " + exception.Message);
            }

            button1.Enabled = true;
            button2.Enabled = true;
            btnPDF.Enabled  = true;
        }
 public void Add_EmptyFileName_ThrowsArgumentException()
 {
     var content = new MultipartFormDataContent();
     Assert.Throws<ArgumentException>(() => content.Add(new StringContent("Hello world"), "name", String.Empty));
 }
Beispiel #36
0
        public ActionResult Create(VehicleViewModel vehicleViewModel)
        {
            try
            {
                if (Request.Files.Count > 0)
                {
                    HttpPostedFileBase[] httpPostedFileBase = new HttpPostedFileBase[4];
                    if (vehicleViewModel.MulkiaFront1File != null)
                    {
                        httpPostedFileBase[0] = vehicleViewModel.MulkiaFront1File;
                    }
                    if (vehicleViewModel.MulkiaBack1File != null)
                    {
                        httpPostedFileBase[1] = vehicleViewModel.MulkiaBack1File;
                    }
                    if (vehicleViewModel.MulkiaFront2File != null)
                    {
                        httpPostedFileBase[2] = vehicleViewModel.MulkiaFront2File;
                    }
                    if (vehicleViewModel.MulkiaBack2File != null)
                    {
                        httpPostedFileBase[3] = vehicleViewModel.MulkiaBack2File;
                    }

                    var file = vehicleViewModel.MulkiaFront1File;

                    using (HttpClient client = new HttpClient())
                    {
                        using (var content = new MultipartFormDataContent())
                        {
                            if (httpPostedFileBase.ToList().Count > 0)
                            {
                                for (int i = 0; i < 4; 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("MulkiaFront1")
                                            {
                                                FileName = file.FileName
                                            };
                                        }
                                        else if (i == 1)
                                        {
                                            fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("MulkiaBack1")
                                            {
                                                FileName = file.FileName
                                            };
                                        }
                                        else if (i == 2)
                                        {
                                            fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("MulkiaFront2")
                                            {
                                                FileName = file.FileName
                                            };
                                        }
                                        else if (i == 3)
                                        {
                                            fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("MulkiaBack2")
                                            {
                                                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("ClientDocs"), "ClientDocs");
                            content.Add(new StringContent(vehicleViewModel.VehicleType.ToString()), "VehicleType");
                            content.Add(new StringContent(vehicleViewModel.TraficPlateNumber == null ? "" : vehicleViewModel.TraficPlateNumber), "TraficPlateNumber");
                            content.Add(new StringContent(vehicleViewModel.TCNumber == null ? "" : vehicleViewModel.TCNumber), "TCNumber");
                            content.Add(new StringContent(vehicleViewModel.Model == null ? "" : vehicleViewModel.Model), "Model");
                            content.Add(new StringContent(vehicleViewModel.Brand == null ? "" : vehicleViewModel.Brand), "Brand");
                            content.Add(new StringContent(vehicleViewModel.Color == null ? "" : vehicleViewModel.Color), "Color");
                            content.Add(new StringContent(vehicleViewModel.MulkiaExpiry == null ? "" : vehicleViewModel.MulkiaExpiry), "MulkiaExpiry");
                            content.Add(new StringContent(vehicleViewModel.InsuranceExpiry == null ? "" : vehicleViewModel.InsuranceExpiry), "InsuranceExpiry");
                            content.Add(new StringContent(vehicleViewModel.RegisteredRegion == null ? "" : vehicleViewModel.RegisteredRegion), "RegisteredRegion");
                            content.Add(new StringContent(vehicleViewModel.Comments == null ? "" : vehicleViewModel.Comments), "Comments");



                            var result = webServices.PostMultiPart(content, "AWFVehicle/Add", true);
                            if (result.StatusCode == System.Net.HttpStatusCode.Accepted)
                            {
                                return(Redirect(nameof(Index)));
                            }
                        }
                    }
                }
                return(RedirectToAction(nameof(Details), new { Id = vehicleViewModel.Id }));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Gets the multi-part content (with files) for a request
        /// </summary>
        /// <param name="client">The REST client that will execute the request</param>
        /// <param name="request">REST request to get the content for</param>
        /// <param name="parameters">The merged request parameters</param>
        /// <returns>The HTTP content to be sent</returns>
        private static IHttpContent GetMultiPartContent([CanBeNull] this IRestClient client, IRestRequest request, RequestParameters parameters)
        {
            var isPostMethod = client.GetEffectiveHttpMethod(request, parameters.OtherParameters) == Method.POST;
            var multipartContent = new MultipartFormDataContent(new GenericHttpHeaders());
            foreach (var parameter in parameters.OtherParameters)
            {
                var fileParameter = parameter as FileParameter;
                if (fileParameter != null)
                {
                    var file = fileParameter;
                    var data = new ByteArrayContent((byte[])file.Value);
                    if (!string.IsNullOrEmpty(file.ContentType))
                    {
                        data.Headers.ReplaceWithoutValidation("Content-Type", file.ContentType);
                    }

                    data.Headers.ReplaceWithoutValidation("Content-Length", file.ContentLength.ToString());
                    multipartContent.Add(data, file.Name, file.FileName);
                }
                else if (isPostMethod && parameter.Type == ParameterType.GetOrPost)
                {
                    IHttpContent data;
                    var bytes = parameter.Value as byte[];
                    if (bytes != null)
                    {
                        var rawData = bytes;
                        data = new ByteArrayContent(rawData);
                        data.Headers.ReplaceWithoutValidation(
                            "Content-Type",
                            string.IsNullOrEmpty(parameter.ContentType) ? "application/octet-stream" : parameter.ContentType);
                        data.Headers.ReplaceWithoutValidation("Content-Length", rawData.Length.ToString());
                        multipartContent.Add(data, parameter.Name);
                    }
                    else
                    {
                        var value = parameter.ToRequestString();
                        data = new StringContent(value, parameter.Encoding ?? ParameterExtensions.DefaultEncoding);
                        if (!string.IsNullOrEmpty(parameter.ContentType))
                        {
                            data.Headers.ReplaceWithoutValidation("Content-Type", parameter.ContentType);
                        }

                        multipartContent.Add(data, parameter.Name);
                    }
                }
                else if (parameter.Type == ParameterType.RequestBody)
                {
                    var data = request.GetBodyContent(parameter);
                    multipartContent.Add(data, parameter.Name);
                }
            }

            return multipartContent;
        }
        public ActionResult Edit([Bind(Include = "Id,JobTitle,JobContent,JobImageFile,CategoryId")] Job job)
        {
            ModelState.Remove("JobImageFile"); // remove the Validation message of JobImageFile property "The JobImageFile is required", in case the user isn't upload a new image.
            if (!ModelState.IsValid)
            {
                using (JobFinderDbContext db = new JobFinderDbContext())
                {
                    ViewBag.CategoryId = new SelectList(db.Categories.ToList(), "Id", "CategoryName", job.CategoryId);
                }
                return(View(job));
            }

            using (var formData = new MultipartFormDataContent())
            {
                //1-- Check if the User post a new image
                if (job.JobImageFile != null)
                {
                    // Read The Image File in byte[].
                    byte[] imgData;

                    using (var reader = new BinaryReader(job.JobImageFile.InputStream))
                    {
                        imgData = reader.ReadBytes(job.JobImageFile.ContentLength);
                    }
                    formData.Add(new ByteArrayContent(imgData), "JobImageFile", job.JobImageFile.FileName);
                }
                //--

                //2-- Get the other job properties.
                Dictionary <string, string> formFields = new Dictionary <string, string>();
                formFields.Add("Id", job.Id.ToString());
                formFields.Add("JobTitle", job.JobTitle);
                formFields.Add("JobContent", job.JobContent);
                formFields.Add("CategoryId", job.CategoryId.ToString());

                FormUrlEncodedContent formFieldsContent = new FormUrlEncodedContent(formFields);
                formData.Add(formFieldsContent, "job");
                //--


                if (Request.Cookies["BearerToken"] != null)
                {
                    var token = Request.Cookies["BearerToken"].Value;
                    httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
                }

                var ResponseTask = httpClient.PutAsync("jobs", formData);
                ResponseTask.Wait();

                var response = ResponseTask.Result;
                if (response.IsSuccessStatusCode)
                {
                    return(RedirectToAction("Index"));
                }
                else if (response.StatusCode == HttpStatusCode.NotFound)
                {
                    return(HttpNotFound());
                }
                else
                {
                    using (JobFinderDbContext db = new JobFinderDbContext())
                    {
                        ModelState.AddModelError("", response.Content.ReadAsStringAsync().Result);
                        ViewBag.CategoryId = new SelectList(db.Categories.ToList(), "Id", "CategoryName", job.CategoryId);
                        return(View(job));
                    }
                }
            }
        }