/// <summary>
        /// Call api asynchronous and return response of specified type asynchronously.
        /// </summary>
        /// <param name="method">HTTP method.</param>
        /// <param name="url">Url for api call.</param>
        /// <param name="parameters">Parameters for api call.</param>
        /// <param name="file">File to upload (must be null for non-uploading actions).</param>
        /// <param name="extraHeaders">Extra headers.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>Return response of specified type.</returns>
        /// <typeparam name="T">Type of the parsed response.</typeparam>
        internal virtual Task <T> CallApiAsync <T>(
            HttpMethod method,
            string url,
            BaseParams parameters,
            FileDescription file,
            Dictionary <string, string> extraHeaders = null,
            CancellationToken?cancellationToken      = null)
            where T : BaseResult, new()
        {
            parameters?.Check();

            var callParams = (method == HttpMethod.PUT || method == HttpMethod.POST)
                ? parameters?.ToParamsDictionary()
                : null;

            return(CallAndParseAsync <T>(method, url, callParams, file, extraHeaders, cancellationToken));
        }
Beispiel #2
0
 /// <summary>
 /// Call the Cloudinary API and parse HTTP response.
 /// </summary>
 /// <typeparam name="T">Type of the response.</typeparam>
 /// <param name="method">HTTP method.</param>
 /// <param name="url">A generated URL.</param>
 /// <param name="parameters">Cloudinary parameters to add to the API call.</param>
 /// <param name="file">(Optional) Add file to the body of the API call.</param>
 /// <param name="extraHeaders">(Optional) Headers to add to the request.</param>
 /// <returns>Instance of the parsed response from the cloudinary API.</returns>
 public T CallAndParse <T>(
     HttpMethod method,
     string url,
     SortedDictionary <string, object> parameters,
     FileDescription file,
     Dictionary <string, string> extraHeaders = null)
     where T : BaseResult, new()
 {
     using (var response = Call(
                method,
                url,
                parameters,
                file,
                extraHeaders))
     {
         return(Parse <T>(response));
     }
 }
        /// <summary>
        /// Prepares request body to be sent on custom call to Cloudinary API.
        /// </summary>
        /// <param name="request">HTTP request to alter.</param>
        /// <param name="method">HTTP method of call.</param>
        /// <param name="parameters">Dictionary of call parameters.</param>
        /// <param name="file">File to upload.</param>
        /// <param name="extraHeaders">(Optional) Headers to add to the request.</param>
        /// <returns>Prepared HTTP request.</returns>
        internal HttpRequestMessage PrepareRequestBody(
            HttpRequestMessage request,
            HttpMethod method,
            SortedDictionary <string, object> parameters,
            FileDescription file,
            Dictionary <string, string> extraHeaders = null)
        {
            PrePrepareRequestBody(request, method, extraHeaders);

            if (ShouldPrepareContent(method, parameters))
            {
                SetChunkedEncoding(request);

                PrepareRequestContent(request, parameters, file, extraHeaders);
            }

            return(request);
        }
Beispiel #4
0
        /// <summary>
        /// Makes custom call to Cloudinary API.
        /// </summary>
        /// <param name="method">HTTP method of call.</param>
        /// <param name="url">URL to call.</param>
        /// <param name="parameters">Dictionary of call parameters (can be null).</param>
        /// <param name="file">File to upload (must be null for non-uploading actions).</param>
        /// <param name="extraHeaders">Headers to add to the request.</param>
        /// <returns>HTTP response on call.</returns>
        public HttpResponseMessage Call(
            HttpMethod method,
            string url,
            SortedDictionary <string, object> parameters,
            FileDescription file,
            Dictionary <string, string> extraHeaders = null)
        {
            using (var request = requestBuilder(url))
            {
                PrepareRequestBody(request, method, parameters, file, extraHeaders);

                var cancellationToken = GetDefaultCancellationToken();

                return(Client
                       .SendAsync(request, cancellationToken)
                       .GetAwaiter()
                       .GetResult());
            }
        }
