示例#1
37
        public void ContentLength_SetStreamSupportingSeeking_StreamLengthMatchesHeaderValue()
        {
            var source = new MockStream(new byte[10], true, true); // Supports seeking.
            var content = new StreamContent(source);

            Assert.Equal(source.Length, content.Headers.ContentLength);;
        }
示例#2
0
        public void ContentLength_SetStreamNotSupportingSeeking_NullReturned()
        {
            var source = new MockStream(new byte[10], false, true); // Doesn't support seeking.
            var content = new StreamContent(source);

            Assert.Null(content.Headers.ContentLength);
        }
示例#3
0
        public void ContentLength_SetStreamSupportingSeekingPartiallyConsumed_StreamLengthMatchesHeaderValueMinusConsumed()
        {
            int consumed = 4;
            var source = new MockStream(new byte[10], true, true); // Supports seeking.
            source.Read(new byte[consumed], 0, consumed);
            var content = new StreamContent(source);

            Assert.Equal(source.Length - consumed, content.Headers.ContentLength);
        }
示例#4
0
        public async Task CopyToAsync_CallMultipleTimesWithStreamSupportingSeeking_ContentIsSerializedMultipleTimes()
        {
            var source = new MockStream(new byte[10], true, true); // Supports seeking.
            var content = new StreamContent(source);

            var destination1 = new MemoryStream();
            await content.CopyToAsync(destination1);
            Assert.Equal(source.Length, destination1.Length);

            var destination2 = new MemoryStream();
            await content.CopyToAsync(destination2);
            Assert.Equal(source.Length, destination2.Length);
        }
示例#5
0
        public async Task ContentReadStream_GetPropertyPartiallyConsumed_ReturnOriginalStream()
        {
            int consumed = 4;
            var source = new MockStream(new byte[10]);
            source.Read(new byte[consumed], 0, consumed);
            var content = new StreamContent(source);

            Stream stream = await content.ReadAsStreamAsync();
            Assert.False(stream.CanWrite);
            Assert.Equal(source.Length, stream.Length);
            Assert.Equal(1, source.ReadCount);
            Assert.Equal(consumed, stream.Position);
            Assert.NotSame(source, stream);
        }
示例#6
0
        public async Task Send(WnsNotification notification)
        {
            // Get or renew our access token
            var accessToken = await AccessTokenManager.GetAccessToken();

            //https://cloud.notify.windows.com/?token=.....
            //Authorization: Bearer {AccessToken}
            //

            // Not sure how to do this in httpclient
            var http = new HttpClient();

            http.DefaultRequestHeaders.ExpectContinue = false; //Disable expect-100 to improve latency

            http.DefaultRequestHeaders.TryAddWithoutValidation("X-WNS-Type", string.Format("wns/{0}", notification.Type.ToString().ToLower()));

            if (!http.DefaultRequestHeaders.Contains("Authorization")) //prevent double values
            {
                http.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Bearer " + accessToken);
            }

            if (notification.RequestForStatus.HasValue)
            {
                http.DefaultRequestHeaders.TryAddWithoutValidation("X-WNS-RequestForStatus", notification.RequestForStatus.Value.ToString().ToLower());
            }

            if (notification.TimeToLive.HasValue)
            {
                http.DefaultRequestHeaders.TryAddWithoutValidation("X-WNS-TTL", notification.TimeToLive.Value.ToString());                 //Time to live in seconds
            }
            if (notification.Type == WnsNotificationType.Tile)
            {
                var winTileNot = notification as WnsTileNotification;

                if (winTileNot != null && winTileNot.CachePolicy.HasValue)
                {
                    http.DefaultRequestHeaders.Add("X-WNS-Cache-Policy", winTileNot.CachePolicy == WnsNotificationCachePolicyType.Cache ? "cache" : "no-cache");
                }

                if (winTileNot != null && !string.IsNullOrEmpty(winTileNot.NotificationTag))
                {
                    http.DefaultRequestHeaders.Add("X-WNS-Tag", winTileNot.NotificationTag);                     // TILE only
                }
            }
            else if (notification.Type == WnsNotificationType.Badge)
            {
                var winTileBadge = notification as WnsBadgeNotification;

                if (winTileBadge != null && winTileBadge.CachePolicy.HasValue)
                {
                    http.DefaultRequestHeaders.Add("X-WNS-Cache-Policy", winTileBadge.CachePolicy == WnsNotificationCachePolicyType.Cache ? "cache" : "no-cache");
                }
            }
            else if (notification.Type == WnsNotificationType.Toast)
            {
                http.DefaultRequestHeaders.TryAddWithoutValidation("X-WindowsPhone-Target", notification.Type.ToString().ToLower());
            }

            HttpContent content = null;

            if (notification.Type == WnsNotificationType.Raw)
            {
                content = new StreamContent(new MemoryStream(((WnsRawNotification)notification).RawData));
            }
            else
            {
                content = new StringContent(
                    notification.Payload.ToString(), // Get XML payload
                    Encoding.UTF8,
                    "text/xml");
            }

            var result = await http.PostAsync(notification.ChannelUri, content);

            var status = ParseStatus(result, notification);

            //RESPONSE HEADERS
            // X-WNS-Debug-Trace   string
            // X-WNS-DeviceConnectionStatus  connected | disconnected | tempdisconnected   (if RequestForStatus was set to true)
            // X-WNS-Error-Description  string
            // X-WNS-Msg-ID   string  (max 16 char)
            // X-WNS-NotificationStatus   received | dropped | channelthrottled
            //

            // 200 OK
            // 400  One or more headers were specified incorrectly or conflict with another header.
            // 401  The cloud service did not present a valid authentication ticket. The OAuth ticket may be invalid.
            // 403  The cloud service is not authorized to send a notification to this URI even though they are authenticated.
            // 404  The channel URI is not valid or is not recognized by WNS. - Raise Expiry
            // 405  Invalid Method - never will get
            // 406  The cloud service exceeded its throttle limit.
            // 410  The channel expired. - Raise Expiry
            // 413  The notification payload exceeds the 5000 byte size limit.
            // 500  An internal failure caused notification delivery to fail.
            // 503  The server is currently unavailable.

            // OK, everything worked!
            if (status.HttpStatus == HttpStatusCode.OK &&
                status.NotificationStatus == WnsNotificationSendStatus.Received)
            {
                return;
            }

            //401
            if (status.HttpStatus == HttpStatusCode.Unauthorized)
            {
                AccessTokenManager.InvalidateAccessToken(accessToken);
                throw new RetryAfterException(notification, "Access token expired", DateTime.UtcNow.AddSeconds(5));
            }

            //404 or 410
            if (status.HttpStatus == HttpStatusCode.NotFound || status.HttpStatus == HttpStatusCode.Gone)
            {
                throw new DeviceSubscriptionExpiredException(notification)
                      {
                          OldSubscriptionId = notification.ChannelUri,
                          ExpiredAt         = DateTime.UtcNow
                      };
            }


            // Any other error
            throw new WnsNotificationException(status);
        }
示例#7
0
        public async Task CopyToAsync_CallMultipleTimesWithStreamNotSupportingSeekingButBufferedStreamPartiallyConsumed_ContentSerializedOnceToBuffer()
        {
            int consumed = 4;
            var source = new MockStream(new byte[10], false, true); // doesn't support seeking.
            source.Read(new byte[consumed], 0, consumed);
            var content = new StreamContent(source);

            // After loading the content into a buffer, we should be able to copy the content to a destination stream
            // multiple times, even though the stream doesn't support seeking.
            await content.LoadIntoBufferAsync();

            var destination1 = new MemoryStream();
            await content.CopyToAsync(destination1);
            // Use hardcoded expected length, since source.Length would throw (source stream gets disposed if non-seekable).
            Assert.Equal(10 - consumed, destination1.Length);

            var destination2 = new MemoryStream();
            await content.CopyToAsync(destination2);
            Assert.Equal(10 - consumed, destination2.Length);
        }
示例#8
0
        /// <summary>
        /// Upload a blob
        /// </summary>
        /// If your blob is an image, use image APIs. For all other blob types, use
        /// this API.
        /// <param name='authorization'>
        /// Format is: "Scheme CredentialsList". Possible values are:
        ///
        /// - Anon AK=AppKey
        ///
        /// - SocialPlus TK=SessionToken
        ///
        /// - Facebook AK=AppKey|TK=AccessToken
        ///
        /// - Google AK=AppKey|TK=AccessToken
        ///
        /// - Twitter AK=AppKey|RT=RequestToken|TK=AccessToken
        ///
        /// - Microsoft AK=AppKey|TK=AccessToken
        ///
        /// - AADS2S AK=AppKey|[UH=UserHandle]|TK=AADToken
        /// </param>
        /// <param name='blob'>
        /// MIME encoded contents of the blob
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <PostBlobResponse> > PostBlobWithHttpMessagesAsync(string authorization, System.IO.Stream blob, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (authorization == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "authorization");
            }
            if (blob == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "blob");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("authorization", authorization);
                tracingParameters.Add("blob", blob);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "PostBlob", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url     = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v0.7/blobs").ToString();
            // Create HTTP transport objects
            HttpRequestMessage  _httpRequest  = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("POST");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (authorization != null)
            {
                if (_httpRequest.Headers.Contains("Authorization"))
                {
                    _httpRequest.Headers.Remove("Authorization");
                }
                _httpRequest.Headers.TryAddWithoutValidation("Authorization", authorization);
            }
            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;
            StreamContent _fileStreamContent = new StreamContent(blob);

            _httpRequest.Content = _fileStreamContent;
            _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.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 != 201 && (int)_statusCode != 400 && (int)_statusCode != 401 && (int)_statusCode != 500)
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                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 <PostBlobResponse>();

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

                try
                {
                    _result.Body = SafeJsonConvert.DeserializeObject <PostBlobResponse>(_responseContent, this.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);
        }
