public async Task CloudBlobClientServerTimeoutAsync()
        {
            CloudBlobClient client = GenerateCloudBlobClient();

            string           timeout = null;
            OperationContext context = new OperationContext();

            context.SendingRequest += (sender, e) =>
            {
                IDictionary <string, string> query = HttpWebUtility.ParseQueryString(e.RequestUri.Query);
                if (!query.TryGetValue("timeout", out timeout))
                {
                    timeout = null;
                }
            };

            BlobRequestOptions options = new BlobRequestOptions();
            await client.GetServicePropertiesAsync(null, context);

            Assert.IsNull(timeout);
            await client.GetServicePropertiesAsync(options, context);

            Assert.IsNull(timeout);

            options.ServerTimeout = TimeSpan.FromSeconds(100);
            await client.GetServicePropertiesAsync(options, context);

            Assert.AreEqual("100", timeout);

            client.DefaultRequestOptions.ServerTimeout = TimeSpan.FromSeconds(90);
            await client.GetServicePropertiesAsync(null, context);

            Assert.AreEqual("90", timeout);
            await client.GetServicePropertiesAsync(options, context);

            Assert.AreEqual("100", timeout);

            options.ServerTimeout = null;
            await client.GetServicePropertiesAsync(options, context);

            Assert.AreEqual("90", timeout);

            options.ServerTimeout = TimeSpan.Zero;
            await client.GetServicePropertiesAsync(options, context);

            Assert.IsNull(timeout);
        }
예제 #2
0
        public string CanonicalizeHttpRequest(HttpRequestMessage request, string accountName)
        {
            // Add the method (GET, POST, PUT, or HEAD).
            CanonicalizedString canonicalizedString = new CanonicalizedString(request.Method.Method);

            // Add the Content-* HTTP headers. Empty values are allowed.
            if (request.Content != null)
            {
                canonicalizedString.AppendCanonicalizedElement(HttpWebUtility.CombineHttpHeaderValues(request.Content.Headers.ContentEncoding));
                canonicalizedString.AppendCanonicalizedElement(HttpWebUtility.CombineHttpHeaderValues(request.Content.Headers.ContentLanguage));
                AuthenticationUtility.AppendCanonicalizedContentLengthHeader(canonicalizedString, request);
                canonicalizedString.AppendCanonicalizedElement((request.Content.Headers.ContentMD5 == null) ? null :
                                                               Convert.ToBase64String(request.Content.Headers.ContentMD5));
                canonicalizedString.AppendCanonicalizedElement((request.Content.Headers.ContentType == null) ? null :
                                                               request.Content.Headers.ContentType.ToString());
            }
            else
            {
                canonicalizedString.AppendCanonicalizedElement(null);
                canonicalizedString.AppendCanonicalizedElement(null);
                canonicalizedString.AppendCanonicalizedElement(null);
                canonicalizedString.AppendCanonicalizedElement(null);
                canonicalizedString.AppendCanonicalizedElement(null);
            }

            // Add the Date HTTP header (only if the x-ms-date header is not being used)
            AuthenticationUtility.AppendCanonicalizedDateHeader(canonicalizedString, request);

            // Add If-* headers and Range header
            canonicalizedString.AppendCanonicalizedElement(AuthenticationUtility.GetCanonicalizedHeaderValue(request.Headers.IfModifiedSince));
            canonicalizedString.AppendCanonicalizedElement(CommonUtility.GetFirstHeaderValue(request.Headers.IfMatch));
            canonicalizedString.AppendCanonicalizedElement(CommonUtility.GetFirstHeaderValue(request.Headers.IfNoneMatch));
            canonicalizedString.AppendCanonicalizedElement(AuthenticationUtility.GetCanonicalizedHeaderValue(request.Headers.IfUnmodifiedSince));
            canonicalizedString.AppendCanonicalizedElement((request.Headers.Range == null) ? null :
                                                           CommonUtility.GetFirstHeaderValue(request.Headers.Range.Ranges));

            // Add any custom headers
            AuthenticationUtility.AppendCanonicalizedCustomHeaders(canonicalizedString, request);

            // Add the canonicalized URI element
            string resourceString = AuthenticationUtility.GetCanonicalizedResourceString(request.RequestUri, accountName);

            canonicalizedString.AppendCanonicalizedElement(resourceString);

            return(canonicalizedString.ToString());
        }
예제 #3
0
        private void UpdateQueryBuilder()
        {
            this.queryBuilder = new UriQueryBuilder();
            this.isHttpsOnly  = false;
            IDictionary <string, string> parameters = HttpWebUtility.ParseQueryString(this.SASToken);

            foreach (KeyValuePair <string, string> parameter in parameters)
            {
                if (string.CompareOrdinal(parameter.Key, Constants.QueryConstants.SignedProtocols) == 0 && string.CompareOrdinal(parameter.Value, "https") == 0)
                {
                    this.isHttpsOnly = true;
                }

                this.queryBuilder.Add(parameter.Key, parameter.Value);
            }

            this.queryBuilder.Add(Constants.QueryConstants.ApiVersion, Constants.HeaderConstants.TargetStorageVersion);
        }