Beispiel #5
0
        /// <summary>
        /// Prepares request body to be sent on custom asynchronous call to Cloudinary API.
        /// </summary>
        /// <param name="request">HTTP request to alter.</param>
        /// <param name="method">HTTP method of call.</param>
        /// <param name="parameters">Dictionary of call parameters.</param>
        /// <param name="file">File to upload.</param>
        /// <param name="extraHeaders">(Optional) Headers to add to the request.</param>
        /// <param name="cancellationToken">(Optional) Cancellation token.</param>
        /// <returns>Prepared HTTP request.</returns>
        internal async Task <HttpRequestMessage> PrepareRequestBodyAsync(
            HttpRequestMessage request,
            HttpMethod method,
            SortedDictionary <string, object> parameters,
            FileDescription file,
            Dictionary <string, string> extraHeaders = null,
            CancellationToken?cancellationToken      = null)
        {
            PrePrepareRequestBody(request, method, extraHeaders);

            if (ShouldPrepareContent(method, parameters))
            {
                SetChunkedEncoding(request);

                await PrepareRequestContentAsync(request, parameters, file, extraHeaders, cancellationToken);
            }

            return(request);
        }
Beispiel #6
0
 /// <summary>
 /// Call the Cloudinary API and parse HTTP response asynchronously.
 /// </summary>
 /// <typeparam name="T">Type of the response.</typeparam>
 /// <param name="method">HTTP method.</param>
 /// <param name="url">A generated URL.</param>
 /// <param name="parameters">Cloudinary parameters to add to the API call.</param>
 /// <param name="file">(Optional) Add file to the body of the API call.</param>
 /// <param name="extraHeaders">Headers to add to the request.</param>
 /// <param name="cancellationToken">(Optional) Cancellation token.</param>
 /// <returns>Instance of the parsed response from the cloudinary API.</returns>
 public async Task <T> CallAndParseAsync <T>(
     HttpMethod method,
     string url,
     SortedDictionary <string, object> parameters,
     FileDescription file,
     Dictionary <string, string> extraHeaders = null,
     CancellationToken?cancellationToken      = null)
     where T : BaseResult, new()
 {
     using (var response = await CallAsync(
                method,
                url,
                parameters,
                file,
                extraHeaders,
                cancellationToken).ConfigureAwait(false))
     {
         return(await ParseAsync <T>(response).ConfigureAwait(false));
     }
 }
Beispiel #7
0
 /// <summary>
 /// Makes custom call to Cloudinary API asynchronously.
 /// </summary>
 /// <param name="method">HTTP method of call.</param>
 /// <param name="url">URL to call.</param>
 /// <param name="parameters">Dictionary of call parameters (can be null).</param>
 /// <param name="file">File to upload (must be null for non-uploading actions).</param>
 /// <param name="extraHeaders">Headers to add to the request.</param>
 /// <param name="cancellationToken">(Optional) Cancellation token.</param>
 /// <returns>HTTP response on call.</returns>
 public async Task <HttpResponseMessage> CallAsync(
     HttpMethod method,
     string url,
     SortedDictionary <string, object> parameters,
     FileDescription file,
     Dictionary <string, string> extraHeaders = null,
     CancellationToken?cancellationToken      = null)
 {
     using (var request =
                await PrepareRequestBodyAsync(
                    requestBuilder(url),
                    method,
                    parameters,
                    file,
                    extraHeaders,
                    cancellationToken).ConfigureAwait(false))
     {
         var httpCancellationToken = cancellationToken ?? GetDefaultCancellationToken();
         return(await Client.SendAsync(request, httpCancellationToken).ConfigureAwait(false));
     }
 }