示例#9
0
        public async System.Threading.Tasks.Task CreateRequestImageUploadAsync()
        {
            var    ACCESS_TOKEN       = WebConfigurationManager.AppSettings["access_token"];
            var    API_LIST_HIERACHY  = WebConfigurationManager.AppSettings["api_list_hierachy"];
            var    API_CREATE_REQUEST = WebConfigurationManager.AppSettings["api_create_request"];
            var    API_ADD_DOCUMENT   = WebConfigurationManager.AppSettings["api_add_document"];
            string responseDetail     = "";

            HttpClient client = new HttpClient
            {
                BaseAddress = new Uri(WebConfigurationManager.AppSettings["apiBaseAddress"])
            };

            // Address SSL and TLS security issue.
            #region
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 |
                                                   SecurityProtocolType.Tls |
                                                   SecurityProtocolType.Tls11 |
                                                   SecurityProtocolType.Tls12;
            #endregion
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", ACCESS_TOKEN);

            // Post to get organisation unit to a list of units.
            HierachyNode node = new HierachyNode()
            {
                IncludeAncestors = true, IncludeChildren = true, IncludeDescendents = 0, IncludeSiblings = true, IncludeSubItems = true
            };
            node.ObjectKey = new ObjectKey()
            {
                ObjectType = "ObjectType_OrganisationUnit", Int32Value = 0
            };
            // POST request
            HttpResponseMessage response = await client.PostAsJsonAsync(API_LIST_HIERACHY, node);

            // Check response
            if (!response.IsSuccessStatusCode)
            {
                throw new System.ArgumentException(response.StatusCode.ToString(), "Cannot get organisation units");
            }
            // Get headers which contain organisation units
            responseDetail = response.Content.ReadAsStringAsync().Result;
            AllHeaders netObjects = JsonConvert.DeserializeObject <AllHeaders>(responseDetail);


            // Get organisation ID from first header for each department
            int orgUnitId = netObjects.Headers[0].ObjectKey.Int32Value;
            // Create user object and changing the necessary fields.
            string[] changes = { "RequestDetail", "RequestorName", "OrganisationUnitID" };
            User     user    = new User();
            user.ChangeSet = new ChangeSet()
            {
                Changes = changes
            };
            user.ChangeSet.Updated = new Updated {
                RequestDetail = "This a request" + netObjects.Headers[0].ObjectName, RequestorName = "Jason Lee", OrganisationUnitID = orgUnitId
            };
            // POST request
            HttpResponseMessage createUserResponse = await client.PostAsJsonAsync(API_CREATE_REQUEST, user);

            // Check response
            if (!createUserResponse.IsSuccessStatusCode)
            {
                throw new System.ArgumentException(createUserResponse.StatusCode.ToString(), "Cannot create user");
            }
            // Get request ID
            string requestID = createUserResponse.Content.ReadAsStringAsync().Result;
            Debug.WriteLine(String.Format("Request ID: {0}    |     Organisation Name: {1}", requestID, netObjects.Headers[0].ObjectName));

            // Create Container for chosen Request. Change path to "Request" and use requestID.
            DocContainer con = new DocContainer()
            {
                DocumentDescription = "Request Image", Address = $"file://conquest_documents/Request/{requestID}/JasonTestImage.png", ContentType = "image/png",
            };
            con.ObjectKey = new ObjectKey()
            {
                ObjectType = "ObjectType_Request", Int32Value = int.Parse(requestID)
            };
            HttpResponseMessage createFileResponse = await client.PostAsJsonAsync(API_ADD_DOCUMENT, con);

            // Check response
            if (!createFileResponse.IsSuccessStatusCode)
            {
                throw new System.ArgumentException(createFileResponse.StatusCode.ToString(), "Cannot create file response");
            }
            Debug.WriteLine(createFileResponse.Content.ReadAsStringAsync().Result);

            // Upload image to container
            DocDataObject docDataObject = JsonConvert.DeserializeObject <DocDataObject>(createFileResponse.Content.ReadAsStringAsync().Result);

            var f         = System.IO.File.OpenRead("..\\..\\B.png");
            var content   = new StreamContent(f);
            var mpcontent = new MultipartFormDataContent();
            content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
            mpcontent.Add(content);

            HttpResponseMessage uploadDocumentResponse = await client.PutAsync(docDataObject.UploadUri, mpcontent);

            //Check response
            if (!uploadDocumentResponse.IsSuccessStatusCode)
            {
                throw new System.ArgumentException(uploadDocumentResponse.StatusCode.ToString(), "Cannot upload image");
            }
        }
        /// <summary>
        /// Handle a simple http request dumping remote content to the client
        /// </summary>
        /// <param name="context"></param>
        /// <param name="_options"></param>
        /// <param name="destination"></param>
        /// <param name="host"></param>
        /// <param name="port"></param>
        /// <param name="scheme"></param>
        /// <returns></returns>
        private async Task HandleHttpRequest(HttpContext context, InternalProxyOptions _options, Node destination, string host, int port, string scheme)
        {
            var requestMessage = new HttpRequestMessage();
            var requestMethod  = context.Request.Method;

            if (!HttpMethods.IsGet(requestMethod) && !HttpMethods.IsHead(requestMethod) && !HttpMethods.IsDelete(requestMethod) && !HttpMethods.IsTrace(requestMethod))
            {
                var streamContent = new StreamContent(context.Request.Body);
                requestMessage.Content = streamContent;
            }

            // All request headers and cookies must be transferend to remote server. Some headers will be skipped
            foreach (var header in context.Request.Headers)
            {
                if (!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()) && requestMessage.Content != null)
                {
                    requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
                }
            }


            requestMessage.Headers.Host = host;
            //recreate remote url
            string uriString = GetUri(context, host, port, scheme);

            requestMessage.RequestUri = new Uri(uriString);
            requestMessage.Method     = new HttpMethod(context.Request.Method);
            using (var responseMessage = await _httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
            {
                context.Response.StatusCode = (int)responseMessage.StatusCode;
                foreach (var header in responseMessage.Headers)
                {
                    context.Response.Headers[header.Key] = header.Value.ToArray();
                }

                foreach (var header in responseMessage.Content.Headers)
                {
                    context.Response.Headers[header.Key] = header.Value.ToArray();
                }


                if (!_options.SendChunked)
                {
                    //tell to the browser that response is not chunked
                    context.Response.Headers.Remove("transfer-encoding");
                    await responseMessage.Content.CopyToAsync(context.Response.Body);
                }
                else
                {
                    var buffer = new byte[_options.BufferSize ?? DefaultBufferSize];

                    using (var responseStream = await responseMessage.Content.ReadAsStreamAsync())
                    {
                        //long pos = responseStream.Position;
                        //if (pos > 0)
                        //{
                        //    responseStream.Seek(0, SeekOrigin.Begin);
                        //}
                        //context.Response.Body = new MemoryStream();

                        int len  = 0;
                        int full = 0;
                        while ((len = await responseStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                        {
                            await context.Response.Body.WriteAsync(buffer, 0, buffer.Length);

                            // await context.Response.Body.FlushAsync();
                            full += buffer.Length;
                        }
                        // context.Response.ContentLength = full;

                        context.Response.Headers.Remove("transfer-encoding");
                    }
                }
            }
        }
示例#11
0
        public static async Task <IEnumerable <Claim> > getList(string method, Dictionary <string, string> parameters = null)
        {
            #region generate token to send it to api
            byte[] key = Convert.FromBase64String(Secret);
            SymmetricSecurityKey securityKey = new SymmetricSecurityKey(key);

            var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials
                                  (securityKey, SecurityAlgorithms.HmacSha256Signature);

            //  Finally create a Token
            var header  = new JwtHeader(credentials);
            var nbf     = DateTime.UtcNow.AddSeconds(-1);
            var exp     = DateTime.UtcNow.AddSeconds(120);
            var payload = new JwtPayload(null, "", new List <Claim>(), nbf, exp);

            if (parameters != null)
            {
                for (int i = 0; i < parameters.Count; i++)
                {
                    payload.Add(parameters.Keys.ToList()[i], parameters.Values.ToList()[i]);
                }
            }
            // add userLogInID to parameters
            payload.Add("userLogInID", MainWindow.userLogInID);

            var token   = new JwtSecurityToken(header, payload);
            var handler = new JwtSecurityTokenHandler();

            // Token to String so you can use post it to api
            string getToken       = handler.WriteToken(token);
            var    encryptedToken = EncryptThenCompress(getToken);

            //encryptedToken = HttpUtility.UrlPathEncode(encryptedToken);

            string tmpPath = writeToTmpFile(encryptedToken);
            //string dir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
            //string tmpPath = Path.Combine(dir, Global.TMPFolder);
            // tmpPath = Path.Combine(tmpPath, "tmp.txt");
            FileStream fs = new FileStream(tmpPath, FileMode.Open, FileAccess.Read);
            #endregion
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(Global.APIUri);
                client.Timeout     = System.TimeSpan.FromSeconds(3600);
                string boundary = string.Format("----WebKitFormBoundary{0}", DateTime.Now.Ticks.ToString("x"));
                MultipartFormDataContent form = new MultipartFormDataContent();
                HttpContent content           = new StreamContent(fs);

                content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                {
                    FileName = "tmp.txt"
                };
                content.Headers.Add("client", "true");

                form.Add(content, "fileToUpload");

                var response = await client.PostAsync(@method + "?token=" + "null", form);

                if (response.IsSuccessStatusCode)
                {
                    var jsonString = await response.Content.ReadAsStringAsync();

                    var Sresponse = JsonConvert.DeserializeObject <string>(jsonString);
                    fs.Dispose();
                    File.Delete(tmpPath);
                    if (Sresponse != "")
                    {
                        var decryptedToken = DeCompressThenDecrypt(Sresponse);
                        var jwtToken       = new JwtSecurityToken(decryptedToken);
                        var s = jwtToken.Claims.ToArray();
                        IEnumerable <Claim> claims = jwtToken.Claims;
                        string validAuth           = claims.Where(f => f.Type == "scopes").Select(x => x.Value).FirstOrDefault();
                        if (validAuth != null && s[2].Value == "-7") // invalid authintication
                        {
                            return(null);
                        }
                        else if (validAuth != null && s[2].Value == "-8")
                        {
                            MainWindow.go_out = true;
                        }
                        return(claims);
                    }
                }
                else
                {
                    fs.Dispose();
                    File.Delete(tmpPath);
                }
            }
            return(null);
        }
        /// <inheritdoc />
        public async Task AttachFileToIssue(string issueId, string attachmentName, Stream attachmentStream, string group = null, string author = null, string attachmentContentType = null)
        {
            if (string.IsNullOrEmpty(issueId))
            {
                throw new ArgumentNullException(nameof(issueId));
            }
            if (string.IsNullOrEmpty(attachmentName))
            {
                throw new ArgumentNullException(nameof(attachmentName));
            }
            if (attachmentStream == null)
            {
                throw new ArgumentNullException(nameof(attachmentStream));
            }

            var queryString = new List <string>(3);

            if (!string.IsNullOrEmpty(attachmentName))
            {
                queryString.Add($"attachmentName={attachmentName}");
            }
            if (!string.IsNullOrEmpty(group))
            {
                queryString.Add($"group={group}");
            }
            if (!string.IsNullOrEmpty(group))
            {
                queryString.Add($"author={author}");
            }

            var query = string.Join("&", queryString);

            var streamContent = new StreamContent(attachmentStream);

            if (!string.IsNullOrEmpty(attachmentContentType))
            {
                streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse(attachmentContentType);
            }
            streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                FileName = attachmentName,
                Name     = attachmentName
            };

            var content = new MultipartFormDataContent
            {
                streamContent
            };

            var client = await _connection.GetAuthenticatedHttpClient();

            var response = await client.PostAsync($"rest/issue/{issueId}/attachment?{query}", content);

            if (response.StatusCode == HttpStatusCode.BadRequest)
            {
                // Try reading the error message
                var responseJson = JObject.Parse(await response.Content.ReadAsStringAsync());
                if (responseJson["value"] != null)
                {
                    throw new YouTrackErrorException(responseJson["value"].Value <string>());
                }

                throw new YouTrackErrorException(Strings.Exception_UnknownError);
            }

            response.EnsureSuccessStatusCode();
        }
        /// <summary>
        /// This helper method makes an HTTP request and eventually returns a result
        /// </summary>
        /// <param name="httpMethod">The HTTP method for the request</param>
        /// <param name="requestUrl">The URL of the request</param>
        /// <param name="accept">The content type of the accepted response</param>
        /// <param name="content">The content of the request</param>
        /// <param name="contentType">The content  type of the request</param>
        /// <param name="resultPredicate">The predicate to retrieve the result, if any</param>
        /// <typeparam name="TResult">The type of the result, if any</typeparam>
        /// <returns>The value of the result, if any</returns>
        private static TResult MakeHttpRequest <TResult>(
            String httpMethod,
            String requestUrl,
            String accept      = null,
            Object content     = null,
            String contentType = null,
            Func <HttpResponseMessage, TResult> resultPredicate = null)
        {
            // Prepare the variable to hold the result, if any
            TResult result = default(TResult);

            // Get the OAuth Access Token
            Uri requestUri  = new Uri(requestUrl);
            Uri graphUri    = new Uri(MSGraphAPIDemoSettings.MicrosoftGraphResourceId);
            var accessToken =
                GetAccessTokenForCurrentUser(requestUri.DnsSafeHost != graphUri.DnsSafeHost ?
                                             ($"{requestUri.Scheme}://{requestUri.Host}") : MSGraphAPIDemoSettings.MicrosoftGraphResourceId
                                             );

            if (!String.IsNullOrEmpty(accessToken))
            {
                // If we have the token, then handle the HTTP request
                HttpClientHandler handler = new HttpClientHandler();
                handler.AllowAutoRedirect = true;
                HttpClient httpClient = new HttpClient(handler, true);

                // Set the Authorization Bearer token
                httpClient.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", accessToken);

                // If there is an accept argument, set the corresponding HTTP header
                if (!String.IsNullOrEmpty(accept))
                {
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue(accept));
                }

                // Prepare the content of the request, if any
                HttpContent      requestContent = null;
                System.IO.Stream streamContent  = content as System.IO.Stream;
                if (streamContent != null)
                {
                    requestContent = new StreamContent(streamContent);
                    requestContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                }
                else
                {
                    requestContent =
                        (content != null) ?
                        new StringContent(JsonConvert.SerializeObject(content,
                                                                      Formatting.None,
                                                                      new JsonSerializerSettings
                    {
                        NullValueHandling = NullValueHandling.Ignore,
                        ContractResolver  = new CamelCasePropertyNamesContractResolver(),
                    }),
                                          Encoding.UTF8, contentType) :
                        null;
                }

                // Prepare the HTTP request message with the proper HTTP method
                HttpRequestMessage request = new HttpRequestMessage(
                    new HttpMethod(httpMethod), requestUrl);

                // Set the request content, if any
                if (requestContent != null)
                {
                    request.Content = requestContent;
                }

                // Fire the HTTP request
                HttpResponseMessage response = httpClient.SendAsync(request).Result;

                if (response.IsSuccessStatusCode)
                {
                    // If the response is Success and there is a
                    // predicate to retrieve the result, invoke it
                    if (resultPredicate != null)
                    {
                        result = resultPredicate(response);
                    }
                }
                else
                {
                    throw new ApplicationException(
                              String.Format("Exception while invoking endpoint {0}.", requestUrl),
                              new HttpException(
                                  (Int32)response.StatusCode,
                                  response.Content.ReadAsStringAsync().Result));
                }
            }

            return(result);
        }