예제 #4
0
        /// <summary>
        /// Populate the RequestResult.
        /// </summary>
        /// <param name="reqResult">The request result.</param>
        /// <param name="response">The web response.</param>
        private static void PopulateRequestResult(RequestResult reqResult, HttpWebResponse response)
        {
            reqResult.HttpStatusMessage = response.StatusDescription;
            reqResult.HttpStatusCode    = (int)response.StatusCode;
            if (response.Headers != null)
            {
                reqResult.ServiceRequestID = HttpWebUtility.TryGetHeader(response, Constants.HeaderConstants.RequestIdHeader, null);
                reqResult.ContentMd5       = HttpWebUtility.TryGetHeader(response, "Content-MD5", null);
                string tempDate = HttpWebUtility.TryGetHeader(response, "Date", null);
                reqResult.RequestDate = string.IsNullOrEmpty(tempDate) ? DateTime.Now.ToString("R", CultureInfo.InvariantCulture) : tempDate;
                reqResult.Etag        = response.Headers[HttpResponseHeader.ETag];
            }

            if (response.ContentLength > 0)
            {
                reqResult.IngressBytes += response.ContentLength;
            }
        }
        /// <summary>
        /// Applies the condition for a source blob to the web request.
        /// </summary>
        /// <param name="request">The request to be modified.</param>
        /// <param name="accessCondition">Access condition to be added to the request.</param>
        internal static void ApplyAccessConditionToSource(this StorageRequestMessage request, AccessCondition accessCondition)
        {
            if (accessCondition != null)
            {
                if (!string.IsNullOrEmpty(accessCondition.IfMatchETag))
                {
                    request.Headers.Add(Constants.HeaderConstants.SourceIfMatchHeader, accessCondition.IfMatchETag);
                }

                if (!string.IsNullOrEmpty(accessCondition.IfNoneMatchETag))
                {
                    request.Headers.Add(Constants.HeaderConstants.SourceIfNoneMatchHeader, accessCondition.IfNoneMatchETag);
                }

                if (!string.IsNullOrEmpty(accessCondition.IfMatchContentCrc))
                {
                    request.Headers.Add(Constants.HeaderConstants.SourceIfMatchCrcHeader, accessCondition.IfMatchContentCrc);
                }

                if (!string.IsNullOrEmpty(accessCondition.IfNoneMatchContentCrc))
                {
                    request.Headers.Add(Constants.HeaderConstants.SourceIfNoneMatchCrcHeader, accessCondition.IfNoneMatchContentCrc);
                }

                if (accessCondition.IfModifiedSinceTime.HasValue)
                {
                    request.Headers.Add(
                        Constants.HeaderConstants.SourceIfModifiedSinceHeader,
                        HttpWebUtility.ConvertDateTimeToHttpString(accessCondition.IfModifiedSinceTime.Value));
                }

                if (accessCondition.IfNotModifiedSinceTime.HasValue)
                {
                    request.Headers.Add(
                        Constants.HeaderConstants.SourceIfUnmodifiedSinceHeader,
                        HttpWebUtility.ConvertDateTimeToHttpString(accessCondition.IfNotModifiedSinceTime.Value));
                }

                if (!string.IsNullOrEmpty(accessCondition.LeaseId))
                {
                    throw new InvalidOperationException(SR.LeaseConditionOnSource);
                }
            }
        }