Beispiel #8
0
 private void WriteFile(StreamWriter writer, FileDescription file)
 {
     if (file.IsRemote)
     {
         WriteParam(writer, "file", file.FilePath);
     }
     else
     {
         if (file.Stream == null)
         {
             using (FileStream stream = new FileStream(file.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
             {
                 WriteFile(writer, stream, file.FileName);
             }
         }
         else
         {
             WriteFile(writer, file.Stream, file.FileName);
         }
     }
 }
Beispiel #9
0
        private void PrepareRequestContent(ref HttpWebRequest request, SortedDictionary <string, object> parameters,
                                           FileDescription file)
        {
            if (request == null)
            {
                return;
            }

            HandleUnsignedParameters(parameters);

            if (request.ContentType == Constants.CONTENT_TYPE_APPLICATION_JSON)
            {
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    streamWriter.Write(ParamsToJson(parameters));
                }
            }
            else
            {
                PrepareMultipartFormDataContent(request, parameters, file);
            }
        }
Beispiel #10
0
        /// <summary>
        /// Custom call to cloudinary API
        /// </summary>
        /// <param name="method">HTTP method of call</param>
        /// <param name="url">URL to call</param>
        /// <param name="parameters">Dictionary of call parameters (can be null)</param>
        /// <param name="file">File to upload (must be null for non-uploading actions)</param>
        /// <returns>HTTP response on call</returns>
        public HttpWebResponse Call(HttpMethod method, string url, SortedDictionary <string, object> parameters, FileDescription file)
        {
#if DEBUG
            Console.WriteLine(String.Format("{0} REQUEST:", method));
            Console.WriteLine(url);
#endif

            HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
            request.Method = Enum.GetName(typeof(HttpMethod), method);

            if (method == HttpMethod.POST && parameters != null)
            {
                request.ContentType = "multipart/form-data; boundary=" + HTTP_BOUNDARY;
                FinalizeUploadParameters(parameters);

                using (Stream requestStream = request.GetRequestStream())
                {
                    using (StreamWriter writer = new StreamWriter(requestStream)
                    {
                        AutoFlush = true
                    })
                    {
                        foreach (var param in parameters)
                        {
                            if (param.Value != null)
                            {
                                if (param.Value is IEnumerable <string> )
                                {
                                    foreach (var item in (IEnumerable <string>)param.Value)
                                    {
                                        WriteParam(writer, param.Key + "[]", item);
                                    }
                                }
                                else
                                {
                                    WriteParam(writer, param.Key, param.Value.ToString());
                                }
                            }
                        }

                        if (file != null)
                        {
                            WriteFile(writer, file);
                        }

                        writer.Write("--{0}--", HTTP_BOUNDARY);
                    }
                }
            }
            else
            {
                byte[] authBytes = Encoding.ASCII.GetBytes(String.Format("{0}:{1}", Account.ApiKey, Account.ApiSecret));
                request.Headers.Add("Authorization", String.Format("Basic {0}", Convert.ToBase64String(authBytes)));
            }

            try
            {
                return(request.GetResponse() as HttpWebResponse);
            }
            catch (WebException ex)
            {
                return(ex.Response as HttpWebResponse);
            }
        }
Beispiel #11
0
 public virtual T CallAndParse <T>(HttpMethod method, string url, SortedDictionary <string, object> parameters, FileDescription file, Dictionary <string, string> extraHeaders = null) where T : BaseResult, new()
 {
     throw new NotImplementedException();
 }
Beispiel #12
0
 public virtual object InternalCall(HttpMethod method, string url, SortedDictionary <string, object> parameters, FileDescription file, Dictionary <string, string> extraHeaders = null)
 {
     throw new Exception("Please call overriden method");
 }
Beispiel #13
0
        /// <summary>
        /// Custom call to cloudinary API
        /// </summary>
        /// <param name="method">HTTP method of call</param>
        /// <param name="url">URL to call</param>
        /// <param name="parameters">Dictionary of call parameters (can be null)</param>
        /// <param name="file">File to upload (must be null for non-uploading actions)</param>
        /// <returns>HTTP response on call</returns>
        public HttpWebResponse Call(HttpMethod method, string url, SortedDictionary <string, object> parameters, FileDescription file)
        {
#if DEBUG
            Console.WriteLine(String.Format("{0} REQUEST:", method));
            Console.WriteLine(url);
#endif

            HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
            request.Method    = Enum.GetName(typeof(HttpMethod), method);
            request.UserAgent = USER_AGENT;
            if (Timeout > 0)
            {
                request.Timeout = Timeout;
            }

            if (method == HttpMethod.POST && parameters != null)
            {
                request.AllowWriteStreamBuffering = false;
                request.AllowAutoRedirect         = false;
                if (UseChunkedEncoding)
                {
                    request.SendChunked = true;
                }

                request.ContentType = "multipart/form-data; boundary=" + HTTP_BOUNDARY;

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

                using (Stream requestStream = request.GetRequestStream())
                {
                    using (StreamWriter writer = new StreamWriter(requestStream))
                    {
                        foreach (var param in parameters)
                        {
                            if (param.Value != null)
                            {
                                if (param.Value is IEnumerable <string> )
                                {
                                    foreach (var item in (IEnumerable <string>)param.Value)
                                    {
                                        WriteParam(writer, param.Key + "[]", item);
                                    }
                                }
                                else
                                {
                                    WriteParam(writer, param.Key, param.Value.ToString());
                                }
                            }
                        }

                        if (file != null)
                        {
                            WriteFile(writer, file);
                        }

                        writer.Write("--{0}--", HTTP_BOUNDARY);
                    }
                }
            }
            else
            {
                byte[] authBytes = Encoding.ASCII.GetBytes(String.Format("{0}:{1}", Account.ApiKey, Account.ApiSecret));
                request.Headers.Add("Authorization", String.Format("Basic {0}", Convert.ToBase64String(authBytes)));
            }

            try
            {
                return((HttpWebResponse)request.GetResponse());
            }
            catch (WebException ex)
            {
                var response = ex.Response as HttpWebResponse;
                if (response == null)
                {
                    throw;
                }
                else
                {
                    return(response);
                }
            }
        }
Beispiel #14
0
        public async Task <RawUploadResult> UploadAsync(string resourceType, IDictionary <string, object> parameters, FileDescription fileDescription)
        {
            var url = Api.ApiUrlV.Action("upload").ResourceType(resourceType).BuildUrl();

            ResetInternalFileDescription(fileDescription, int.MaxValue);
            if (parameters == null)
            {
                parameters = new SortedDictionary <string, object>();
            }
            if (!(parameters is SortedDictionary <string, object>))
            {
                parameters = new SortedDictionary <string, object>(parameters);
            }
            using (var response = await Api.CallAsync(HttpMethod.Post, url, (SortedDictionary <string, object>)parameters, fileDescription, null))
            {
                return(await RawUploadResult.Parse(response));
            }
        }
 private static Stream GetFileStream(FileDescription file) =>
 file.Stream ?? File.OpenRead(file.FilePath);
Beispiel #16
0
        private void PrepareRequestContent(HttpRequestMessage request, SortedDictionary <string, object> parameters, FileDescription file, Dictionary <string, string> extraHeaders = null)
        {
            HandleUnsignedParameters(parameters);

            HttpContent content = extraHeaders != null &&
                                  extraHeaders.ContainsKey(Constants.HEADER_CONTENT_TYPE) &&
                                  extraHeaders[Constants.HEADER_CONTENT_TYPE] == Constants.CONTENT_TYPE_APPLICATION_JSON
                ? new StringContent(ParamsToJson(parameters), Encoding.UTF8, Constants.CONTENT_TYPE_APPLICATION_JSON)
                : PrepareMultipartFormDataContent(parameters, file, extraHeaders);

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

            request.Content = content;
        }
Beispiel #17
0
        /// <summary>
        /// Custom call to cloudinary API
        /// </summary>
        /// <param name="method">HTTP method of call</param>
        /// <param name="url">URL to call</param>
        /// <param name="parameters">Dictionary of call parameters (can be null)</param>
        /// <param name="file">File to upload (must be null for non-uploading actions)</param>
        /// <param name="extraHeaders">Headers to add to the request</param>
        /// <returns>HTTP response on call</returns>
        public HttpWebResponse Call(HttpMethod method, string url, SortedDictionary <string, object> parameters, FileDescription file, Dictionary <string, string> extraHeaders = null)
        {
            HttpWebRequest  request  = RequestBuilder(url);
            HttpWebResponse response = null;

            if (Timeout > 0)
            {
                request.Timeout = Timeout;
            }

            PrepareRequestBody(request, method, parameters, file, extraHeaders);

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
                if (response == null)
                {
                    throw;
                }
            }
            return(response);
        }
