public void DoesNotExist()
 {
     FileResponse.BaseDirectory = Path.GetTempPath();
     var file = Path.Combine(Path.GetTempPath(), "Test.txt");
     var response = new FileResponse(file);
     response.StatusCode.Should().Be(HttpStatusCode.NotFound);
 }
Example #2
0
 public CachedFile(FileResponse response, HttpResponse gzippedResponse)
 {
     Response = response;
     LastModified = response.LastModified;
     ContentType = response.ContentType;
     GZippedResponse = gzippedResponse;
 }
 public void FileExists()
 {
     FileResponse.BaseDirectory = Path.GetTempPath();
     var filePath = Path.GetTempFileName();
     File.WriteAllText(filePath, "Test");
     var fileInfo = new FileInfo(filePath);
     var response = new FileResponse(filePath);
     response.StatusCode.Should().Be(HttpStatusCode.OK);
     response.ContentType.Should().Be(MimeTypes.GetMimeType(filePath));
     response.Headers.Should().Contain("ETag", fileInfo.LastWriteTimeUtc.Ticks.ToString("x"));
     response.Headers.Should().Contain("Last-Modified", fileInfo.LastWriteTimeUtc.ToString("R"));
     response.Body.AsString().Should().Be("Test");
     File.Delete(filePath);
 }
 public abstract void FileEdited(FileResponse res, FileEditRequest req);
 public abstract void FileDeleted(FileResponse res, FileDeleteRequest req);
Example #6
0
        /// <param name="file">file chunk</param>
        /// <param name="json">json data</param>
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public async System.Threading.Tasks.Task <FileResponse> UploadAsync(FileParameter file, string json, System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Upload/Upload");

            var client_ = _httpClient;

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    var boundary_ = System.Guid.NewGuid().ToString();
                    var content_  = new System.Net.Http.MultipartFormDataContent(boundary_);
                    content_.Headers.Remove("Content-Type");
                    content_.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary_);
                    if (file == null)
                    {
                        throw new System.ArgumentNullException("file");
                    }
                    else
                    {
                        var content_file_ = new System.Net.Http.StreamContent(file.Data);
                        if (!string.IsNullOrEmpty(file.ContentType))
                        {
                            content_file_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(file.ContentType);
                        }
                        content_.Add(content_file_, "file", file.FileName ?? "file");
                    }
                    if (json == null)
                    {
                        throw new System.ArgumentNullException("json");
                    }
                    else
                    {
                        content_.Add(new System.Net.Http.StringContent(ConvertToString(json, System.Globalization.CultureInfo.InvariantCulture)), "json");
                    }
                    request_.Content = content_;
                    request_.Method  = new System.Net.Http.HttpMethod("POST");
                    request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/octet-stream"));

                    PrepareRequest(client_, request_, urlBuilder_);
                    var url_ = urlBuilder_.ToString();
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
                    PrepareRequest(client_, request_, url_);

                    var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

                    try
                    {
                        var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
                        if (response_.Content != null && response_.Content.Headers != null)
                        {
                            foreach (var item_ in response_.Content.Headers)
                            {
                                headers_[item_.Key] = item_.Value;
                            }
                        }

                        ProcessResponse(client_, response_);

                        var status_ = ((int)response_.StatusCode).ToString();
                        if (status_ == "200" || status_ == "206")
                        {
                            var responseStream_ = response_.Content == null ? System.IO.Stream.Null : await response_.Content.ReadAsStreamAsync().ConfigureAwait(false);

                            var fileResponse_ = new FileResponse((int)response_.StatusCode, headers_, responseStream_, null, response_);
                            client_ = null; response_ = null; // response and client are disposed by FileResponse
                            return(fileResponse_);
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null);
                        }

                        return(default(FileResponse));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
            }
        }
 public void NotInBaseDirectory()
 {
     var response = new FileResponse(@"C:\Temp\Test.txt");
     response.StatusCode.Should().Be(HttpStatusCode.NotFound);
 }
Example #8
0
        public void Constructor_WithPathWithPathToExistingTextFile_ShouldReturnAResponseWithStatusCodeOk()
        {
            var response = new FileResponse("../../Fakes/Files/HelloWorld.txt");

            Assert.That(response.StatusCode, Is.EqualTo(200));
        }