예제 #6
0
        public void CloudFileClientServerTimeout()
        {
            CloudFileClient client = GenerateCloudFileClient();
            CloudFileShare  share  = client.GetShareReference("timeouttest");

            string           timeout = null;
            OperationContext context = new OperationContext();

            context.SendingRequest += (sender, e) =>
            {
                IDictionary <string, string> query = HttpWebUtility.ParseQueryString(e.Request.RequestUri.Query);
                if (!query.TryGetValue("timeout", out timeout))
                {
                    timeout = null;
                }
            };

            FileRequestOptions options = new FileRequestOptions();

            share.Exists(null, context);
            Assert.IsNull(timeout);
            share.Exists(options, context);
            Assert.IsNull(timeout);

            options.ServerTimeout = TimeSpan.FromSeconds(100);
            share.Exists(options, context);
            Assert.AreEqual("100", timeout);

            client.DefaultRequestOptions.ServerTimeout = TimeSpan.FromSeconds(90);
            share.Exists(null, context);
            Assert.AreEqual("90", timeout);
            share.Exists(options, context);
            Assert.AreEqual("100", timeout);

            options.ServerTimeout = null;
            share.Exists(options, context);
            Assert.AreEqual("90", timeout);

            options.ServerTimeout = TimeSpan.Zero;
            share.Exists(options, context);
            Assert.IsNull(timeout);
        }
        private Task <HttpResponseMessage> GetSharedKeyAuthenticationTask(StorageRequestMessage request, CancellationToken cancellationToken)
        {
            ICanonicalizer     canonicalizer = request.Canonicalizer;
            StorageCredentials credentials   = request.Credentials;
            string             accountName   = request.AccountName;

            if (!request.Headers.Contains("x-ms-date"))
            {
                string value = HttpWebUtility.ConvertDateTimeToHttpString(DateTimeOffset.UtcNow);
                request.Headers.Add("x-ms-date", value);
            }
            if (credentials.IsSharedKey)
            {
                string key     = credentials.Key;
                string message = canonicalizer.CanonicalizeHttpRequest(request, accountName);
                string arg     = CryptoUtility.ComputeHmac256(key, message);
                request.Headers.Authorization = new AuthenticationHeaderValue(canonicalizer.AuthorizationScheme, string.Format(CultureInfo.InvariantCulture, "{0}:{1}", credentials.AccountName, arg));
            }
            return(base.SendAsync((HttpRequestMessage)request, cancellationToken));
        }
        public void ParseQueryStringTest()
        {
            IDictionary <string, string> dictionary = HttpWebUtility.ParseQueryString("?a=1&b&=c&d=&a=&d=2&&&d=&d=");

            Assert.AreEqual(3, dictionary.Count);
            Assert.AreEqual("b,c,,", dictionary[""]);
            Assert.AreEqual("1,", dictionary["a"]);
            Assert.AreEqual(",2,,", dictionary["d"]);

            dictionary = HttpWebUtility.ParseQueryString("a=1&b");
            Assert.AreEqual(2, dictionary.Count);
            Assert.AreEqual("b", dictionary[""]);
            Assert.AreEqual("1", dictionary["a"]);

            dictionary = HttpWebUtility.ParseQueryString("");
            Assert.AreEqual(0, dictionary.Count);

            dictionary = HttpWebUtility.ParseQueryString("?");
            Assert.AreEqual(0, dictionary.Count);
        }