示例#14
0
 public void Dispose()
 {
     this.msg     = null;
     this.outStr  = null;
     this.content = null;
 }
示例#15
0
        protected async Task <T> Post <T, TRequest>(TRequest requestObject, CancellationToken ct)
            where TRequest : ArcGISServerOperation, IAttachment
            where T : IPortalResponse
        {
            LiteGuard.Guard.AgainstNullArgument(nameof(requestObject), requestObject);
            LiteGuard.Guard.AgainstNullArgumentProperty(nameof(requestObject), nameof(requestObject.Endpoint), requestObject.Endpoint);

            requestObject.BeforeRequest?.Invoke();

            var endpoint = requestObject.Endpoint;
            var url      = endpoint.BuildAbsoluteUrl(RootUrl).Split('?').FirstOrDefault();

            var token = await CheckGenerateToken(ct);

            if (ct.IsCancellationRequested)
            {
                return(default(T));
            }

            // these should have already been added
            if (string.IsNullOrWhiteSpace(requestObject.Token) && token != null && !string.IsNullOrWhiteSpace(token.Value))
            {
                requestObject.Token = token.Value;
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token.Value);
                if (token.AlwaysUseSsl)
                {
                    url = url.Replace("http:", "https:");
                }
            }

            _httpClient.CancelPendingRequests();

            Uri  uri;
            bool validUrl = Uri.TryCreate(url, UriKind.Absolute, out uri);

            if (!validUrl)
            {
                throw new HttpRequestException(string.Format("Not a valid url: {0}", url));
            }

            _logger.DebugFormat("Post attachment to {0}", uri);
            string resultString = string.Empty;
            var    attachment   = (IAttachment)requestObject;

            using (var content = new MultipartFormDataContent())
            {
                var streamContent = new StreamContent(new MemoryStream(attachment.Attachment));
                var header        = new ContentDispositionHeaderValue("form-data");
                header.Name     = "\"attachment\"";
                header.FileName = attachment.FileName;
                streamContent.Headers.ContentDisposition = header;
                streamContent.Headers.ContentType        = new MediaTypeHeaderValue(attachment.ContentType);

                content.Add(streamContent);
                content.Add(new StringContent("json"), "f");
                if (!string.IsNullOrWhiteSpace(requestObject.Token))
                {
                    content.Add(new StringContent(requestObject.Token), "token");
                }

                try
                {
                    using (var message = await _httpClient.PostAsync(uri, content))
                    {
                        message.EnsureSuccessStatusCode();
                        resultString = await message.Content.ReadAsStringAsync();
                    }
                }
                catch (TaskCanceledException)
                {
                    return(default(T));
                }
            }

            var result = Serializer.AsPortalResponse <T>(resultString);

            if (result.Error != null)
            {
                throw new InvalidOperationException(result.Error.ToString());
            }

            requestObject.AfterRequest?.Invoke();

            return(result);
        }
示例#16
0
        /// <summary>
        /// The function used to process http request.
        /// </summary>
        /// <param name="context">The context of the http request.</param>
        public override void Process(HttpContext context)
        {
            HttpRequestMessage reqMsg = context.Request;

            if (reqMsg.Method != HttpMethod.Get)
            {
                return;
            }
            string url      = reqMsg.RequestUri.ToString();
            int    paramPos = url.IndexOf("?");

            if (paramPos >= 0)
            {
                url = url.Substring(0, paramPos);
            }

            string sFilePath = HttpUtility.UrlDecode(url);
            // sFilePath = sFilePath.Replace("/", "\\");
            bool   isRootRequest = sFilePath == "/";
            string filePath      = null;

            if (isRootRequest)
            {
                if (DefaultFiles.Count == 0)
                {
                    return;
                }
                bool isMatch = false;
                foreach (string fileName in DefaultFiles)
                {
                    filePath = Path.Combine(RootDir, fileName);
                    if (File.Exists(filePath))
                    {
                        isMatch = true;
                        break;
                    }
                }

                if (!isMatch)
                {
                    return;
                }
            }
            else
            {
                filePath = Path.Combine(RootDir, sFilePath.TrimStart('/'));
                if (!File.Exists(filePath))
                {
                    return;
                }
            }

            string         ext = Path.GetExtension(filePath);
            DateTimeOffset?reqModifyDateTime = null;

            if (context.Request.Headers.TryGetValues("If-Modified-Since", out IEnumerable <string> vals))
            {
                if (DateTimeOffset.TryParse(vals.First(), out DateTimeOffset outTime))
                {
                    reqModifyDateTime = outTime;
                }
            }
            try
            {
                FileInfo            fi       = new FileInfo(filePath);
                HttpResponseMessage repMsg   = ResponseMsgHelper.CreateSimpleRepMsg();
                HttpContent         content  = null;
                DateTimeOffset      fileTime = new DateTimeOffset(fi.LastWriteTimeUtc);

                bool isFileTimeSame = false;
                if (reqModifyDateTime != null)
                {
                    isFileTimeSame = fileTime.Year == reqModifyDateTime.Value.Year &&
                                     fileTime.Month == reqModifyDateTime.Value.Month &&
                                     fileTime.Day == reqModifyDateTime.Value.Day &&
                                     fileTime.Hour == reqModifyDateTime.Value.Hour &&
                                     fileTime.Minute == reqModifyDateTime.Value.Minute &&
                                     fileTime.Second == reqModifyDateTime.Value.Second;
                }

                if (!isFileTimeSame)
                {
                    string fileName    = Path.GetFileName(filePath);
                    string contentType = MimeDict.First().Value;
                    if (!string.IsNullOrEmpty(ext))
                    {
                        ext = ext.TrimStart('.').ToLower();
                        if (MimeDict.TryGetValue(ext, out string temp))
                        {
                            contentType = temp;
                        }
                    }

                    bool acceptGzip = EnableGZIP && reqMsg.Headers.AcceptEncoding.Any(p => p.Value.ToLower() == "gzip");
                    if (acceptGzip)
                    {
                        if (fi.Length <= 2 * 1024 || !CompressFileExt.Contains(ext) || fi.Length > MaxCompressLength)
                        {
                            acceptGzip = false;
                        }
                    }

                    if (acceptGzip || fi.Length <= MaxCacheLength)
                    {
                        FileStream fs   = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                        byte[]     data = null;
                        if (acceptGzip)
                        {
                            data = DataZip.CompressToGZIPBytes(fs);
                        }
                        else
                        {
                            data = new byte[fs.Length];
                            fs.Read(data, 0, data.Length);
                        }

                        fs.Close();
                        content = new ByteArrayContent(data);
                        content.Headers.ContentLength = data.Length;
                    }
                    else
                    {
                        FileStream    fs            = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                        StreamContent streamContent = new StreamContent(fs);
                        content = streamContent;
                        content.Headers.ContentLength = fi.Length;
                    }

                    MediaTypeHeaderValue headerValue = new MediaTypeHeaderValue(contentType);
                    content.Headers.ContentType = headerValue;

                    content.Headers.Add("Last-Modified", fileTime.ToString("R"));
                    if (acceptGzip)
                    {
                        content.Headers.ContentEncoding.Add("gzip");
                    }
                }
                else
                {
                    repMsg.StatusCode = System.Net.HttpStatusCode.NotModified;
                }

                repMsg.Content   = content;
                context.Response = repMsg;
            }
            catch (Exception ex)
            {
                context.Response = new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError);
                //System.Diagnostics.Trace.WriteLine(ex.ToString());
                Console.WriteLine(ex.Message);
            }
        }