Example #9
0
        public void Constructor_WithPathToExistingTextFile_ShouldReturnAResponseWithCorrectContentType()
        {
            var response = new FileResponse("../../Fakes/Files/HelloWorld.txt");

            Assert.That(response.ContentType, Is.EqualTo("application/octet-stream"));
        }
Example #10
0
 public static FileResponse WithoutData(this UserFile file)
 {
     return(FileResponse.FromUserFile(file));
 }
Example #11
0
        /// <summary>
        /// Requests the specified request method.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="requestMethod">The request method.</param>
        /// <param name="url">The URL.</param>
        /// <param name="requestData">The request data.</param>
        /// <param name="options">The options.</param>
        /// <returns>System.Threading.Tasks.Task&lt;T&gt;.</returns>
        /// <exception cref="System.Exception">ClientId and ClientSecret is not set</exception>
        /// <exception cref="PodioInvalidGrantException"></exception>
        /// <exception cref="PodioBadRequestException"></exception>
        /// <exception cref="PodioAuthorizationException"></exception>
        /// <exception cref="PodioForbiddenException"></exception>
        /// <exception cref="PodioNotFoundException"></exception>
        /// <exception cref="PodioConflictException"></exception>
        /// <exception cref="PodioGoneException"></exception>
        /// <exception cref="PodioRateLimitException"></exception>
        /// <exception cref="PodioServerException"></exception>
        /// <exception cref="PodioUnavailableException"></exception>
        /// <exception cref="PodioException"></exception>
        private async Task <T> RequestAsync <T>(RequestMethod requestMethod, string url, dynamic requestData, dynamic options = null) where T : new()
        {
            Dictionary <string, string> requestHeaders = new Dictionary <string, string>();
            var    data        = new List <string>();
            string httpMethod  = string.Empty;
            string originalUrl = url;

            url = this.ApiUrl + url;

            //To use url other than api.podio.com, ex file download from files.podio.com
            if (options != null && options.ContainsKey("url"))
            {
                url = options["url"];
            }

            if (string.IsNullOrEmpty(ClientId) || string.IsNullOrEmpty(ClientSecret))
            {
                throw new Exception("ClientId and ClientSecret is not set");
            }

            switch (requestMethod.ToString())
            {
            case "GET":
                httpMethod = "GET";
                requestHeaders["Content-type"] = "application/x-www-form-urlencoded";
                if (requestData != null)
                {
                    string query = EncodeAttributes(requestData);
                    url = url + "?" + query;
                }
                requestHeaders["Content-length"] = "0";
                break;

            case "DELETE":
                httpMethod = "DELETE";
                requestHeaders["Content-type"] = "application/x-www-form-urlencoded";
                if (requestData != null)
                {
                    string query = EncodeAttributes(requestData);
                    url = url + "?" + query;
                }
                requestHeaders["Content-length"] = "0";
                break;

            case "POST":
                httpMethod = "POST";
                if (options != null && options.ContainsKey("upload") && options["upload"])
                {
                    requestHeaders["Content-type"] = "multipart/form-data";
                    data.Add("file");
                }
                else if (options != null && options.ContainsKey("oauth_request") && options["oauth_request"])
                {
                    data.Add("oauth");
                    requestHeaders["Content-type"] = "application/x-www-form-urlencoded";
                }
                else
                {
                    requestHeaders["Content-type"] = "application/json";
                    data.Add("post");
                }
                break;

            case "PUT":
                httpMethod = "PUT";
                requestHeaders["Content-type"] = "application/json";
                data.Add("put");
                break;
            }

            if (OAuth != null && !string.IsNullOrEmpty(OAuth.AccessToken))
            {
                requestHeaders["Authorization"] = "OAuth2 " + OAuth.AccessToken;
                if (options != null && options.ContainsKey("oauth_request") && options["oauth_request"])
                {
                    requestHeaders.Remove("Authorization");
                }
            }
            else
            {
                requestHeaders.Remove("Authorization");
            }

            if (options != null && options.ContainsKey("file_download") && options["file_download"])
            {
                requestHeaders["Accept"] = "*/*";
            }
            else
            {
                requestHeaders["Accept"] = "application/json";
            }

            var request = (HttpWebRequest)WebRequest.Create(url);

            request.Method = httpMethod;

            PodioResponse podioResponse   = new PodioResponse();
            var           responseHeaders = new Dictionary <string, string>(StringComparer.CurrentCultureIgnoreCase);
            var           responseObject  = new T();

            if (requestHeaders.Any())
            {
                if (requestHeaders.ContainsKey("Accept"))
                {
                    request.Accept = requestHeaders["Accept"];
                }
                if (requestHeaders.ContainsKey("Content-type"))
                {
                    request.ContentType = requestHeaders["Content-type"];
                }
                if (requestHeaders.ContainsKey("Authorization"))
                {
                    request.Headers["Authorization"] = requestHeaders["Authorization"];
                }
            }
            if (data.Any())
            {
                foreach (string item in data)
                {
                    if (item == "file")
                    {
                        await AddFileToRequestStream(requestData.filePath, requestData.fileName, requestData.mimeType, request);
                    }
                    else if (item == "oauth")
                    {
                        await WriteToRequestStream(EncodeAttributes(requestData), request);
                    }
                    else
                    {
                        await WriteToRequestStream(requestData, request);
                    }
                }
            }

            try
            {
                WebResponse webResponse = await Task.Factory.FromAsync <WebResponse>(request.BeginGetResponse, request.EndGetResponse, request);

                using (webResponse)
                {
                    podioResponse.Status = (int)((HttpWebResponse)webResponse).StatusCode;
                    foreach (string key in webResponse.Headers.AllKeys)
                    {
                        responseHeaders.Add(key, webResponse.Headers[key]);
                    }

                    if (options != null && options.ContainsKey("file_download"))
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            var fileResponse = new FileResponse();
                            webResponse.GetResponseStream().CopyTo(memoryStream);
                            fileResponse.FileContents  = memoryStream.ToArray();
                            fileResponse.ContentType   = webResponse.ContentType;
                            fileResponse.ContentLength = webResponse.ContentLength;
                            return((T)fileResponse.ChangeType <T>());
                        }
                    }
                    else if (options != null && options.ContainsKey("return_raw"))
                    {
                        using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
                        {
                            podioResponse.Body = sr.ReadToEnd();
                            return(podioResponse.Body);
                        }
                    }
                    else
                    {
                        using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
                        {
                            podioResponse.Body = sr.ReadToEnd();
                        }
                    }
                    podioResponse.Headers = responseHeaders;
                }
            }
            catch (WebException e)
            {
                using (WebResponse response = e.Response)
                {
                    podioResponse.Status = (int)((HttpWebResponse)response).StatusCode;
                    foreach (string key in response.Headers.AllKeys)
                    {
                        responseHeaders.Add(key, response.Headers[key]);
                    }

                    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                    {
                        podioResponse.Body = sr.ReadToEnd();
                    }
                    podioResponse.Headers = responseHeaders;
                }
            }


            if (podioResponse.Headers.ContainsKey("X-Rate-Limit-Remaining"))
            {
                RateLimitRemaining = int.Parse(podioResponse.Headers["X-Rate-Limit-Remaining"]);
            }
            if (podioResponse.Headers.ContainsKey("X-Rate-Limit-Limit"))
            {
                RateLimit = int.Parse(podioResponse.Headers["X-Rate-Limit-Limit"]);
            }

            PodioError podioError = new PodioError();

            if (podioResponse.Status >= 400)
            {
                podioError = JSONSerializer.Deserilaize <PodioError>(podioResponse.Body);
            }

            switch (podioResponse.Status)
            {
            case 200:
            case 201:
                responseObject = JSONSerializer.Deserilaize <T>(podioResponse.Body);
                break;

            case 204:
                responseObject = default(T);
                break;

            case 400:
                if (podioError.Error == "invalid_grant")
                {
                    //Reset auth info
                    OAuth = new PodioOAuth();
                    throw new PodioInvalidGrantException(podioResponse.Status, podioError);
                }
                else
                {
                    throw new PodioBadRequestException(podioResponse.Status, podioError);
                }

            case 401:
                if (podioError.ErrorDescription == "expired_token" || podioError.Error == "invalid_token")
                {
                    if (!string.IsNullOrEmpty(OAuth.RefreshToken))
                    {
                        //Refresh access token
                        var authInfo = await RefreshAccessTokenAsync();

                        if (authInfo != null && !string.IsNullOrEmpty(authInfo.AccessToken))
                        {
                            responseObject = await RequestAsync <T>(requestMethod, originalUrl, requestData, options);
                        }
                    }
                    else
                    {
                        throw new PodioAuthorizationException(podioResponse.Status, podioError);
                    }
                }
                break;

            case 403:
                throw new PodioForbiddenException(podioResponse.Status, podioError);

            case 404:
                throw new PodioNotFoundException(podioResponse.Status, podioError);

            case 409:
                throw new PodioConflictException(podioResponse.Status, podioError);

            case 410:
                throw new PodioGoneException(podioResponse.Status, podioError);

            case 420:
                throw new PodioRateLimitException(podioResponse.Status, podioError);

            case 500:
                throw new PodioServerException(podioResponse.Status, podioError);

            case 502:
            case 503:
            case 504:
                throw new PodioUnavailableException(podioResponse.Status, podioError);

            default:
                throw new PodioException(podioResponse.Status, podioError);
            }

            return(responseObject);
        }
        /// <summary>Remove Face from WatchlistItem specified by FaceId and WatchlistItemId.</summary>
        /// <param name="payload">JSON with FaceId and WatchlistItemId.</param>
        /// <returns>Remove Face from WatchlistItem specified by FaceId and WatchlistItemId.</returns>
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public async System.Threading.Tasks.Task <FileResponse> RemoveFaceAsync(RemoveExistingFaceFromWlItemData payload, System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/rpc/WatchlistItems/RemoveFace");

            var client_ = _httpClient;

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(payload, _settings.Value));
                    content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
                    request_.Content             = content_;
                    request_.Method = new System.Net.Http.HttpMethod("POST");
                    request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));

                    PrepareRequest(client_, request_, urlBuilder_);
                    var url_ = urlBuilder_.ToString();
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
                    PrepareRequest(client_, request_, url_);

                    var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

                    try
                    {
                        var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
                        if (response_.Content != null && response_.Content.Headers != null)
                        {
                            foreach (var item_ in response_.Content.Headers)
                            {
                                headers_[item_.Key] = item_.Value;
                            }
                        }

                        ProcessResponse(client_, response_);

                        var status_ = ((int)response_.StatusCode).ToString();
                        if (status_ == "204" || status_ == "206")
                        {
                            var responseStream_ = response_.Content == null ? System.IO.Stream.Null : await response_.Content.ReadAsStreamAsync().ConfigureAwait(false);

                            var fileResponse_ = new FileResponse((int)response_.StatusCode, headers_, responseStream_, null, response_);
                            client_ = null; response_ = null; // response and client are disposed by FileResponse
                            return(fileResponse_);
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null);
                        }

                        return(default(FileResponse));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
            }
        }