예제 #9
0
        internal static void AddTokenAuth(StorageRequestMessage request)
        {
            StorageCredentials credentials = request.Credentials;

            if (!request.Headers.Contains(Constants.HeaderConstants.Date))
            {
                string dateString = HttpWebUtility.ConvertDateTimeToHttpString(DateTimeOffset.UtcNow);
                request.Headers.Add(Constants.HeaderConstants.Date, dateString);
            }

            if (!"https".Equals(request.RequestUri.Scheme, StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException(SR.OnlyHttpsIsSupportedForTokenCredential);
            }

            if (credentials.IsToken)
            {
                request.Headers.Add(
                    "Authorization",
                    string.Format(CultureInfo.InvariantCulture, "Bearer {0}", credentials.TokenCredential.Token));
            }
        }
예제 #10
0
        /// <summary>
        /// Gets the blob's properties from the response.
        /// </summary>
        /// <param name="response">The web response.</param>
        /// <returns>The blob's properties.</returns>
        public static BlobProperties GetProperties(HttpResponseMessage response)
        {
            CommonUtility.AssertNotNull("response", response);

            BlobProperties properties = new BlobProperties();

            if (response.Content != null)
            {
                properties.LastModified = response.Content.Headers.LastModified;
                HttpContentHeaders contentHeaders = response.Content.Headers;
                properties.ContentEncoding    = HttpWebUtility.GetHeaderValues("Content-Encoding", contentHeaders);
                properties.ContentLanguage    = HttpWebUtility.GetHeaderValues("Content-Language", contentHeaders);
                properties.ContentDisposition = HttpWebUtility.GetHeaderValues("Content-Disposition", contentHeaders);
                properties.ContentType        = HttpWebUtility.GetHeaderValues("Content-Type", contentHeaders);


                if (response.Content.Headers.ContentMD5 != null && response.Content.Headers.ContentRange == null)
                {
                    properties.ContentMD5 = HttpResponseParsers.GetContentMD5(response);
                }
                else if (!string.IsNullOrEmpty(response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.BlobContentMD5Header)))
                {
                    properties.ContentMD5 = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.BlobContentMD5Header);
                }

                string created = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.CreationTimeHeader);
                properties.Created = string.IsNullOrEmpty(created) ? (DateTimeOffset?)null : DateTimeOffset.Parse(created, CultureInfo.InvariantCulture).ToUniversalTime();

                string blobEncryption = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.ServerEncrypted);
                properties.IsServerEncrypted = string.Equals(blobEncryption, Constants.HeaderConstants.TrueHeader, StringComparison.OrdinalIgnoreCase);

                string incrementalCopy = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.IncrementalCopyHeader);
                properties.IsIncrementalCopy = string.Equals(incrementalCopy, Constants.HeaderConstants.TrueHeader, StringComparison.OrdinalIgnoreCase);

                // Get the content length. Prioritize range and x-ms over content length for the special cases.
                string contentLengthHeader = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.BlobContentLengthHeader);
                if ((response.Content.Headers.ContentRange != null) &&
                    response.Content.Headers.ContentRange.HasLength)
                {
                    properties.Length = response.Content.Headers.ContentRange.Length.Value;
                }
                else if (!string.IsNullOrEmpty(contentLengthHeader))
                {
                    properties.Length = long.Parse(contentLengthHeader);
                }
                else if (response.Content.Headers.ContentLength.HasValue)
                {
                    properties.Length = response.Content.Headers.ContentLength.Value;
                }
            }
            properties.CacheControl = HttpWebUtility.GetHeaderValues("Cache-Control", response.Headers);

            if (response.Headers.ETag != null)
            {
                properties.ETag = response.Headers.ETag.ToString();
            }

            // Get blob type
            string blobType = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.BlobType);

            if (!string.IsNullOrEmpty(blobType))
            {
                properties.BlobType = (BlobType)Enum.Parse(typeof(BlobType), blobType, true);
            }

            // Get lease properties
            properties.LeaseStatus   = GetLeaseStatus(response);
            properties.LeaseState    = GetLeaseState(response);
            properties.LeaseDuration = GetLeaseDuration(response);

            // Get sequence number
            string sequenceNumber = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.BlobSequenceNumber);

            if (!string.IsNullOrEmpty(sequenceNumber))
            {
                properties.PageBlobSequenceNumber = long.Parse(sequenceNumber, CultureInfo.InvariantCulture);
            }

            // Get committed block count
            string comittedBlockCount = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.BlobCommittedBlockCount);

            if (!string.IsNullOrEmpty(comittedBlockCount))
            {
                properties.AppendBlobCommittedBlockCount = int.Parse(comittedBlockCount, CultureInfo.InvariantCulture);
            }

            // Get the tier of the blob
            string premiumBlobTierInferredString = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.AccessTierInferredHeader);

            if (!string.IsNullOrEmpty(premiumBlobTierInferredString))
            {
                properties.BlobTierInferred = Convert.ToBoolean(premiumBlobTierInferredString);
            }

            string              blobTierString = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.AccessTierHeader);
            StandardBlobTier?   standardBlobTier;
            PremiumPageBlobTier?premiumPageBlobTier;

            BlobHttpResponseParsers.GetBlobTier(properties.BlobType, blobTierString, out standardBlobTier, out premiumPageBlobTier);
            properties.StandardBlobTier    = standardBlobTier;
            properties.PremiumPageBlobTier = premiumPageBlobTier;

            // Get the rehydration status
            string rehydrationStatusString = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.ArchiveStatusHeader);

            if (!string.IsNullOrEmpty(rehydrationStatusString))
            {
                if (Constants.RehydratePendingToHot.Equals(rehydrationStatusString))
                {
                    properties.RehydrationStatus = RehydrationStatus.PendingToHot;
                }
                else if (Constants.RehydratePendingToCool.Equals(rehydrationStatusString))
                {
                    properties.RehydrationStatus = RehydrationStatus.PendingToCool;
                }
                else
                {
                    properties.RehydrationStatus = RehydrationStatus.Unknown;
                }
            }

            if ((properties.PremiumPageBlobTier.HasValue || properties.StandardBlobTier.HasValue) && !properties.BlobTierInferred.HasValue)
            {
                properties.BlobTierInferred = false;
            }

            // Get the time the tier of the blob was last modified
            string accessTierChangeTimeString = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.AccessTierChangeTimeHeader);

            if (!string.IsNullOrEmpty(accessTierChangeTimeString))
            {
                properties.BlobTierLastModifiedTime = DateTimeOffset.Parse(accessTierChangeTimeString, CultureInfo.InvariantCulture);
            }

            return(properties);
        }
        /// <summary>
        /// Gets the file's properties from the response.
        /// </summary>
        /// <param name="response">The web response.</param>
        /// <returns>The file's properties.</returns>
        public static FileProperties GetProperties(HttpResponseMessage response)
        {
            FileProperties properties = new FileProperties();

            if (response.Content != null)
            {
                properties.LastModified = response.Content.Headers.LastModified;
#if NETCORE
                HttpContentHeaders contentHeaders = response.Content.Headers;
                properties.ContentEncoding    = HttpWebUtility.GetHeaderValues("Content-Encoding", contentHeaders);
                properties.ContentLanguage    = HttpWebUtility.GetHeaderValues("Content-Language", contentHeaders);
                properties.ContentDisposition = HttpWebUtility.GetHeaderValues("Content-Disposition", contentHeaders);
                properties.ContentType        = HttpWebUtility.GetHeaderValues("Content-Type", contentHeaders);
#else
                properties.ContentEncoding = HttpWebUtility.CombineHttpHeaderValues(response.Content.Headers.ContentEncoding);
                properties.ContentLanguage = HttpWebUtility.CombineHttpHeaderValues(response.Content.Headers.ContentLanguage);

                if (response.Content.Headers.ContentDisposition != null)
                {
                    properties.ContentDisposition = response.Content.Headers.ContentDisposition.ToString();
                }
                if (response.Content.Headers.ContentType != null)
                {
                    properties.ContentType = response.Content.Headers.ContentType.ToString();
                }
#endif

                if (response.Content.Headers.ContentMD5 != null && response.Content.Headers.ContentRange == null)
                {
                    properties.ContentChecksum.MD5 = Convert.ToBase64String(response.Content.Headers.ContentMD5);
                }
                else if (!string.IsNullOrEmpty(response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.FileContentMD5Header)))
                {
                    properties.ContentChecksum.MD5 = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.FileContentMD5Header);
                }

                if (!string.IsNullOrEmpty(response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.FileContentCRC64Header)))
                {
                    properties.ContentChecksum.CRC64 = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.FileContentCRC64Header);
                }

                string fileEncryption = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.ServerEncrypted);
                properties.IsServerEncrypted = string.Equals(fileEncryption, Constants.HeaderConstants.TrueHeader, StringComparison.OrdinalIgnoreCase);

                // Get the content length. Prioritize range and x-ms over content length for the special cases.
                string contentLengthHeader = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.FileContentLengthHeader);
                if ((response.Content.Headers.ContentRange != null) &&
                    response.Content.Headers.ContentRange.HasLength)
                {
                    properties.Length = response.Content.Headers.ContentRange.Length.Value;
                }
                else if (!string.IsNullOrEmpty(contentLengthHeader))
                {
                    properties.Length = long.Parse(contentLengthHeader);
                }
                else if (response.Content.Headers.ContentLength.HasValue)
                {
                    properties.Length = response.Content.Headers.ContentLength.Value;
                }
            }