Beispiel #18
0
        public async Task <HttpResponseMessage> CallAsync(HttpMethod method, string url, SortedDictionary <string, object> parameters, FileDescription file, Dictionary <string, string> extraHeaders = null)
        {
            using (var stream = new MemoryStream())
            {
                var bytes = Encoding.ASCII.GetBytes(string.Format("{0}:{1}", Account.ApiKey, Account.ApiSecret));
                using (var client = new HttpClient()
                {
                    DefaultRequestHeaders =
                    {
                        { "User-Agent",    string.IsNullOrEmpty(UserPlatform) ? USER_AGENT : string.Format("{0} {1}", UserPlatform, USER_AGENT) },
                        { "Authorization", string.Format("Basic {0}",                                                 Convert.ToBase64String(bytes)) }
                    }
                })
                {
                    if (this.Timeout > 0)
                    {
                        client.Timeout = TimeSpan.FromMilliseconds(this.Timeout);
                    }

                    var content = new StreamContent(stream)
                    {
                    };

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



                    if (parameters != null && (method == HttpMethod.Post || method == HttpMethod.Put))
                    {
                        content.Headers.Add("Content-Type", "multipart/form-data; boundary=notrandomsequencetouseasboundary");
                        if (!parameters.ContainsKey("unsigned") || parameters["unsigned"].ToString() == "false")
                        {
                            FinalizeUploadParameters(parameters);
                        }

                        var writer = new StreamWriter(stream);
                        foreach (var parameter in parameters)
                        {
                            if (parameter.Value != null)
                            {
                                if (parameter.Value is IEnumerable <string> )
                                {
                                    foreach (var str in (IEnumerable <string>)parameter.Value)
                                    {
                                        WriteParam(writer, parameter.Key + "[]", str);
                                    }
                                }
                                else
                                {
                                    WriteParam(writer, parameter.Key, parameter.Value.ToString());
                                }
                            }
                        }
                        if (file != null)
                        {
                            WriteFile(writer, file);
                        }
                        writer.Write("--{0}--", HTTP_BOUNDARY);

                        writer.Flush();
                        stream.Position = 0;
                    }
                    return(await client.SendAsync(new HttpRequestMessage(method, url) { Content = content }));
                }
            }
        }