Example #13
0
        public async Task <List <FileResponse> > Upload(List <IFormFile> files, string domain, string accessKey, string secretKey)
        {
            List <FileResponse> responseList = null;

            if (files.Count > 0)
            {
                foreach (IFormFile file in files)
                {
                    FileResponse model    = new FileResponse();
                    var          filePath = System.IO.Path.GetTempFileName();
                    string       keyName  = "Recycle-" + Guid.NewGuid() + "_@" + file.FileName;
                    string       fileType = System.IO.Path.GetExtension(keyName).Remove(0, 1);

                    if (fileType == "jpg" || fileType == "jpeg" || fileType == "png" || fileType == "gif")
                    {
                        model.FileTypeId = 1;
                    }
                    else
                    {
                        model.FileTypeId = GetFileType(fileType);
                    }

                    model.FileName = file.FileName;
                    try
                    {
                        BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);

                        AmazonS3Client s3Client = new AmazonS3Client(credentials, bucketRegion);

                        var transferUtilityConfig = new TransferUtilityConfig
                        {
                            ConcurrentServiceRequests = 5
                        };

                        TransferUtility fileTransferUtility = new TransferUtility(s3Client);

                        using (System.IO.FileStream stream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
                        {
                            await file.CopyToAsync(stream);

                            fileTransferUtility.Upload(stream, "sabio-training", keyName);
                        }
                        model.Url = domain + keyName;
                        if (responseList == null)
                        {
                            responseList = new List <FileResponse>();
                        }

                        responseList.Add(model);
                    }
                    catch (AmazonS3Exception e)
                    {
                        throw (e);
                    }
                    catch (Exception e)
                    {
                        throw (e);
                    }
                }
                return(responseList);
            }
            else
            {
                return(null);
            }
        }