#if NETCORE
            properties.CacheControl = HttpWebUtility.GetHeaderValues("Cache-Control", response.Headers);
#else
            if (response.Headers.CacheControl != null)
            {
                properties.CacheControl = response.Headers.CacheControl.ToString();
            }
#endif
            if (response.Headers.ETag != null)
            {
                properties.ETag = response.Headers.ETag.ToString();
            }

            return(properties);
        }
        public static StorageException TranslateException(Exception ex, RequestResult reqResult)
        {
            CommonUtility.AssertNotNull("reqResult", reqResult);
            CommonUtility.AssertNotNull("ex", ex);

            // Dont re-wrap storage exceptions
            if (ex is StorageException)
            {
                return((StorageException)ex);
            }
            else if (ex is TimeoutException)
            {
                reqResult.HttpStatusMessage        = null;
                reqResult.HttpStatusCode           = (int)HttpStatusCode.Unused;
                reqResult.ExtendedErrorInformation = null;
                return(new StorageException(reqResult, ex.Message, ex));
            }
            else if (ex is ArgumentException)
            {
                reqResult.HttpStatusMessage        = null;
                reqResult.HttpStatusCode           = (int)HttpStatusCode.Unused;
                reqResult.ExtendedErrorInformation = null;
                return(new StorageException(reqResult, ex.Message, ex)
                {
                    IsRetryable = false
                });
            }
#if WINDOWS_RT
            else if (ex is OperationCanceledException)
            {
                reqResult.HttpStatusMessage        = null;
                reqResult.HttpStatusCode           = 306; // unused
                reqResult.ExtendedErrorInformation = null;
                return(new StorageException(reqResult, ex.Message, ex));
            }
#elif WINDOWS_DESKTOP && !WINDOWS_PHONE
            else
            {
                StorageException tableEx = TableUtilities.TranslateDataServiceClientException(ex, reqResult);

                if (tableEx != null)
                {
                    return(tableEx);
                }
            }
#endif

            WebException we = ex as WebException;
            if (we != null)
            {
                try
                {
                    HttpWebResponse response = we.Response as HttpWebResponse;
                    if (response != null)
                    {
                        reqResult.HttpStatusMessage = response.StatusDescription;
                        reqResult.HttpStatusCode    = (int)response.StatusCode;
                        if (response.Headers != null)
                        {
#if WINDOWS_DESKTOP
                            reqResult.ServiceRequestID = HttpWebUtility.TryGetHeader(response, Constants.HeaderConstants.RequestIdHeader, null);
                            reqResult.ContentMd5       = HttpWebUtility.TryGetHeader(response, "Content-MD5", null);
                            string tempDate = HttpWebUtility.TryGetHeader(response, "Date", null);
                            reqResult.RequestDate = string.IsNullOrEmpty(tempDate) ? DateTime.Now.ToString("R", CultureInfo.InvariantCulture) : tempDate;
                            reqResult.Etag        = response.Headers[HttpResponseHeader.ETag];
#endif
                        }
#if WINDOWS_RT
                        reqResult.ExtendedErrorInformation = StorageExtendedErrorInformation.ReadFromStream(response.GetResponseStream().AsInputStream());
#else
                        reqResult.ExtendedErrorInformation = StorageExtendedErrorInformation.ReadFromStream(response.GetResponseStream());
#endif
                    }
                }
                catch (Exception)
                {
                    // no op
                }
            }

            // Not WebException, just wrap in StorageException
            return(new StorageException(reqResult, ex.Message, ex));
        }