Beispiel #19
0
 private static void ResetInternalFileDescription(FileDescription file, int bufferSize = Int32.MaxValue)
 {
     file.BufferLength = bufferSize;
     file.EOF          = false;
     file.BytesSent    = 0;
 }
Beispiel #20
0
        private void PrepareMultipartFormDataContent(HttpWebRequest request, SortedDictionary <string, object> parameters, FileDescription file)
        {
            request.ContentType = "multipart/form-data; boundary=" + HTTP_BOUNDARY;

            using (Stream requestStream = request.GetRequestStream())
            {
                using (StreamWriter writer = new StreamWriter(requestStream))
                {
                    foreach (var param in parameters)
                    {
                        if (param.Value != null)
                        {
                            if (param.Value is IEnumerable <string> )
                            {
                                foreach (var item in (IEnumerable <string>)param.Value)
                                {
                                    WriteParam(writer, param.Key + "[]", item);
                                }
                            }
                            else
                            {
                                WriteParam(writer, param.Key, param.Value.ToString());
                            }
                        }
                    }

                    if (file != null)
                    {
                        WriteFile(writer, file);
                    }

                    writer.Write("--{0}--", HTTP_BOUNDARY);
                }
            }
        }
Beispiel #21
0
        internal HttpWebRequest PrepareRequestBody(HttpWebRequest request, HttpMethod method, SortedDictionary <string, object> parameters, FileDescription file, Dictionary <string, string> extraHeaders = null)
        {
            SetHttpMethod(method, request);

            // Add platform information to the USER_AGENT header
            // This is intended for platform information and not individual applications!
            request.UserAgent = string.IsNullOrEmpty(UserPlatform)
                ? USER_AGENT
                : string.Format("{0} {1}", UserPlatform, USER_AGENT);

            byte[] authBytes = Encoding.ASCII.GetBytes(String.Format("{0}:{1}", Account.ApiKey, Account.ApiSecret));
            request.Headers.Add("Authorization", String.Format("Basic {0}", Convert.ToBase64String(authBytes)));

            if (extraHeaders != null)
            {
                if (extraHeaders.ContainsKey("Content-Type"))
                {
                    request.ContentType = extraHeaders["Content-Type"];
                    extraHeaders.Remove("Content-Type");
                }

                foreach (var header in extraHeaders)
                {
                    request.Headers[header.Key] = header.Value;
                }
            }

            if ((method == HttpMethod.POST || method == HttpMethod.PUT) && parameters != null)
            {
                request.AllowWriteStreamBuffering = false;
                request.AllowAutoRedirect         = false;

                if (UseChunkedEncoding)
                {
                    request.SendChunked = true;
                }

                PrepareRequestContent(ref request, parameters, file);
            }

            return(request);
        }