示例#17
0
        /// <summary>
        /// Sends audio and returns transcription results for a sessionless recognition request. Returns only the final results; to enable interim results, use Sessions or WebSockets. The service imposes a data size limit of 100 MB. It automatically detects the endianness of the incoming audio and, for audio that includes multiple channels, downmixes the audio to one-channel mono during transcoding.
        /// You specify the parameters of the request as a path parameter, request headers, and query parameters. You provide the audio as the body of the request. This method is preferred to the multipart approach for submitting a sessionless recognition request.
        /// For requests to transcribe live audio as it becomes available, you must set the Transfer-Encoding header to chunked to use streaming mode. In streaming mode, the server closes the connection (response code 408) if the service receives no data chunk for 30 seconds and the service has no audio to transcribe for 30 seconds. The server also closes the connection (response code 400) if no speech is detected for inactivity_timeout seconds of audio (not processing time); use the inactivity_timeout parameter to change the default of 30 seconds.
        /// </summary>
        /// <param name="sessionId"></param>
        /// <param name="contentType"></param>
        /// <param name="transferEncoding"></param>
        /// <param name="audio"></param>
        /// <param name="model"></param>
        /// <param name="customizationId"></param>
        /// <param name="continuous"></param>
        /// <param name="inactivityTimeout"></param>
        /// <param name="keywords"></param>
        /// <param name="keywordsThreshold"></param>
        /// <param name="maxAlternatives"></param>
        /// <param name="wordAlternativesThreshold"></param>
        /// <param name="wordConfidence"></param>
        /// <param name="timestamps"></param>
        /// <param name="profanityFilter"></param>
        /// <param name="smartFormatting"></param>
        /// <param name="speakerLabels"></param>
        /// <returns></returns>
        private SpeechRecognitionResults 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)}");
            }

            SpeechRecognitionResults result = null;

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

                IClient client;
                if (_tokenManager == null)
                {
                    client = this.Client.WithAuthentication(this.UserName, this.Password);
                }
                else
                {
                    client = this.Client.WithAuthentication(_tokenManager.GetToken());
                }

                if (string.IsNullOrEmpty(sessionId))
                {
                    restRequest = client.PostAsync($"{this.Endpoint}/v1/recognize");
                }
                else
                {
                    restRequest = client.PostAsync($"{this.Endpoint}/v1/sessions/{sessionId}")
                                  .WithHeader("Cookie", sessionId);
                }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    restRequest.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))
                    {
                        restRequest.WithArgument("model", model);
                    }

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

                    restRequest.WithBodyContent(formData);
                }

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

            return(result);
        }
示例#18
0
        private async Task <OcrResult> GetHandwritingTextImpl(Stream stream, string url)
        {
            var client = new HttpClient();

            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", apiKey);

            var uri = "https://westus.api.cognitive.microsoft.com/vision/v1.0/recognizeText?handwriting=true";

            HttpResponseMessage response;

            // Request body
            if (stream != null)
            {
                using (var content = new StreamContent(stream))
                {
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                    response = await client.PostAsync(uri, content);
                }
            }
            else
            {
                var json = JsonConvert.SerializeObject(new { url = url });
                using (var content = new StringContent(json))
                {
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    response = await client.PostAsync(uri, content);
                }
            }

            OcrResult            result = null;
            IEnumerable <string> opLocation;

            if (!response.IsSuccessStatusCode)
            {
                var err = await response.Content.ReadAsStringAsync();

                response.EnsureSuccessStatusCode();
            }



            if (response.Headers.TryGetValues("Operation-Location", out opLocation))
            {
                while (true)
                {
                    response = await client.GetAsync(opLocation.First());

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

                    var status = JsonConvert.DeserializeObject <AsyncStatusResult>(txt);
                    if (status.status == "Running" || status.status == "NotStarted")
                    {
                        await Task.Delay(TimeSpan.FromMilliseconds(100));
                    }
                    else
                    {
                        result = status.recognitionResult;

                        break;
                    }
                }
            }

            return(result);
        }
        public async Task <Validation> SubmitAsync(FileValidationRequest request, WaitingStrategy waitingStrategy = default, CancellationToken cancellationToken = default)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var restClient = _restClientFactory.Build();

            // Serialize the validation request (settings only) to JSON

            var settingsContent = restClient
                                  .Serialize(new
            {
                quality       = request.Quality?.NameOrGuid,
                deduplication = request.Deduplication?.NameOrGuid,
                priority      = request.Priority?.Value,
                name          = request.Name,
                // Strips the milliseconds portion from the specified retention period, if any
                retention = request.Retention == null
                        ? null
                        : new TimeSpan(request.Retention.Value.Days,
                                       request.Retention.Value.Hours,
                                       request.Retention.Value.Minutes,
                                       request.Retention.Value.Seconds)
                            .ToString(),
                callback = request.CompletionCallback == null
                        ? null
                        : new
                {
                    url = request.CompletionCallback.ToString()
                },

                // File-specific

                startingRow = request.StartingRow,
                endingRow   = request.EndingRow,
                column      = request.Column,
                sheet       = request.Sheet,
                lineEnding  = request.LineEnding,
                delimiter   = request.Delimiter,
            });

            // Send the request to the Verifalia servers

            using (var postedFileContent = new StreamContent(request.File))
                using (var postedSettingsContent = new StringContent(settingsContent, Encoding.UTF8, WellKnownMimeContentTypes.ApplicationJson))
                {
                    postedFileContent.Headers.ContentType     = request.ContentType;
                    postedSettingsContent.Headers.ContentType = new MediaTypeHeaderValue(WellKnownMimeContentTypes.ApplicationJson);

                    return(await SubmitAsync(restClient,
                                             contentFactory : _ =>
                    {
                        var postedContent = new MultipartFormDataContent();

                        postedContent.Add(postedFileContent, "inputFile",
                                          // HACK: Must send a filename, as the backend expects one
                                          // see https://github.com/dotnet/aspnetcore/blob/425c196cba530b161b120a57af8f1dd513b96f67/src/Http/Headers/src/ContentDispositionHeaderValueIdentityExtensions.cs#L27
                                          "dummy");
                        postedContent.Add(postedSettingsContent, "settings");

                        return Task.FromResult <HttpContent>(postedContent);
                    },
                                             waitingStrategy,
                                             cancellationToken)
                           .ConfigureAwait(false));
                }
        }
        private async Task HandleHttpRequest(HttpContext context, Instance destination, string host, int port, string scheme)
        {
            var requestMessage = new HttpRequestMessage();
            var requestMethod  = context.Request.Method;

            if (!HttpMethods.IsGet(requestMethod) && !HttpMethods.IsHead(requestMethod) && !HttpMethods.IsDelete(requestMethod) && !HttpMethods.IsTrace(requestMethod))
            {
                var streamContent = new StreamContent(context.Request.Body);
                requestMessage.Content = streamContent;
            }

            // All request headers and cookies must be transferend to remote server. Some headers will be skipped
            foreach (var header in context.Request.Headers)
            {
                if (!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()) && requestMessage.Content != null)
                {
                    requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
                }
            }

            requestMessage.Headers.Host = host;
            //recreate remote url
            string uriString = GetUri(context, host, port, scheme);

            requestMessage.RequestUri = new Uri(uriString);
            requestMessage.Method     = new HttpMethod(context.Request.Method);
            try
            {
                using (var responseMessage = await _httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
                {
                    context.Response.StatusCode = (int)responseMessage.StatusCode;
                    foreach (var header in responseMessage.Headers)
                    {
                        context.Response.Headers[header.Key] = header.Value.ToArray();
                    }

                    foreach (var header in responseMessage.Content.Headers)
                    {
                        context.Response.Headers[header.Key] = header.Value.ToArray();
                    }

                    var buffer = new byte[Int32.Parse(context.Response.Headers["Content-Length"])];

                    using (var responseStream = await responseMessage.Content.ReadAsStreamAsync())
                    {
                        int len  = 0;
                        int full = 0;
                        while ((len = await responseStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                        {
                            await context.Response.Body.WriteAsync(buffer, 0, buffer.Length);

                            full += buffer.Length;
                        }

                        //context.Response.Headers.Remove("transfer-encoding");
                    }

                    Logger.Log(context.Request.GetDisplayUrl(), requestMessage.Method.Method, destination, uriString, context.Response.StatusCode);
                }
            }
            catch (HttpRequestException)
            {
                Logger.Log(context.Request.GetDisplayUrl(), requestMessage.Method.Method, destination, uriString, 500);
                await context.Response.WriteAsync("Target server unavaliable");
            }
        }
示例#21
0
        public async Task <JsonResult> Upload()
        {
            try
            {
                IFormFile file = Request.Form.Files[0];

                Guid     fileId  = Guid.NewGuid();
                DateTime nowDate = DateTime.Now;
                string   path    = string.Format("/uploadfiles/{0:yyyy/MMdd}/{1}", nowDate, fileId);
                string   url     = string.Format("{0}/{1}", path, file.FileName);
                // 服务器的存储全路径
                string destFileName = MapPath(url);
                // 创建目录路径
                if (!Directory.Exists(Path.GetDirectoryName(destFileName)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(destFileName));
                }

                SysAttachment fileData = new SysAttachment();
                fileData.Id = fileId;
                //fileDatas.RelationID = "";
                fileData.Name         = file.FileName;
                fileData.Names        = "";
                fileData.Url          = url;
                fileData.Type         = 0;
                fileData.Suffix       = Path.GetExtension(file.FileName).ToLower();
                fileData.Path         = path;
                fileData.Status       = 0;
                fileData.Size         = 0;
                fileData.CreateBy     = "";
                fileData.CreateByName = SSOClient.User.UserName;
                fileData.CreateTime   = nowDate;

                string ThumbnailSizes = Request.Form["thumbnailSizes"].FirstOrDefault();
                if (isLocal)
                {
                    //保存本地
                    using (var stream = System.IO.File.Create(destFileName))
                    {
                        await file.CopyToAsync(stream);
                    }
                    // 图片文件扩展名验证正则表达式
                    Regex regexExtension = new Regex(@".*\.(jpg|jpeg|png|gif|bmp)");
                    if (regexExtension.IsMatch(destFileName.ToLower()))
                    {
                        string[] ThumbnailSizeArr = new string[] { };
                        //生成缩略图
                        if (!string.IsNullOrEmpty(ThumbnailSizes) && (ThumbnailSizeArr = ThumbnailSizes.Split(';')).Length > 0)
                        {
                            string[] fileNamesArr = new string[ThumbnailSizeArr.Length];
                            for (int i = 0; i < ThumbnailSizeArr.Length; i++)
                            {
                                string size          = ThumbnailSizeArr[i];
                                string ThumbFileName = Path.GetFileNameWithoutExtension(url) + "_" + size + fileData.Suffix;
                                string ThumbPath     = url.Replace(Path.GetFileName(url), ThumbFileName);
                                ThumbnailHelper.MakeThumbnail(Convert.ToInt32(size), MapPath(url), MapPath(ThumbPath));
                                fileNamesArr[i] = ThumbFileName;
                            }
                            fileData.Names = string.Join("|", fileNamesArr);
                        }
                    }
                }
                else
                {
                    //保存文件服务器
                    HttpClient client             = new HttpClient();
                    MultipartFormDataContent form = new MultipartFormDataContent();

                    byte[] uploadFileBytes = new byte[file.Length];
                    file.OpenReadStream().Read(uploadFileBytes, 0, (int)file.Length);
                    MemoryStream  stream      = new MemoryStream(uploadFileBytes);
                    StreamContent fileContent = new StreamContent(stream);
                    fileContent.Headers.ContentType                 = new MediaTypeHeaderValue("application/octet-stream");
                    fileContent.Headers.ContentDisposition          = new ContentDispositionHeaderValue("form-data");
                    fileContent.Headers.ContentDisposition.FileName = url;
                    form.Add(fileContent);

                    StringContent thumbnailSizes = new StringContent(ThumbnailSizes);
                    thumbnailSizes.Headers.ContentDisposition      = new ContentDispositionHeaderValue("form-data");
                    thumbnailSizes.Headers.ContentDisposition.Name = "thumbnailSizes";
                    form.Add(thumbnailSizes);

                    HttpResponseMessage res = client.PostAsync(fileServer, form).Result;
                    var     json            = res.Content.ReadAsStringAsync().Result;
                    JObject result          = JObject.Parse(json);

                    fileData.Path  = (string)result["data"]["path"];
                    fileData.Names = (string)result["data"]["names"];
                    fileData.Url   = (string)result["data"]["url"];
                }
                return(Json(new { Code = 0, Msg = "", Data = fileData }));
            }
            catch (Exception ex)
            {
                LogHelper.SaveLog(ex);
                return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" }));
            }
        }
示例#22
0
        public async Task PostTree(string filePath, double latitude, double longitude, string description)
        {
            using (FileStream file = File.OpenRead(filePath))
            {
                StreamContent photo = new StreamContent(file);
                photo.Headers.ContentType = new MediaTypeHeaderValue("image/png");

                HttpClient httpClient = new HttpClient();

                // Set the access token
                httpClient.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", await App.AuthService.GetAccessToken());

                MultipartFormDataContent form = new MultipartFormDataContent();

                if (description != null && description.Trim() != string.Empty)
                {
                    form.Add(new StringContent(description), "Description");
                }

                form.Add(new StringContent($"{latitude.ToString("G", CultureInfo.InvariantCulture)}, {longitude.ToString("G", CultureInfo.InvariantCulture)}"), "Coordinates");
                form.Add(photo, "Photo", filePath.Substring(filePath.LastIndexOf("/") + 1));

                HttpResponseMessage response = await httpClient.PostAsync(_postTreeUrl, form);

                if (response.StatusCode == HttpStatusCode.BadRequest)
                {
                    string message = string.Empty;

                    dynamic json = JObject.Parse(await response.Content.ReadAsStringAsync());

                    if (json.errors.Photo != null)
                    {
                        foreach (string error in json.errors.Photo)
                        {
                            message += $"{error}\n";
                        }
                    }

                    if (json.errors.Description != null)
                    {
                        foreach (string error in json.errors.Description)
                        {
                            message += $"{error}\n";
                        }
                    }

                    if (json.errors.Coordinates != null)
                    {
                        foreach (string error in json.errors.Coordinates)
                        {
                            message += $"{error}\n";
                        }
                    }

                    throw new ArgumentException(message);
                }

                if (!response.IsSuccessStatusCode)
                {
                    throw new HttpRequestException();
                }
            }
        }
示例#23
0
        public void UploadMap()
        {
            ErrorText.enabled = false;

            if (!CheckUserInput())
            {
                return;
            }
            string uniqueTempPathInProject  = GetUniqueTempPath() + ".zip";
            string tempPathForWrapperFolder = GetUniqueTempPath();

            FileDirectory.DirectoryCopyWithSourceFolder(MapFolderPathInputField.text, tempPathForWrapperFolder, true);

            //Move Map Folder into a wrapper folder so map folder lies within the zip
            try
            {
                //Zip everything
                ZipUtil.CreateZipFromFolder(uniqueTempPathInProject, null, tempPathForWrapperFolder);
            }
            catch (Exception e)
            {
                OnError("Could not package map. Is the path you entered correct? Exception is:\n" + e.Message);
                return;
            }

            Debug.Log("Writing map to temp file: " + uniqueTempPathInProject);
            HttpClient httpClient         = new HttpClient();
            MultipartFormDataContent form = new MultipartFormDataContent();

            form.Add(new StringContent("{\"isRanked\":" + (RankedToggle.isOn ? "true" : "false") + " }", Encoding.UTF8, "application/json"), "metadata");
            FileStream    fileStream    = new FileStream(uniqueTempPathInProject, FileMode.Open);
            StreamContent streamContent = new StreamContent(fileStream);

            streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
            form.Add(streamContent, "file", Path.GetFileName(uniqueTempPathInProject));
            try
            {
                //var token = GetAccessTokenFromOwnAuthSvr();
                //httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token.AccessToken);
            }
            catch (Exception e)
            {
                OnError("Login failed, please check connection and login data. Exception is : \n" + e.Message);
                return;
            }

            httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
            try
            {
                HttpResponseMessage res = httpClient.PostAsync(Config.ApiUrl + "/maps/upload", form).Result;
                try
                {
                    res.EnsureSuccessStatusCode();
                }
                catch (Exception e)
                {
                    OnError(
                        "JAVA-API complains: \n" + res.Content.ReadAsStringAsync().Result + "\n\nException is: \n" + e.Message);
                }
            }
            catch (Exception e)
            {
                OnError("Sending failed. Maybe map is too big... Exception was: \n" + e.Message);
            }

            httpClient.Dispose();
            form.Dispose();
            GenericInfoPopup.ShowInfo("Uploaded Successful... Check the vault to see ;)");
        }
示例#24
0
 private bool IsKeepAliveMessageFromTwitterApi(StreamContent strm)
 {
     return(string.IsNullOrWhiteSpace(strm.Content));
 }
示例#25
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;
                }
            }
        }