예제 #13
0
    private void VerifyAccountWorkerWithHttpRequest(LB_VerifyAccount msg, PBChannel channel)
    {
        HttpWebRequest  myHttpWebRequest  = null;
        HttpWebResponse myHttpWebResponse = null;

        try
        {
            int    tag       = CreateTag();
            string signParam = string.Format("{0}{1}{2}{3}{4}{5}", msg.OpCode, msg.Data, m_AppKey, m_AppSecret, tag, msg.ChannelId);
            string sign      = CreateSign(signParam);
            IDictionary <string, string> headers = new Dictionary <string, string>();
            headers.Add("appkey", m_AppKey);
            headers.Add("sign", sign);
            headers.Add("tag", tag.ToString());
            headers.Add("opcode", msg.OpCode.ToString());
            headers.Add("channelId", msg.ChannelId.ToString());
            IDictionary <string, string> parameters = new Dictionary <string, string>();
            parameters.Add("data", msg.Data);
            LogSys.Log(LOG_TYPE.INFO, "Account:{0}, HttpPost headers. appkey:{1}, sign:{2}, tag:{3}, opcode:{4}, channelId:{5}",
                       msg.Account, m_AppKey, sign, tag, msg.OpCode, msg.ChannelId);
            LogSys.Log(LOG_TYPE.INFO, "Account:{0}, HttpPost parameters. data:{1}", msg.Account, msg.Data);
            //============================================
            myHttpWebRequest  = HttpWebUtility.CreatePostHttpRequest(m_TestBillingServerUrl, headers, parameters, m_HttpRequestTimeout);
            myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
            string responseStr = string.Empty;
            using (Stream streamResponse = myHttpWebResponse.GetResponseStream())
            {
                using (StreamReader readStream = new StreamReader(streamResponse, Encoding.UTF8))
                {
                    responseStr = readStream.ReadToEnd();
                    readStream.Close();
                }
                streamResponse.Flush();
                streamResponse.Close();
            }
            DestroyTag(tag);
            //==================================================
            LogSys.Log(LOG_TYPE.INFO, "Account:{0}, Response:{1}", msg.Account, responseStr);
            //==================================================
            JsonVerifyAccountResult result = JsonConvert.DeserializeObject(responseStr, typeof(JsonVerifyAccountResult)) as JsonVerifyAccountResult;
            var reply = BL_VerifyAccountResult.CreateBuilder();
            reply.Account   = msg.Account;
            reply.OpCode    = result.opcode;
            reply.ChannelId = result.channelId;
            reply.AccountId = "";
            reply.Result    = false;
            int repState = result.state;
            if (repState == (int)BillingRepState.Success && result.data != null)
            {
                int status = int.Parse(result.data.status);
                if (status == 1 && result.channelId == msg.ChannelId && result.opcode == msg.OpCode)
                {
                    reply.AccountId = result.data.userid;
                    reply.Result    = true;
                }
            }
            if (reply.Result == true)
            {
                LogSys.Log(LOG_TYPE.INFO, ConsoleColor.Green, "Account verify success. Account:{0} ID:{1}", reply.Account, reply.AccountId);
            }
            else
            {
                LogSys.Log(LOG_TYPE.INFO, ConsoleColor.Yellow, "Account verify failed. Account:{0} Msg:{1}", reply.Account, result.error);
            }
            channel.Send(reply.Build());
        }
        catch (Exception ex)
        {
            LogSys.Log(LOG_TYPE.ERROR, ConsoleColor.Red, "Exception Type:{0}", ex.GetType().ToString());
            LogSys.Log(LOG_TYPE.ERROR, ConsoleColor.Red, "Exception:{0}\n{1}", ex.Message, ex.StackTrace);
        }
        finally
        {
            if (myHttpWebResponse != null)
            {
                myHttpWebResponse.Close();
            }
            if (myHttpWebRequest != null)
            {
                myHttpWebRequest.Abort();
            }
        }
    }