Example #14
0
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        public async System.Threading.Tasks.Task <FileResponse> CreateCategoryAsync(CreateCategoryInput input, System.Threading.CancellationToken cancellationToken)
        {
            if (input == null)
            {
                throw new System.ArgumentNullException("input");
            }

            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Category");

            var client_        = _httpClient;
            var disposeClient_ = false;

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(input, _settings.Value));
                    content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
                    request_.Content             = content_;
                    request_.Method = new System.Net.Http.HttpMethod("POST");
                    request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/octet-stream"));

                    PrepareRequest(client_, request_, urlBuilder_);

                    var url_ = urlBuilder_.ToString();
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);

                    PrepareRequest(client_, request_, url_);

                    var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

                    var disposeResponse_ = true;
                    try
                    {
                        var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
                        if (response_.Content != null && response_.Content.Headers != null)
                        {
                            foreach (var item_ in response_.Content.Headers)
                            {
                                headers_[item_.Key] = item_.Value;
                            }
                        }

                        ProcessResponse(client_, response_);

                        var status_ = (int)response_.StatusCode;
                        if (status_ == 200 || status_ == 206)
                        {
                            var responseStream_ = response_.Content == null ? System.IO.Stream.Null : await response_.Content.ReadAsStreamAsync().ConfigureAwait(false);

                            var fileResponse_ = new FileResponse(status_, headers_, responseStream_, null, response_);
                            disposeClient_ = false; disposeResponse_ = false; // response and client are disposed by FileResponse
                            return(fileResponse_);
                        }
                        else
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new SwaggerException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null);
                        }
                    }
                    finally
                    {
                        if (disposeResponse_)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (disposeClient_)
                {
                    client_.Dispose();
                }
            }
        }