示例#26
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")))
            {
                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 if (request.Headers.ContainsKey("content-type"))
                    {
                        requestMessage.Content = new ByteArrayContent(
                            request.Body == null ? new byte[] { } : Encoding.UTF8.GetBytes((string)request.Body));

                        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 (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);
                            if (string.IsNullOrEmpty(fileInfo.FileName))
                            {
                                fileInfo.FileName = "file";
                            }
                            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));
        }
示例#27
0
        public string GetPdfUrl(string switches, string html, string fileName = "", string header = "", string footer = "", string contentDisposition = "")
        {
            var context = HttpContext.Current;
            var webRoot = string.Format("{0}://{1}{2}",
                                        context.Request.Url.Scheme,
                                        context.Request.Url.Host,
                                        context.Request.Url.Port == 80
                  ? string.Empty : ":" + context.Request.Url.Port);

            webRoot = webRoot.TrimEnd('/');
            var requestPath    = context.Request.Path;
            var packageBuilder = new PackageBuilder(new MapPathResolver(), webRoot);

            packageBuilder.AddHtmlToPackage(html, requestPath, "index");
            if (!string.IsNullOrEmpty(header))
            {
                packageBuilder.AddHtmlToPackage(header, requestPath, "header");
            }
            if (!string.IsNullOrEmpty(footer))
            {
                packageBuilder.AddHtmlToPackage(footer, requestPath, "footer");
            }
            var assets = packageBuilder.AssetsContents
                         .Select(a => new KeyValuePair <string, byte[]>(
                                     a.NewUri + "." + a.Suffix, a.Content))
                         .ToDictionary(x => x.Key, x => x.Value);
            var payload = new PdfRequestPayloadV2
            {
                Id                 = Guid.NewGuid(),
                Filename           = fileName,
                Switches           = switches,
                HtmlAssets         = assets,
                ContentDisposition = contentDisposition
            };
            string gzipIt = ConfigurationManager.AppSettings["RotativaGZip"];

            if (HttpContext.Current != null && HttpContext.Current.Request.IsLocal && gzipIt == null)
            {
                gzipIt = "1";
            }
            if (gzipIt == "1")
            {
                var httpClient = new HttpClient(new GzipCompressingHandler(new HttpClientHandler()));
                using (
                    var request = CreateRequest("/v2", "application/json", HttpMethod.Post))
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        var sw = new StreamWriter(ms);//, new UnicodeEncoding());
                        Serializer.Serialize(ms, payload);
                        ms.Position = 0;
                        HttpContent content = new StreamContent(ms);
                        request.Content = content; // new GzipContent(content);
                        using (
                            HttpResponseMessage response =
                                httpClient.SendAsync(request, new CancellationTokenSource().Token).Result)
                        {
                            var httpResponseMessage = response;
                            var result      = response.Content.ReadAsStringAsync();
                            var jsonReponse = JObject.Parse(result.Result);
                            if (response.StatusCode == HttpStatusCode.Unauthorized)
                            {
                                var error = jsonReponse["error"].Value <string>();
                                throw new UnauthorizedAccessException(error);
                            }
                            var pdfUrl = jsonReponse["pdfUrl"].Value <string>(); //
                            return(pdfUrl);
                        }
                    }
                }
            }
            else
            {
                var httpClient = new HttpClient();
                using (
                    var request = CreateRequest("/v2", "application/json", HttpMethod.Post))
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        var sw = new StreamWriter(ms, new UnicodeEncoding());
                        Serializer.Serialize(ms, payload);
                        ms.Position = 0;
                        HttpContent content = new StreamContent(ms);
                        request.Content = content;

                        using (
                            HttpResponseMessage response =
                                httpClient.SendAsync(request, new CancellationTokenSource().Token).Result)
                        {
                            var httpResponseMessage = response;
                            var result      = response.Content.ReadAsStringAsync();
                            var jsonReponse = JObject.Parse(result.Result);
                            if (response.StatusCode == HttpStatusCode.Unauthorized)
                            {
                                var error = jsonReponse["error"].Value <string>();
                                throw new UnauthorizedAccessException(error);
                            }
                            var pdfUrl = jsonReponse["pdfUrl"].Value <string>(); //
                            return(pdfUrl);
                        }
                    }
                }
            }
        }