예제 #14
0
        /// <summary>
        /// Gets the blob's properties from the response.
        /// </summary>
        /// <param name="response">The web response.</param>
        /// <returns>The blob's properties.</returns>
        public static BlobProperties GetProperties(HttpResponseMessage response)
        {
            BlobProperties properties = new BlobProperties();

            if (response.Content != null)
            {
                properties.LastModified    = response.Content.Headers.LastModified;
                properties.ContentEncoding = HttpWebUtility.CombineHttpHeaderValues(response.Content.Headers.ContentEncoding);
                properties.ContentLanguage = HttpWebUtility.CombineHttpHeaderValues(response.Content.Headers.ContentLanguage);

                if (response.Content.Headers.ContentDisposition != null)
                {
                    properties.ContentDisposition = response.Content.Headers.ContentDisposition.ToString();
                }

                if (response.Content.Headers.ContentMD5 != null && response.Content.Headers.ContentRange == null)
                {
                    properties.ContentMD5 = Convert.ToBase64String(response.Content.Headers.ContentMD5);
                }
                else if (!string.IsNullOrEmpty(response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.BlobContentMD5Header)))
                {
                    properties.ContentMD5 = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.BlobContentMD5Header);
                }

                if (response.Content.Headers.ContentType != null)
                {
                    properties.ContentType = response.Content.Headers.ContentType.ToString();
                }

                string blobEncryption = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.ServerEncrypted);
                properties.IsServerEncrypted = string.Equals(blobEncryption, Constants.HeaderConstants.TrueHeader, StringComparison.OrdinalIgnoreCase);

                string incrementalCopy = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.IncrementalCopyHeader);
                properties.IsIncrementalCopy = string.Equals(incrementalCopy, Constants.HeaderConstants.TrueHeader, StringComparison.OrdinalIgnoreCase);

                // Get the content length. Prioritize range and x-ms over content length for the special cases.
                string contentLengthHeader = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.BlobContentLengthHeader);
                if ((response.Content.Headers.ContentRange != null) &&
                    response.Content.Headers.ContentRange.HasLength)
                {
                    properties.Length = response.Content.Headers.ContentRange.Length.Value;
                }
                else if (!string.IsNullOrEmpty(contentLengthHeader))
                {
                    properties.Length = long.Parse(contentLengthHeader);
                }
                else if (response.Content.Headers.ContentLength.HasValue)
                {
                    properties.Length = response.Content.Headers.ContentLength.Value;
                }
            }

            if (response.Headers.CacheControl != null)
            {
                properties.CacheControl = response.Headers.CacheControl.ToString();
            }

            if (response.Headers.ETag != null)
            {
                properties.ETag = response.Headers.ETag.ToString();
            }

            // Get blob type
            string blobType = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.BlobType);

            if (!string.IsNullOrEmpty(blobType))
            {
                properties.BlobType = (BlobType)Enum.Parse(typeof(BlobType), blobType, true);
            }

            // Get lease properties
            properties.LeaseStatus   = GetLeaseStatus(response);
            properties.LeaseState    = GetLeaseState(response);
            properties.LeaseDuration = GetLeaseDuration(response);

            // Get sequence number
            string sequenceNumber = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.BlobSequenceNumber);

            if (!string.IsNullOrEmpty(sequenceNumber))
            {
                properties.PageBlobSequenceNumber = long.Parse(sequenceNumber, CultureInfo.InvariantCulture);
            }

            // Get committed block count
            string comittedBlockCount = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.BlobCommittedBlockCount);

            if (!string.IsNullOrEmpty(comittedBlockCount))
            {
                properties.AppendBlobCommittedBlockCount = int.Parse(comittedBlockCount, CultureInfo.InvariantCulture);
            }

            // Get the tier of the blob
            string premiumBlobTierInferredString = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.AccessTierInferredHeader);

            if (!string.IsNullOrEmpty(premiumBlobTierInferredString))
            {
                properties.BlobTierInferred = Convert.ToBoolean(premiumBlobTierInferredString);
            }

            string premiumBlobTierString = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.AccessTierHeader);
            PremiumPageBlobTier?premiumPageBlobTier;

            BlobHttpResponseParsers.GetBlobTier(properties.BlobType, premiumBlobTierString, out premiumPageBlobTier);
            properties.PremiumPageBlobTier = premiumPageBlobTier;
            if (properties.PremiumPageBlobTier.HasValue && !properties.BlobTierInferred.HasValue)
            {
                properties.BlobTierInferred = false;
            }

            return(properties);
        }
예제 #15
0
        public static string GetOneSentence()
        {
            string sentence = HttpWebUtility.Get("https://v1.hitokoto.cn/");

            return(sentence);
        }
        /// <summary>
        /// Gets the blob's properties from the response.
        /// </summary>
        /// <param name="response">The web response.</param>
        /// <returns>The blob's properties.</returns>
        public static BlobProperties GetProperties(HttpResponseMessage response)
        {
            BlobProperties properties = new BlobProperties();

            if (response.Content != null)
            {
                properties.LastModified    = response.Content.Headers.LastModified;
                properties.ContentEncoding = HttpWebUtility.CombineHttpHeaderValues(response.Content.Headers.ContentEncoding);
                properties.ContentLanguage = HttpWebUtility.CombineHttpHeaderValues(response.Content.Headers.ContentLanguage);

                if (response.Content.Headers.ContentDisposition != null)
                {
                    properties.ContentDisposition = response.Content.Headers.ContentDisposition.ToString();
                }

                if (response.Content.Headers.ContentMD5 != null)
                {
                    properties.ContentMD5 = Convert.ToBase64String(response.Content.Headers.ContentMD5);
                }

                if (response.Content.Headers.ContentType != null)
                {
                    properties.ContentType = response.Content.Headers.ContentType.ToString();
                }

                // Get the content length. Prioritize range and x-ms over content length for the special cases.
                string contentLengthHeader = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.BlobContentLengthHeader);
                if ((response.Content.Headers.ContentRange != null) &&
                    response.Content.Headers.ContentRange.HasLength)
                {
                    properties.Length = response.Content.Headers.ContentRange.Length.Value;
                }
                else if (!string.IsNullOrEmpty(contentLengthHeader))
                {
                    properties.Length = long.Parse(contentLengthHeader);
                }
                else if (response.Content.Headers.ContentLength.HasValue)
                {
                    properties.Length = response.Content.Headers.ContentLength.Value;
                }
            }

            if (response.Headers.CacheControl != null)
            {
                properties.CacheControl = response.Headers.CacheControl.ToString();
            }

            if (response.Headers.ETag != null)
            {
                properties.ETag = response.Headers.ETag.ToString();
            }

            // Get blob type
            string blobType = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.BlobType);

            if (!string.IsNullOrEmpty(blobType))
            {
                properties.BlobType = (BlobType)Enum.Parse(typeof(BlobType), blobType, true);
            }

            // Get lease properties
            properties.LeaseStatus   = GetLeaseStatus(response);
            properties.LeaseState    = GetLeaseState(response);
            properties.LeaseDuration = GetLeaseDuration(response);

            // Get sequence number
            string sequenceNumber = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.BlobSequenceNumber);

            if (!string.IsNullOrEmpty(sequenceNumber))
            {
                properties.PageBlobSequenceNumber = long.Parse(sequenceNumber, CultureInfo.InvariantCulture);
            }

            // Get committed block count
            string comittedBlockCount = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.BlobCommittedBlockCount);

            if (!string.IsNullOrEmpty(comittedBlockCount))
            {
                properties.AppendBlobCommittedBlockCount = int.Parse(comittedBlockCount, CultureInfo.InvariantCulture);
            }

            return(properties);
        }