Example #15
0
 public FileService()
 {
     _fileResponse = new FileResponse();
 }
Example #16
0
        public void Constructor_WithPathToNonExistingTextFile_ShouldReturnAResponseWithStatusCodeNotFound()
        {
            var response = new FileResponse("../../Fakes/Files/NotFound.txt");

            Assert.That(response.StatusCode, Is.EqualTo(404));
        }
Example #17
0
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        public async System.Threading.Tasks.Task <FileResponse> GetLogsAsync(System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/application_watcher/get_logs");

            var client_        = new System.Net.Http.HttpClient();
            var disposeClient_ = true;

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    request_.Method = new System.Net.Http.HttpMethod("GET");
                    request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/octet-stream"));

                    PrepareRequest(client_, request_, urlBuilder_);

                    var url_ = urlBuilder_.ToString();
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);

                    PrepareRequest(client_, request_, url_);

                    var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

                    var disposeResponse_ = true;
                    try
                    {
                        var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
                        if (response_.Content != null && response_.Content.Headers != null)
                        {
                            foreach (var item_ in response_.Content.Headers)
                            {
                                headers_[item_.Key] = item_.Value;
                            }
                        }

                        ProcessResponse(client_, response_);

                        var status_ = (int)response_.StatusCode;
                        if (status_ == 200 || status_ == 206)
                        {
                            var responseStream_ = response_.Content == null ? System.IO.Stream.Null : await response_.Content.ReadAsStreamAsync().ConfigureAwait(false);

                            var fileResponse_ = new FileResponse(status_, headers_, responseStream_, client_, response_);
                            disposeClient_ = false; disposeResponse_ = false; // response and client are disposed by FileResponse
                            return(fileResponse_);
                        }
                        else
                        if (status_ == 404)
                        {
                            var objectResponse_ = await ReadObjectResponseAsync <ProblemDetails>(response_, headers_, cancellationToken).ConfigureAwait(false);

                            if (objectResponse_.Object == null)
                            {
                                throw new SwaggerException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null);
                            }
                            throw new SwaggerException <ProblemDetails>("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null);
                        }
                        else
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new SwaggerException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null);
                        }
                    }
                    finally
                    {
                        if (disposeResponse_)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (disposeClient_)
                {
                    client_.Dispose();
                }
            }
        }