示例#28
0
        private async void Compress()
        {
            try
            {
                string zipFileName = Guid.ToString().Replace("-", "") + "_" + DateTime.UtcNow.ToString("yyyyMMddhhmmss") + "_Data_zip";
                string zipFolder   = Path.Combine(TelemetryFolder, "Zip");

                if (!Directory.Exists(zipFolder))
                {
                    Directory.CreateDirectory(zipFolder);
                }

                string LocalZipfileName = Path.Combine(zipFolder, zipFileName);

                ZipFile.CreateFromDirectory(TelemetryDataFolder, LocalZipfileName);

                if (File.Exists(LocalZipfileName))
                {
                    foreach (string fn in Directory.GetFiles(TelemetryDataFolder))
                    {
                        File.Delete(fn);
                    }
                }

                if (!NetworkAvailable)
                {
                    return;
                }


                // TODO; run in parallel
                foreach (string zipfile in Directory.GetFiles(zipFolder))
                {
                    FileStream    fileStream = new FileStream(Path.Combine(TelemetryFolder, zipfile), FileMode.Open);
                    StreamContent content    = new StreamContent(fileStream);
                    try
                    {
                        HttpResponseMessage response = await mClient.PostAsync("api/Telemetry/" + zipFileName.Replace(".", "_"), content);

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

                        fileStream.Close();

                        if (response.IsSuccessStatusCode)
                        {
                            if (rc == "OK")
                            {
                                System.IO.File.Delete(zipfile);
                            }
                        }
                        else
                        {
                            //
                        }
                    }
                    catch
                    {
                        // Failed to upload
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Telemetry Ex: " + ex.Message);
            }

            done = true;
        }
        public async Task <bool> Upload()
        {
            try
            {
                // var fileuploadPath = ConfigurationManager.AppSettings["FileUploadLocation"];



                var fullPath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/App_Data/ProfileImages");



                var provider = new MultipartFormDataStreamProvider(fullPath);
                var content  = new StreamContent(HttpContext.Current.Request.GetBufferlessInputStream(true));
                foreach (var header in Request.Content.Headers)
                {
                    content.Headers.TryAddWithoutValidation(header.Key, header.Value);
                }



                await content.ReadAsMultipartAsync(provider);



                //Code for renaming the random file to Original file name
                // string uploadingFileName = provider.FileData.Select(x => x.LocalFileName).FirstOrDefault();
                //      string originalFileName = String.Concat(fileuploadPath, "\\" + (provider.Contents[0].Headers.ContentDisposition.FileName).Trim(new Char[] { '"' }));



                int    uId   = int.Parse(HttpContext.Current.Request.Params.Get("uid"));
                string email = HttpContext.Current.Request.Params.Get("email");



                string fileName         = email + "_formal_" + uId + ".jpg";
                string originalFileName = String.Concat(fullPath, "\\" + fileName);



                if (File.Exists(originalFileName))
                {
                    File.Delete(originalFileName);
                }



                //File.Move(uploadingFileName, originalFileName);
                //return fileName;
                // Code renaming ends...
                bool flag = cdf.UpdateProfilePic(uId, fileName);
                if (flag == true)
                {
                    string uploadingFileName = provider.FileData.Select(x => x.LocalFileName).FirstOrDefault();
                    File.Move(uploadingFileName, originalFileName);
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
                return(false);
            }
        }
        /// <summary>
        /// Uploads a new package or a new version of an existing package. The content
        /// of the package is sent as a .nupkg file embedded in the HTTP request.
        /// </summary>
        /// <remarks>
        /// Required permissions: Packages.Create.
        /// </remarks>
        /// <param name='file'>
        /// </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="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse> UploadPackageWithHttpMessagesAsync(Stream file, Dictionary <string, List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (file == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "file");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("file", file);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "UploadPackage", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "odata/Processes/UiPath.Server.Configuration.OData.UploadPackage").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 (file != null)
            {
                StreamContent _file = new StreamContent(file);
                _file.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                FileStream _fileAsFileStream = file as FileStream;
                if (_fileAsFileStream != null)
                {
                    ContentDispositionHeaderValue _contentDispositionHeaderValue = new ContentDispositionHeaderValue("form-data");
                    _contentDispositionHeaderValue.Name     = "file";
                    _contentDispositionHeaderValue.FileName = _fileAsFileStream.Name;
                    _file.Headers.ContentDisposition        = _contentDispositionHeaderValue;
                }
                _multiPartContent.Add(_file, "file");
            }
            _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)
            {
                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();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
示例#31
0
        public async Task CopyToAsync_CallMultipleTimesWithStreamNotSupportingSeeking_ThrowsInvalidOperationException()
        {
            var source = new MockStream(new byte[10], false, true); // doesn't support seeking.
            var content = new StreamContent(source);

            var destination1 = new MemoryStream();
            await content.CopyToAsync(destination1);
            // Use hardcoded expected length, since source.Length would throw (source stream gets disposed if non-seekable).
            Assert.Equal(10, destination1.Length);

            // Note that the InvalidOperationException is thrown in CopyToAsync(). It is not thrown inside the task.
            var destination2 = new MemoryStream();
            Assert.Throws<InvalidOperationException>(() => { Task t = content.CopyToAsync(destination2); });
        }
示例#32
0
        private static void ForwardRequest(HttpEntityManager manager, Uri forwardUri)
        {
            var srcReq  = manager.HttpEntity.Request;
            var request = new HttpRequestMessage();

            request.RequestUri = forwardUri;
            request.Method     = new System.Net.Http.HttpMethod(srcReq.HttpMethod);

            var hasContentLength = false;

            // Copy unrestricted headers (including cookies, if any)
            foreach (var headerKey in srcReq.GetHeaderKeys())
            {
                try {
                    switch (headerKey.ToLower())
                    {
                    case "accept":
                        request.Headers.Accept.ParseAdd(srcReq.GetHeaderValues(headerKey).ToString());
                        break;

                    case "connection":
                        break;

                    case "content-type":
                        break;

                    case "content-length":
                        hasContentLength = true;
                        break;

                    case "date":
                        request.Headers.Date = DateTime.Parse(srcReq.GetHeaderValues(headerKey).ToString());
                        break;

                    case "expect":
                        break;

                    case "host":
                        request.Headers.Host = $"{forwardUri.Host}:{forwardUri.Port}";
                        break;

                    case "if-modified-since":
                        request.Headers.IfModifiedSince = DateTime.Parse(srcReq.GetHeaderValues(headerKey).ToString());
                        break;

                    case "proxy-connection":
                        break;

                    case "range":
                        break;

                    case "referer":
                        request.Headers.Referrer = new Uri(srcReq.GetHeaderValues(headerKey).ToString());
                        break;

                    case "transfer-encoding":
                        request.Headers.TransferEncoding.ParseAdd(srcReq.GetHeaderValues(headerKey).ToString());
                        break;

                    case "user-agent":
                        request.Headers.UserAgent.ParseAdd(srcReq.GetHeaderValues(headerKey).ToString());
                        break;

                    default:
                        request.Headers.Add(headerKey, srcReq.GetHeaderValues(headerKey).ToString());
                        break;
                    }
                } catch (System.FormatException) {
                    request.Headers.TryAddWithoutValidation(headerKey, srcReq.GetHeaderValues(headerKey).ToString());
                }
            }

            if (!request.Headers.Contains(ProxyHeaders.XForwardedHost))
            {
                request.Headers.Add(ProxyHeaders.XForwardedHost, string.Format("{0}:{1}",
                                                                               manager.RequestedUrl.Host, manager.RequestedUrl.Port));
            }

            // Copy content (if content body is allowed)
            if (!string.Equals(srcReq.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase) &&
                !string.Equals(srcReq.HttpMethod, "HEAD", StringComparison.OrdinalIgnoreCase) &&
                hasContentLength)
            {
                var streamContent = new StreamContent(srcReq.InputStream);
                streamContent.Headers.ContentLength = srcReq.ContentLength64;
                request.Content = streamContent;

                MediaTypeHeaderValue contentType;
                if (MediaTypeHeaderValue.TryParse(srcReq.ContentType, out contentType))
                {
                    streamContent.Headers.ContentType = contentType;
                }
            }

            ForwardResponse(manager, request);
        }
示例#33
0
        public async Task ContentReadStream_GetProperty_ReturnOriginalStream()
        {
            var source = new MockStream(new byte[10]);
            var content = new StreamContent(source);

            Stream stream = await content.ReadAsStreamAsync();
            Assert.False(stream.CanWrite);
            Assert.Equal(source.Length, stream.Length);
            Assert.Equal(0, source.ReadCount);
            Assert.NotSame(source, stream);
        }
示例#34
0
 public void CopyToAsync_NullDestination_ThrowsArgumentnullException()
 {
     var source = new MockStream(new byte[10]);
     var content = new StreamContent(source);
     Assert.Throws<ArgumentNullException>(() => { Task t = content.CopyToAsync(null); });
 }
示例#35
0
        public async Task ContentReadStream_CheckResultProperties_ValuesRepresentReadOnlyStream()
        {
            byte[] data = new byte[10];
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = (byte)i;
            }

            var source = new MockStream(data);

            var content = new StreamContent(source);
            Stream contentReadStream = await content.ReadAsStreamAsync();

            // The following checks verify that the stream returned passes all read-related properties to the 
            // underlying MockStream and throws when using write-related members.

            Assert.False(contentReadStream.CanWrite);
            Assert.True(contentReadStream.CanRead);
            Assert.Equal(source.Length, contentReadStream.Length);

            Assert.Equal(1, source.CanSeekCount);
            _output.WriteLine(contentReadStream.CanSeek.ToString());
            Assert.Equal(2, source.CanSeekCount);

            contentReadStream.Position = 3; // No exception.
            Assert.Equal(3, contentReadStream.Position);
          
            byte byteOnIndex3 = (byte)contentReadStream.ReadByte();
            Assert.Equal(data[3], byteOnIndex3);

            byte[] byteOnIndex4 = new byte[1];
            int result = await contentReadStream.ReadAsync(byteOnIndex4, 0, 1);
            Assert.Equal(1, result);
                        
            Assert.Equal(data[4], byteOnIndex4[0]);

            byte[] byteOnIndex5 = new byte[1];
            Assert.Equal(1, contentReadStream.Read(byteOnIndex5, 0, 1));
            Assert.Equal(data[5], byteOnIndex5[0]);

            contentReadStream.ReadTimeout = 123;
            Assert.Equal(123, source.ReadTimeout);
            Assert.Equal(123, contentReadStream.ReadTimeout);

            Assert.Equal(0, source.CanTimeoutCount);
            _output.WriteLine(contentReadStream.CanTimeout.ToString());
            Assert.Equal(1, source.CanTimeoutCount);

            Assert.Equal(0, source.SeekCount);
            contentReadStream.Seek(0, SeekOrigin.Begin);
            Assert.Equal(1, source.SeekCount);

            Assert.Throws<NotSupportedException>(() => { contentReadStream.WriteTimeout = 5; });
            Assert.Throws<NotSupportedException>(() => contentReadStream.WriteTimeout.ToString());
            Assert.Throws<NotSupportedException>(() => contentReadStream.Flush());
            Assert.Throws<NotSupportedException>(() => contentReadStream.SetLength(1));
            Assert.Throws<NotSupportedException>(() => contentReadStream.Write(null, 0, 0));
            Assert.Throws<NotSupportedException>(() => contentReadStream.WriteByte(1));

            Assert.Equal(0, source.DisposeCount);
            contentReadStream.Dispose();
            Assert.Equal(1, source.DisposeCount);
        }
示例#36
0
        /// <summary>
        /// Make an HTTP request while retrying after failed attempts or timeouts.
        /// </summary>
        /// <remarks>
        /// This method accepts a factory to create instances of the <see cref="HttpRequestMessage"/> because
        /// requests cannot always be used. For example, suppose the request is a POST and contains content
        /// of a stream that can only be consumed once.
        /// </remarks>
        public async Task <HttpResponseMessage> SendAsync(
            HttpRetryHandlerRequest request,
            string source,
            ILogger log,
            CancellationToken cancellationToken)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            var tries = 0;
            HttpResponseMessage response = null;
            var success = false;

            while (tries < request.MaxTries && !success)
            {
                if (tries > 0)
                {
                    await Task.Delay(request.RetryDelay, cancellationToken);
                }

                tries++;
                success = true;

                using (var requestMessage = request.RequestFactory())
                {
                    var stopwatches   = new List <Stopwatch>(2);
                    var bodyStopwatch = new Stopwatch();
                    stopwatches.Add(bodyStopwatch);
                    Stopwatch headerStopwatch = null;
                    if (request.CompletionOption == HttpCompletionOption.ResponseHeadersRead)
                    {
                        headerStopwatch = new Stopwatch();
                        stopwatches.Add(headerStopwatch);
                    }
#if USE_HTTPREQUESTMESSAGE_OPTIONS
                    requestMessage.Options.Set(new HttpRequestOptionsKey <List <Stopwatch> >(StopwatchPropertyName), stopwatches);
#else
                    // stop ignoring CS0618 when fixing https://github.com/NuGet/Home/issues/9981
#pragma warning disable CS0618
                    requestMessage.Properties[StopwatchPropertyName] = stopwatches;
#pragma warning restore CS0618
#endif
                    var requestUri = requestMessage.RequestUri;

                    try
                    {
                        // The only time that we will be disposing this existing response is if we have
                        // successfully fetched an HTTP response but the response has an status code indicating
                        // failure (i.e. HTTP status code >= 500).
                        //
                        // If we don't even get an HTTP response message because an exception is thrown, then there
                        // is no response instance to dispose. Additionally, we cannot use a finally here because
                        // the caller needs the response instance returned in a non-disposed state.
                        //
                        // Also, remember that if an HTTP server continuously returns a failure status code (like
                        // 500 Internal Server Error), we will retry some number of times but eventually return the
                        // response as-is, expecting the caller to check the status code as well. This results in the
                        // success variable being set to false but the response being returned to the caller without
                        // disposing it.
                        response?.Dispose();

                        // Add common headers to the request after it is created by the factory. This includes
                        // X-NuGet-Session-Id which is added to all nuget requests.
                        foreach (var header in request.AddHeaders)
                        {
                            requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value);
                        }

                        log.LogInformation("  " + string.Format(
                                               CultureInfo.InvariantCulture,
                                               Strings.Http_RequestLog,
                                               requestMessage.Method,
                                               requestUri));

                        // Issue the request.
                        var timeoutMessage = string.Format(
                            CultureInfo.CurrentCulture,
                            Strings.Http_Timeout,
                            requestMessage.Method,
                            requestUri,
                            (int)request.RequestTimeout.TotalMilliseconds);
                        response = await TimeoutUtility.StartWithTimeout(
                            async timeoutToken =>
                        {
                            bodyStopwatch.Start();
                            headerStopwatch?.Start();
                            var responseMessage = await request.HttpClient.SendAsync(requestMessage, request.CompletionOption, timeoutToken);
                            headerStopwatch?.Stop();
                            return(responseMessage);
                        },
                            request.RequestTimeout,
                            timeoutMessage,
                            cancellationToken);

                        // Wrap the response stream so that the download can timeout.
                        if (response.Content != null)
                        {
                            var networkStream = await response.Content.ReadAsStreamAsync();

                            var timeoutStream   = new DownloadTimeoutStream(requestUri.ToString(), networkStream, request.DownloadTimeout);
                            var inProgressEvent = new ProtocolDiagnosticInProgressHttpEvent(
                                source,
                                requestUri,
                                headerStopwatch?.Elapsed,
                                (int)response.StatusCode,
                                isRetry: request.IsRetry || tries > 1,
                                isCancelled: false,
                                isLastAttempt: tries == request.MaxTries && request.IsLastAttempt);
                            var diagnosticsStream = new ProtocolDiagnosticsStream(timeoutStream, inProgressEvent, bodyStopwatch, ProtocolDiagnostics.RaiseEvent);

                            var newContent = new StreamContent(diagnosticsStream);

                            // Copy over the content headers since we are replacing the HttpContent instance associated
                            // with the response message.
                            foreach (var header in response.Content.Headers)
                            {
                                newContent.Headers.TryAddWithoutValidation(header.Key, header.Value);
                            }

                            response.Content = newContent;
                        }

                        log.LogInformation("  " + string.Format(
                                               CultureInfo.InvariantCulture,
                                               Strings.Http_ResponseLog,
                                               response.StatusCode,
                                               requestUri,
                                               bodyStopwatch.ElapsedMilliseconds));

                        if ((int)response.StatusCode >= 500)
                        {
                            success = false;
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        response?.Dispose();

                        ProtocolDiagnostics.RaiseEvent(new ProtocolDiagnosticHttpEvent(
                                                           timestamp: DateTime.UtcNow,
                                                           source,
                                                           requestUri,
                                                           headerDuration: null,
                                                           eventDuration: bodyStopwatch.Elapsed,
                                                           httpStatusCode: null,
                                                           bytes: 0,
                                                           isSuccess: false,
                                                           isRetry: request.IsRetry || tries > 1,
                                                           isCancelled: true,
                                                           isLastAttempt: tries == request.MaxTries && request.IsLastAttempt));

                        throw;
                    }
                    catch (Exception e)
                    {
                        success = false;

                        response?.Dispose();

                        ProtocolDiagnostics.RaiseEvent(new ProtocolDiagnosticHttpEvent(
                                                           timestamp: DateTime.UtcNow,
                                                           source,
                                                           requestUri,
                                                           headerDuration: null,
                                                           eventDuration: bodyStopwatch.Elapsed,
                                                           httpStatusCode: null,
                                                           bytes: 0,
                                                           isSuccess: false,
                                                           isRetry: request.IsRetry || tries > 1,
                                                           isCancelled: false,
                                                           isLastAttempt: tries == request.MaxTries && request.IsLastAttempt));

                        if (tries >= request.MaxTries)
                        {
                            throw;
                        }

                        log.LogInformation(string.Format(
                                               CultureInfo.CurrentCulture,
                                               Strings.Log_RetryingHttp,
                                               requestMessage.Method,
                                               requestUri,
                                               requestMessage)
                                           + Environment.NewLine
                                           + ExceptionUtilities.DisplayMessage(e));
                    }
                }
            }

            return(response);
        }
示例#37
0
        static async Task Main(string[] args)
        {
            //D:\Labs\Serv\Text.txt
            Console.WriteLine("Введите путь к файлу: ");
            string   path    = Convert.ToString(Console.ReadLine());
            FileInfo fileInf = new FileInfo(path);

            if (fileInf.Exists)
            {
                string cryptppath   = fileInf.DirectoryName + "\\" + "Crypted" + fileInf.Extension;
                string uncryptppath = fileInf.DirectoryName + "\\" + "FromServerCrypt.Zip";
                string decryptppath = fileInf.DirectoryName + "\\" + "FromServerDeCrypted.Zip";
                Crypted.EncryptFile(path, cryptppath);
                HttpClient httpClient = new HttpClient();
                var        content    = new MultipartFormDataContent();
                using (var fstream = File.OpenRead(cryptppath))
                {
                    var streamContent = new StreamContent(fstream);
                    streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                    {
                        Name = "file"
                        ,
                        FileName = Path.GetFileName(cryptppath),
                    };
                    streamContent.Headers.Add("type", fileInf.Extension);
                    content.Add(streamContent);
                    HttpResponseMessage response = await httpClient.PostAsync("https://localhost:44308/GetFile", content);

                    response.EnsureSuccessStatusCode();
                    httpClient.Dispose();
                    string sd = await response.Content.ReadAsStringAsync();

                    using (FileStream stream = new FileStream(uncryptppath, FileMode.OpenOrCreate))
                    {
                        byte[] array = await response.Content.ReadAsByteArrayAsync();

                        stream.Write(array, 0, array.Length);
                    }
                }
                FileInfo Delete = new FileInfo(cryptppath);
                Delete.Delete();
                Crypted.DecryptFile(uncryptppath, decryptppath);
                Delete = new FileInfo(uncryptppath);
                Delete.Delete();
                string file = "UncryptFile" + fileInf.Extension;
                string cig  = "SignedFile.cig";
                using (var zip = ZipFile.Open(decryptppath, ZipArchiveMode.Update))
                {
                    var entfile  = zip.GetEntry(file);
                    var entcig   = zip.GetEntry(cig);
                    var tempFile = Path.GetTempFileName();
                    var tempCig  = Path.GetTempFileName();
                    entfile.ExtractToFile(tempFile, true);
                    entcig.ExtractToFile(tempCig, true);
                    byte[] hash     = File.ReadAllBytes(tempFile);
                    byte[] signhash = File.ReadAllBytes(tempCig);
                    if (SignDoc.Verify(hash, signhash) == true)
                    {
                        Console.WriteLine("\n1.Файл 2.Его подпись. Подпись: подтверждена");
                    }
                    else
                    {
                        Console.WriteLine("Операция провалена");
                    }
                }
            }
            Console.ReadKey();
        }
示例#38
0
 public CacheResponse(Stream stream)
     : base(HttpStatusCode.OK)
 {
     Headers.Add("X-NuGet-FileCache", "true");
     Content = new StreamContent(stream);
 }
        /// <summary>
        /// 给.NET Core使用的HttpPost请求公共设置方法
        /// </summary>
        /// <param name="url"></param>
        /// <param name="hc"></param>
        /// <param name="cookieContainer"></param>
        /// <param name="postStream"></param>
        /// <param name="fileDictionary">需要上传的文件,Key:对应要上传的Name,Value:本地文件名,或文件内容的Base64编码</param>
        /// <param name="refererUrl"></param>
        /// <param name="encoding"></param>
        /// <param name="certName">证书唯一名称,如果不需要则保留null</param>
        /// <param name="useAjax"></param>
        /// <param name="headerAddition">header附加信息</param>
        /// <param name="timeOut"></param>
        /// <param name="checkValidationResult"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static HttpClient HttpPost_Common_NetCore(
            IServiceProvider serviceProvider,
            string url, out HttpContent hc, CookieContainer cookieContainer = null,
            Stream postStream = null, Dictionary <string, string> fileDictionary = null, string refererUrl = null,
            Encoding encoding = null, string certName = null, bool useAjax = false, Dictionary <string, string> headerAddition = null,
            int timeOut       = Config.TIME_OUT, bool checkValidationResult = false, string contentType = HttpClientHelper.DEFAULT_CONTENT_TYPE)
        {
            //HttpClientHandler handler = HttpClientHelper.GetHttpClientHandler(cookieContainer, SenparcHttpClientWebProxy, DecompressionMethods.GZip);

            //if (checkValidationResult)
            //{
            //    handler.ServerCertificateCustomValidationCallback = new Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool>(CheckValidationResult);
            //}

            //if (cer != null)
            //{
            //    handler.ClientCertificates.Add(cer);
            //}

            //TODO:此处 handler并没有被使用到,因此 cer 实际无法传递(这个也是 .net core 目前针对多 cer 场景的一个问题)

            var senparcHttpClient = SenparcHttpClient.GetInstanceByName(serviceProvider, certName);

            senparcHttpClient.SetCookie(new Uri(url), cookieContainer);//设置Cookie

            HttpClient client = senparcHttpClient.Client;

            HttpClientHeader(client, refererUrl, useAjax, headerAddition, timeOut);

            #region 处理Form表单文件上传

            var formUploadFile = fileDictionary != null && fileDictionary.Count > 0;//是否用Form上传文件
            if (formUploadFile)
            {
                contentType = "multipart/form-data";

                //通过表单上传文件
                string boundary = "----" + SystemTime.Now.Ticks.ToString("x");

                var multipartFormDataContent = new MultipartFormDataContent(boundary);
                hc = multipartFormDataContent;

                foreach (var file in fileDictionary)
                {
                    try
                    {
                        var    fileNameOrFileData = file.Value;
                        var    formFileData       = new FormFileData(fileNameOrFileData);
                        string fileName           = null;

                        //准备文件流
                        var memoryStream = new MemoryStream();//这里不能释放,否则如在请求的时候 memoryStream 已经关闭会发生错误
                        if (formFileData.TryLoadStream(memoryStream).ConfigureAwait(false).GetAwaiter().GetResult())
                        {
                            //fileNameOrFileData 中储存的储存的是 Stream
                            fileName = Path.GetFileName(formFileData.GetAvaliableFileName(SystemTime.NowTicks.ToString()));
                        }
                        else
                        {
                            //fileNameOrFileData 中储存的储存的可能是文件地址或备注
                            using (var fileStream = FileHelper.GetFileStream(fileNameOrFileData))
                            {
                                if (fileStream != null)
                                {
                                    //存在文件
                                    fileStream.CopyTo(memoryStream);//TODO:可以使用异步方法
                                    fileName = Path.GetFileName(fileNameOrFileData);
                                    fileStream.Dispose();
                                }
                                else
                                {
                                    //只是注释
                                    multipartFormDataContent.Add(new StringContent(file.Value), "\"" + file.Key + "\"");
                                }
                            }
                        }

                        if (memoryStream.Length > 0)
                        {
                            //有文件内容
                            //multipartFormDataContent.Add(new StreamContent(memoryStream), file.Key, Path.GetFileName(fileName)); //报流已关闭的异常

                            memoryStream.Seek(0, SeekOrigin.Begin);
                            multipartFormDataContent.Add(CreateFileContent(memoryStream, file.Key, fileName), file.Key, fileName);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }

                hc.Headers.ContentType = MediaTypeHeaderValue.Parse(string.Format("multipart/form-data; boundary={0}", boundary));
            }
            else
            {
                if (postStream.Length > 0)
                {
                    if (contentType == HttpClientHelper.DEFAULT_CONTENT_TYPE)
                    {
                        //如果ContentType是默认值,则设置成为二进制流
                        contentType = "application/octet-stream";
                    }

                    //contentType = "application/x-www-form-urlencoded";
                }

                hc = new StreamContent(postStream);

                hc.Headers.ContentType = new MediaTypeHeaderValue(contentType);

                //使用Url格式Form表单Post提交的时候才使用application/x-www-form-urlencoded
                //去掉注释以测试Request.Body为空的情况
                //hc.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            }

            //HttpContentHeader(hc, timeOut);
            #endregion

            if (!string.IsNullOrEmpty(refererUrl))
            {
                client.DefaultRequestHeaders.Referrer = new Uri(refererUrl);
            }

            return(client);
        }
示例#40
0
        /// <summary>
        /// 给.NET Core使用的HttpPost请求公共设置方法
        /// </summary>
        /// <param name="url"></param>
        /// <param name="hc"></param>
        /// <param name="cookieContainer"></param>
        /// <param name="postStream"></param>
        /// <param name="fileDictionary"></param>
        /// <param name="refererUrl"></param>
        /// <param name="encoding"></param>
        /// <param name="cer"></param>
        /// <param name="useAjax"></param>
        /// <param name="timeOut"></param>
        /// <param name="checkValidationResult"></param>
        /// <returns></returns>
        public static HttpClient HttpPost_Common_NetCore(string url, out HttpContent hc, CookieContainer cookieContainer = null,
                                                         Stream postStream          = null, Dictionary <string, string> fileDictionary = null, string refererUrl = null,
                                                         Encoding encoding          = null, X509Certificate2 cer = null, bool useAjax = false, int timeOut = Config.TIME_OUT,
                                                         bool checkValidationResult = false)
        {
            HttpClientHandler handler = new HttpClientHandler();

            handler.CookieContainer = cookieContainer;

            if (checkValidationResult)
            {
                handler.ServerCertificateCustomValidationCallback = new Func <HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool>(CheckValidationResult);
            }

            if (cer != null)
            {
                handler.ClientCertificates.Add(cer);
            }

            HttpClient client = new HttpClient(handler);

            HttpClientHeader(client, refererUrl, useAjax, timeOut);


            #region 处理Form表单文件上传

            var formUploadFile = fileDictionary != null && fileDictionary.Count > 0;//是否用Form上传文件
            if (formUploadFile)
            {
                //通过表单上传文件
                string boundary = "----" + DateTime.Now.Ticks.ToString("x");
                hc = new MultipartFormDataContent(boundary);

                foreach (var file in fileDictionary)
                {
                    try
                    {
                        var fileName = file.Value;
                        //准备文件流
                        using (var fileStream = FileHelper.GetFileStream(fileName))
                        {
                            if (fileStream != null)
                            {
                                //存在文件
                                //hc.Add(new StreamContent(fileStream), file.Key, Path.GetFileName(fileName)); //报流已关闭的异常
                                fileStream.Dispose();
                                (hc as MultipartFormDataContent).Add(CreateFileContent(File.Open(fileName, FileMode.Open), Path.GetFileName(fileName)), file.Key, Path.GetFileName(fileName));
                            }
                            else
                            {
                                //不存在文件或只是注释
                                (hc as MultipartFormDataContent).Add(new StringContent(string.Empty), file.Key, file.Value);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }

                hc.Headers.ContentType = MediaTypeHeaderValue.Parse(string.Format("multipart/form-data; boundary={0}", boundary));
            }
            else
            {
                hc = new StreamContent(postStream);

                //使用Url格式Form表单Post提交的时候才使用application/x-www-form-urlencoded
                //hc.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                hc.Headers.ContentType = new MediaTypeHeaderValue("text/xml");
            }

            //HttpContentHeader(hc, timeOut);
            #endregion

            if (!string.IsNullOrEmpty(refererUrl))
            {
                client.DefaultRequestHeaders.Referrer = new Uri(refererUrl);
            }

            return(client);
        }
 StreamContent EnsureValue()
 {
     if (value == null)
     {
         var s = func();
         if (this.length == null && s.CanSeek)
         {
             this.length = s.Length;
         }
         value = new StreamContent(s);
     }
     return value;
 }
        private Task<HttpResponseMessage> AddResponseProgress(HttpRequestMessage request, HttpResponseMessage response)
        {
            Task<HttpResponseMessage> responseTask;
            if (HttpReceiveProgress != null && response != null && response.Content != null)
            {
                responseTask = response.Content.ReadAsStreamAsync().Then(
                    stream =>
                    {
                        ProgressStream progressStream = new ProgressStream(stream, this, request, response);
                        HttpContent progressContent = new StreamContent(progressStream);
                        response.Content.Headers.CopyTo(progressContent.Headers);
                        response.Content = progressContent;
                        return response;
                    }, runSynchronously: true);
            }
            else
            {
                responseTask = TaskHelpers.FromResult(response);
            }

            return responseTask;
        }
示例#43
0
        public async Task PostAsync_CallMethod_StreamContent(Uri remoteServer, Stream requestContentStream, byte[] expectedData)
        {
            using (var client = new HttpClient())
            {
                HttpContent content = new StreamContent(requestContentStream);
                content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(expectedData);

                using (HttpResponseMessage response = await client.PostAsync(remoteServer, content))
                {
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                }
            }
        }
示例#44
0
        public async Task CopyToAsync_CallMultipleTimesWithStreamSupportingSeekingPartiallyConsumed_ContentIsSerializedMultipleTimesFromInitialPoint()
        {
            int consumed = 4;
            var source = new MockStream(new byte[10], true, true); // supports seeking.
            source.Read(new byte[consumed], 0, consumed);
            var content = new StreamContent(source);

            var destination1 = new MemoryStream();
            await content.CopyToAsync(destination1);
            Assert.Equal(source.Length - consumed, destination1.Length);

            var destination2 = new MemoryStream();
            await content.CopyToAsync(destination2);
            Assert.Equal(source.Length - consumed, destination2.Length);
        }
 private async Task<HttpResponseMessage> AddResponseProgressAsync(HttpRequestMessage request, HttpResponseMessage response)
 {
     Stream stream = await response.Content.ReadAsStreamAsync();
     ProgressStream progressStream = new ProgressStream(stream, this, request, response);
     HttpContent progressContent = new StreamContent(progressStream);
     response.Content.Headers.CopyTo(progressContent.Headers);
     response.Content = progressContent;
     return response;
 }
示例#46
-1
        public void Dispose_UseMockStreamSourceAndDisposeContent_MockStreamGotDisposed()
        {
            var source = new MockStream(new byte[10]);
            var content = new StreamContent(source);
            content.Dispose();

            Assert.Equal(1, source.DisposeCount);
        }