Beispiel #22
0
        /// <summary>
        /// Custom call to cloudinary API
        /// </summary>
        /// <param name="method">HTTP method of call</param>
        /// <param name="url">URL to call</param>
        /// <param name="parameters">Dictionary of call parameters (can be null)</param>
        /// <param name="file">File to upload (must be null for non-uploading actions)</param>
        /// <param name="extraHeaders">Headers to add to the request</param>
        /// <returns>HTTP response on call</returns>
        public HttpResponseMessage Call(HttpMethod method, string url, SortedDictionary <string, object> parameters, FileDescription file, Dictionary <string, string> extraHeaders = null)
        {
            var request = RequestBuilder(url);
            HttpResponseMessage response = null;

            using (request)
            {
                PrepareRequestBody(request, method, parameters, file, extraHeaders);

                System.Threading.Tasks.Task <HttpResponseMessage> task2;

                if (Timeout > 0)
                {
                    var cancellationTokenSource = new CancellationTokenSource(Timeout);
                    task2 = client.SendAsync(request, cancellationTokenSource.Token);
                }
                else
                {
                    task2 = client.SendAsync(request);
                }

                task2.Wait();
                if (task2.IsFaulted)
                {
                    throw task2.Exception;
                }
                response = task2.Result;

                if (task2.IsCanceled)
                {
                }
                if (task2.IsFaulted)
                {
                    throw task2.Exception;
                }

                return(response);
            }
        }
Beispiel #23
0
        private HttpContent PrepareMultipartFormDataContent(SortedDictionary <string, object> parameters,
                                                            FileDescription file, Dictionary <string, string> extraHeaders = null)
        {
            var content = new MultipartFormDataContent(HTTP_BOUNDARY);

            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)
                {
                    StringContent strContent = new StringContent(file.FilePath);
                    strContent.Headers.Add("Content-Disposition", string.Format("form-data; name=\"{0}\"", "file"));
                    content.Add(strContent);
                }
                else
                {
                    Stream stream;

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

                    if (extraHeaders != null && extraHeaders.ContainsKey("Content-Range"))
                    {
                        // Unfortunately we don't have ByteRangeStreamContent here,
                        // let's create another stream from the original one
                        stream = GetRangeFromFile(file, stream);
                    }

                    var streamContent = new StreamContent(stream);

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

            return(content);
        }