Example #18
0
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        public async System.Threading.Tasks.Task <FileResponse> GetFileAsync(string fileName, System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl).Append("/api/File/GetFile?");
            if (fileName != null)
            {
                urlBuilder_.Append("fileName=").Append(System.Uri.EscapeDataString(System.Convert.ToString(fileName, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            urlBuilder_.Length--;

            var client_ = new System.Net.Http.HttpClient();

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    request_.Method = new System.Net.Http.HttpMethod("GET");
                    request_.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                    PrepareRequest(client_, request_, urlBuilder_);
                    var url_ = urlBuilder_.ToString();
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
                    PrepareRequest(client_, request_, url_);

                    var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

                    try
                    {
                        var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
                        foreach (var item_ in response_.Content.Headers)
                        {
                            headers_[item_.Key] = item_.Value;
                        }

                        ProcessResponse(client_, response_);

                        var status_ = ((int)response_.StatusCode).ToString();
                        if (status_ == "200" || status_ == "206")
                        {
                            var responseStream_ = await response_.Content.ReadAsStreamAsync().ConfigureAwait(false);

                            var fileResponse_ = new FileResponse(status_, headers_, responseStream_, client_, response_);
                            client_ = null; response_ = null; // response and client are disposed by FileResponse
                            return(fileResponse_);
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, headers_, null);
                        }

                        return(default(FileResponse));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
Example #19
0
 public void EmptyFilePath()
 {
     var response = new FileResponse(String.Empty);
     response.StatusCode.Should().Be(HttpStatusCode.NotFound);
 }
Example #20
0
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <exception cref="ApiException">A server side error occurred.</exception>
        public async System.Threading.Tasks.Task <FileResponse> DeleteLabelAsync(string identcode, System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/Label/delete/{identcode}");
            urlBuilder_.Replace("{identcode}", System.Uri.EscapeDataString(ConvertToString(identcode, System.Globalization.CultureInfo.InvariantCulture)));

            var client_ = _httpClient;

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    request_.Method = new System.Net.Http.HttpMethod("DELETE");
                    request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/octet-stream"));

                    PrepareRequest(client_, request_, urlBuilder_);
                    var url_ = urlBuilder_.ToString();
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
                    PrepareRequest(client_, request_, url_);

                    var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

                    try
                    {
                        var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
                        if (response_.Content != null && response_.Content.Headers != null)
                        {
                            foreach (var item_ in response_.Content.Headers)
                            {
                                headers_[item_.Key] = item_.Value;
                            }
                        }

                        ProcessResponse(client_, response_);

                        var status_ = ((int)response_.StatusCode).ToString();
                        if (status_ == "200" || status_ == "206")
                        {
                            var responseStream_ = response_.Content == null ? System.IO.Stream.Null : await response_.Content.ReadAsStreamAsync().ConfigureAwait(false);

                            var fileResponse_ = new FileResponse((int)response_.StatusCode, headers_, responseStream_, null, response_);
                            client_ = null; response_ = null; // response and client are disposed by FileResponse
                            return(fileResponse_);
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new ApiException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null);
                        }

                        return(default(FileResponse));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
            }
        }
Example #21
0
 public void NoExtension()
 {
     var response = new FileResponse("NoExtension");
     response.StatusCode.Should().Be(HttpStatusCode.NotFound);
 }
Example #22
0
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        public async System.Threading.Tasks.Task <FileResponse> PostAsync(Order order = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl).Append("/api/Orders");

            var client_ = new System.Net.Http.HttpClient();

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(order, _settings.Value));
                    content_.Headers.ContentType.MediaType = "application/json";
                    request_.Content = content_;
                    request_.Method  = new System.Net.Http.HttpMethod("POST");
                    request_.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                    PrepareRequest(client_, request_, urlBuilder_);
                    var url_ = urlBuilder_.ToString();
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
                    PrepareRequest(client_, request_, url_);

                    var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

                    try
                    {
                        var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
                        foreach (var item_ in response_.Content.Headers)
                        {
                            headers_[item_.Key] = item_.Value;
                        }

                        ProcessResponse(client_, response_);

                        var status_ = ((int)response_.StatusCode).ToString();
                        if (status_ == "200" || status_ == "206")
                        {
                            var responseStream_ = await response_.Content.ReadAsStreamAsync().ConfigureAwait(false);

                            var fileResponse_ = new FileResponse(status_, headers_, responseStream_, client_, response_);
                            client_ = null; response_ = null; // response and client are disposed by FileResponse
                            return(fileResponse_);
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, headers_, null);
                        }

                        return(default(FileResponse));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
Example #23
0
 public void NullFilePath()
 {
     var response = new FileResponse(null);
     response.StatusCode.Should().Be(HttpStatusCode.NotFound);
 }
 public abstract void FileAdded(FileResponse res, FileAddRequest req);
Example #25
0
        public HttpResponse Handle(IHttpRequest req)
        {
            var fullName = GetFileFullName(req);
            var fileInfo = new FileInfo(fullName);

            if (!fileInfo.Exists) // cached but deleted
            {
                return NotFound;
            }

            DateTime ifModifiedSince;
            CachedFile cachedFile;

            var checkLastModified = req.TryGetIfLastModifiedSince(out ifModifiedSince); // remote client has a cached version
            var hasCachedResponse = checkLastModified ? TryGetCachedFileResponse(fullName, ifModifiedSince, out cachedFile) : TryGetCachedFileResponse(fullName, out cachedFile);

            if (hasCachedResponse && fileInfo.LastWriteTimeUtc <= cachedFile.LastModified)
            {
                if (checkLastModified)
                {
                    return NotChanged(cachedFile.ContentType);
                }
                else
                {
                    return req.IsAcceptGZip() && cachedFile.GZippedResponse != null ? cachedFile.GZippedResponse : cachedFile.Response;
                }
            }
            else
            {
                var fileResponse = new FileResponse(fileInfo);

                cachedFile = new CachedFile(fileResponse, gzipFunc != null ? fileResponse.GZip(gzipFunc) : null);
                cache[fullName] = cachedFile;

                return req.IsAcceptGZip() && cachedFile.GZippedResponse != null ? cachedFile.GZippedResponse : cachedFile.Response;
            }
        }
Example #26
0
        /// <summary>
        /// Lắng nghe phản hồi từ phía client
        /// </summary>
        void Receive(object obj)
        {
            Socket client = obj as Socket;

            try
            {
                while (true)
                {
                    byte[] buffer = new byte[1024 * 1024 * 20];
                    client.Receive(buffer);

                    object         data      = Deserialize(buffer);
                    ServerResponse container = data as ServerResponse;

                    switch (container.Type)
                    {
                    case ServerResponseType.SendStudent:

                        Student student = container.Data as Student;
                        AddMessage(client.RemoteEndPoint.ToString() + ": Thông tin sinh viên thao tác trên máy: " + student.FullNameAndId);

                        break;

                    case ServerResponseType.SendFile:

                        FileResponse file = container.Data as FileResponse;

                        string fileName = file.FileInfo.Name;
                        AddMessage(client.RemoteEndPoint.ToString() + ": Đã nhận bài làm, tập tin có tên: " + fileName);

                        using (var fileStream = File.Create(fileName))
                        {
                            fileStream.Write(file.FileContent, 0, file.FileContent.Length);
                        }

                        break;

                    case ServerResponseType.SendList:
                        break;

                    case ServerResponseType.SendString:

                        string computerName = (string)container.Data;

                        AddMessage(client.RemoteEndPoint.ToString() + ": Tên máy: " + computerName);

                        break;

                    case ServerResponseType.BeginExam:
                        break;

                    case ServerResponseType.FinishExam:
                        break;

                    case ServerResponseType.LockClient:
                        break;

                    default:
                        break;
                    }
                }
            }
            catch
            {
                AddMessage(client.RemoteEndPoint.ToString() + ": " + "Đã đóng kết nối");
                clientList.Remove(client);
                client.Close();
            }
        }