예제 #17
0
 /// <summary>
 /// Public SasQueryBuilder constructor.
 /// </summary>
 /// <param name="sasToken">The ASA token used to authenticate request.</param>
 public SasQueryBuilder(string sasToken)
 {
     this.AddRange(HttpWebUtility.ParseQueryString(sasToken));
 }
        public string CanonicalizeHttpRequest(HttpRequestMessage request, string accountName)
        {
            // Add the method (GET, POST, PUT, or HEAD).
            CanonicalizedString canonicalizedString = new CanonicalizedString(request.Method.Method);

            // Add the Content-* HTTP headers. Empty values are allowed.
            if (request.Content != null)
            {
                canonicalizedString.AppendCanonicalizedElement(HttpWebUtility.CombineHttpHeaderValues(request.Content.Headers.ContentEncoding));
                canonicalizedString.AppendCanonicalizedElement(HttpWebUtility.CombineHttpHeaderValues(request.Content.Headers.ContentLanguage));
                AuthenticationUtility.AppendCanonicalizedContentLengthHeader(canonicalizedString, request);
                canonicalizedString.AppendCanonicalizedElement((request.Content.Headers.ContentMD5 == null) ? null :
                                                               Convert.ToBase64String(request.Content.Headers.ContentMD5));
                canonicalizedString.AppendCanonicalizedElement((request.Content.Headers.ContentType == null) ? null :
                                                               request.Content.Headers.ContentType.ToString());
            }
            else
            {
                canonicalizedString.AppendCanonicalizedElement(null);
                canonicalizedString.AppendCanonicalizedElement(null);

#if WINDOWS_PHONE
                // Always add 0 for content length header for all requests except GET as Wininet on windows phone 8.1 has that behaviour
                if (request.Method != HttpMethod.Get)
                {
                    canonicalizedString.AppendCanonicalizedElement("0");
                }
                else
                {
                    canonicalizedString.AppendCanonicalizedElement(null);
                }
#else
                if (request.Method == HttpMethod.Put || request.Method == HttpMethod.Delete)
                {
                    canonicalizedString.AppendCanonicalizedElement("0");
                }
                else
                {
                    canonicalizedString.AppendCanonicalizedElement(null);
                }
#endif

                canonicalizedString.AppendCanonicalizedElement(null);
                canonicalizedString.AppendCanonicalizedElement(null);
            }

            // Add the Date HTTP header (only if the x-ms-date header is not being used)
            AuthenticationUtility.AppendCanonicalizedDateHeader(canonicalizedString, request);

            // Add If-* headers and Range header
            canonicalizedString.AppendCanonicalizedElement(AuthenticationUtility.GetCanonicalizedHeaderValue(request.Headers.IfModifiedSince));
            canonicalizedString.AppendCanonicalizedElement(CommonUtility.GetFirstHeaderValue(request.Headers.IfMatch));
            canonicalizedString.AppendCanonicalizedElement(CommonUtility.GetFirstHeaderValue(request.Headers.IfNoneMatch));
            canonicalizedString.AppendCanonicalizedElement(AuthenticationUtility.GetCanonicalizedHeaderValue(request.Headers.IfUnmodifiedSince));
            canonicalizedString.AppendCanonicalizedElement((request.Headers.Range == null) ? null :
                                                           CommonUtility.GetFirstHeaderValue(request.Headers.Range.Ranges));

            // Add any custom headers
            AuthenticationUtility.AppendCanonicalizedCustomHeaders(canonicalizedString, request);

            // Add the canonicalized URI element
            string resourceString = AuthenticationUtility.GetCanonicalizedResourceString(request.RequestUri, accountName);
            canonicalizedString.AppendCanonicalizedElement(resourceString);

            return(canonicalizedString.ToString());
        }