Beispiel #24
0
 private static void ResetInternalFileDescription(FileDescription file, int bufferSize = 2147483647)
 {
     file.BufferLength = bufferSize;
     file.EOF          = false;
     file.BytesSent    = 0;
 }
 public static RawUploadResult Upload(this Cloudinary cloudinary, string resourceType, IDictionary <string, object> parameters, FileDescription fileDescription)
 {
     return(cloudinary.UploadAsync(resourceType, parameters, fileDescription).ExecSync());
 }
Beispiel #26
0
        /// <summary>
        /// Uploads a file to cloudinary.
        /// </summary>
        /// <param name="resourceType">Resource type ("image", "raw", "video", "auto")</param>
        /// <param name="parameters">Upload parameters.</param>
        /// <param name="fileDescription">File description.</param>
        public RawUploadResult Upload(string resourceType, IDictionary <string, object> parameters, FileDescription fileDescription)
        {
            string uri = m_api.ApiUrlV.Action("upload").ResourceType(resourceType).BuildUrl();

            ResetInternalFileDescription(fileDescription);

            if (parameters == null)
            {
                parameters = new SortedDictionary <string, object>();
            }

            if (!(parameters is SortedDictionary <string, object>))
            {
                parameters = new SortedDictionary <string, object>(parameters);
            }

            using (HttpWebResponse response = m_api.Call(HttpMethod.POST, uri, (SortedDictionary <string, object>)parameters, fileDescription))
            {
                return(RawUploadResult.Parse(response));
            }
        }
Beispiel #27
0
        private void PrepareRequestContent(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;

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

                    if (extraHeaders != null && extraHeaders.ContainsKey("Content-Range"))
                    {
                        // Unfortunately we don't have ByteRangeStreamContent here,
                        // let's create another stream from the original one
                        stream = GetRangeFromFile(file, stream);
                    }

                    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;
        }
        /// <summary>
        /// Call api synchronous and return response of specified type.
        /// </summary>
        /// <param name="method">HTTP method.</param>
        /// <param name="url">Url for api call.</param>
        /// <param name="parameters">Parameters for api call.</param>
        /// <param name="file">File to upload (must be null for non-uploading actions).</param>
        /// <param name="extraHeaders">Extra headers.</param>
        /// <returns>Return response of specified type.</returns>
        /// <typeparam name="T">Type of the parsed response.</typeparam>
        internal virtual T CallApi <T>(HttpMethod method, string url, BaseParams parameters, FileDescription file, Dictionary <string, string> extraHeaders = null)
            where T : BaseResult, new()
        {
            parameters?.Check();

            return(CallAndParse <T>(
                       method,
                       url,
                       (method == HttpMethod.PUT || method == HttpMethod.POST) ? parameters?.ToParamsDictionary() : null,
                       file,
                       extraHeaders));
        }
Beispiel #29
0
        internal HttpRequestMessage PrepareRequestBody(HttpRequestMessage request, HttpMethod method, SortedDictionary <string, object> parameters, FileDescription file, Dictionary <string, string> extraHeaders = null)
        {
            SetHttpMethod(method, request);

            // Add platform information to the USER_AGENT header
            // This is intended for platform information and not individual applications!
            request.Headers.Add("User-Agent", string.IsNullOrEmpty(UserPlatform)
                ? USER_AGENT
                : string.Format("{0} {1}", UserPlatform, USER_AGENT));

            byte[] authBytes = Encoding.ASCII.GetBytes(String.Format("{0}:{1}", Account.ApiKey, Account.ApiSecret));
            request.Headers.Add("Authorization", String.Format("Basic {0}", Convert.ToBase64String(authBytes)));

            if (extraHeaders != null)
            {
                if (extraHeaders.ContainsKey("Accept"))
                {
                    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(extraHeaders["Accept"]));
                    extraHeaders.Remove("Accept");
                }

                foreach (var header in extraHeaders)
                {
                    request.Headers.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            if ((method == HttpMethod.POST || method == HttpMethod.PUT) && parameters != null)
            {
                if (UseChunkedEncoding)
                {
                    request.Headers.Add("Transfer-Encoding", "chunked");
                }

                PrepareRequestContent(request, parameters, file, extraHeaders);
            }

            return(request);
        }