private static StorageException Create(int httpStatusCode, XElement extendedErrorElement)
        {
            // Unfortunately, the RequestResult properties are all internal-only settable. ReadXml is the only way to
            // create a populated RequestResult instance.
            XElement requestResultElement = new XElement("RequestResult",
                new XElement("HTTPStatusCode", httpStatusCode),
                new XElement("HttpStatusMessage"),
                new XElement("TargetLocation"),
                new XElement("ServiceRequestID"),
                new XElement("ContentMd5"),
                new XElement("Etag"),
                new XElement("RequestDate"),
                new XElement("StartTime", DateTime.Now),
                new XElement("EndTime", DateTime.Now),
                extendedErrorElement);

            RequestResult result = new RequestResult();

            using (XmlReader reader = requestResultElement.CreateReader())
            {
                result.ReadXml(reader);
            }

            return new StorageException(result, null, null);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="RequestEventArgs"/> class by using the specified <see cref="RequestResult"/> parameter.
        /// </summary>
        /// <param name="res">The <see cref="RequestResult"/> object.</param>
        public RequestEventArgs(RequestResult res)
#if !WINDOWS_RT
            : base()
#endif
        {
            this.RequestInformation = res;
        }
 public void IsNotFoundExceptionWithoutStatusTest()
 {
     RequestResult result = new RequestResult();
     string message = string.Empty;
     ResourceAlreadyExistException innerException = new ResourceAlreadyExistException(message);
     StorageException exception = new StorageException(result, message, innerException);
     Assert.IsFalse(exception.IsNotFoundException());
 }
 public void RepackStorageExceptionWithoutStatusMessageTest()
 {
     RequestResult result = new RequestResult()
     {
         HttpStatusCode = 500
     };
     string message = string.Empty;
     ResourceAlreadyExistException innerException = new ResourceAlreadyExistException(message);
     StorageException exception = new StorageException(result, message, innerException);
     Assert.IsNotNull(exception.RepackStorageException());
 }
 public void RepackStorageExceptionTest()
 {
     string status = String.Empty;
     RequestResult result = new RequestResult()
     {
         HttpStatusCode = 404
     };
     string message = "storage exception";
     ResourceAlreadyExistException innerException = new ResourceAlreadyExistException(message);
     StorageException exception = new StorageException(result, message, innerException);
     exception = exception.RepackStorageException();
     Assert.IsNotNull(exception);
 }
        public void IsNotFoundExceptionTest()
        {
            RequestResult result = new RequestResult()
            {
                HttpStatusCode = 500
            };
            string message = string.Empty;
            ResourceAlreadyExistException innerException = new ResourceAlreadyExistException(message);
            StorageException exception = new StorageException(result, message, innerException);
            Assert.IsFalse(exception.IsNotFoundException());

            result = new RequestResult()
            {
                HttpStatusCode = 404
            };
            exception = new StorageException(result, message, innerException);
            Assert.IsTrue(exception.IsNotFoundException());
        }
        internal static int GenerateHResult(Exception ex, RequestResult reqResult)
        {
            int hResult = WindowsAzureErrorCode.UnknownException;

            if (ex is StorageException)
            {
                int statusCode = (int)reqResult.HttpStatusCode;
                if (statusCode >= 400 && statusCode < 600)
                {
                    hResult = WindowsAzureErrorCode.HttpErrorMask | statusCode;
                }
                else if (ex.InnerException != null)
                {
                    hResult = ex.InnerException.HResult;
                }
            }

            return hResult;
        }
 /// <summary>
 /// Translates the specified exception into a <see cref="StorageException"/>.
 /// </summary>
 /// <param name="ex">The exception to translate.</param>
 /// <param name="reqResult">The request result.</param>
 /// <returns>The storage exception.</returns>
 /// <returns>An exception of type <see cref="StorageException"/>.</returns>
 public static StorageException TranslateException(Exception ex, RequestResult reqResult)
 {
     return TranslateException(ex, reqResult, null);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="StorageException"/> class by using the specified parameters.
 /// </summary>
 /// <param name="res">The request result.</param>
 /// <param name="message">The exception message.</param>
 /// <param name="inner">The inner exception.</param>
 public StorageException(RequestResult res, string message, Exception inner)
     : base(message, inner)
 {
     this.RequestInformation = res;
     this.IsRetryable = true;
 }
            public string AcquireLease(string blobName, TimeSpan? leaseTime)
            {
                if (!Exists(blobName))
                {
                    RequestResult result = new RequestResult
                    {
                        HttpStatusCode = 404
                    };
                    throw new StorageException(result, "Blob does not exist", null);
                }

                return _items[blobName].AcquireLease(leaseTime);
            }
 public void ThrowIfLeased()
 {
     if (LeaseId != null)
     {
         if (!LeaseExpires.HasValue || LeaseExpires.Value > DateTime.UtcNow)
         {
             RequestResult result = new RequestResult
             {
                 HttpStatusCode = 409
             };
             throw new StorageException(result, "Blob is leased", null);
         }
     }
 }
Exemplo n.º 12
0
        /// <summary>
        /// Populate the RequestResult.
        /// </summary>
        /// <param name="reqResult">The request result.</param>
        /// <param name="response">The web response.</param>
#if NETCORE
        private static void PopulateRequestResult(RequestResult reqResult, HttpResponseMessage response)
        {
            reqResult.HttpStatusMessage = response.StatusCode.ToString();
            reqResult.HttpStatusCode    = (int)response.StatusCode;
        }
        /// <summary>
        /// Translates the specified exception into a storage exception.
        /// </summary>
        /// <param name="ex">The exception to translate.</param>
        /// <param name="reqResult">The request result.</param>
        /// <param name="parseError">The delegate used to parse the error to get extended error information.</param>
        /// <returns>The storage exception.</returns>
        internal static StorageException TranslateDataServiceException(Exception ex, RequestResult reqResult, Func<Stream, IDictionary<string, string>, StorageExtendedErrorInformation> parseError)
        {
            CommonUtility.AssertNotNull("reqResult", reqResult);
            CommonUtility.AssertNotNull("ex", ex);
            CommonUtility.AssertNotNull("parseError", parseError);

            // Dont re-wrap storage exceptions
            if (ex is StorageException)
            {
                return (StorageException)ex;
            }
            else if (ex is TimeoutException)
            {
                reqResult.HttpStatusMessage = null;
                reqResult.HttpStatusCode = (int)HttpStatusCode.RequestTimeout;
                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 };
            }
            else
            {
                StorageException tableEx = TableUtilities.TranslateDataServiceException(ex, reqResult, parseError);

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

            // Just wrap in StorageException
            return new StorageException(reqResult, ex.Message, ex);
        }
        /// <summary>
        /// Translates the specified exception into a storage exception.
        /// </summary>
        /// <param name="ex">The exception to translate.</param>
        /// <param name="reqResult">The request result.</param>
        /// <param name="parseError">The delegate used to parse the error to get extended error information.</param>
        /// <param name="responseStream">The error stream that contains the error information.</param>
        /// <param name="response">HTTP response message</param>
        /// <returns>The storage exception.</returns>
        internal static StorageException TranslateExceptionWithPreBufferedStream(Exception ex, RequestResult reqResult, Func<Stream, StorageExtendedErrorInformation> parseError, Stream responseStream, HttpResponseMessage response)
        {
            StorageException storageException;

            try
            {
                if ((storageException = CoreTranslate(ex, reqResult, ref parseError)) != null)
                {
                    return storageException;
                }

                if (response != null)
                {
                    PopulateRequestResult(reqResult, response);
                    reqResult.ExtendedErrorInformation = StorageExtendedErrorInformation.ReadFromStream(responseStream);
                }
            }
            catch (Exception)
            {
                // if there is an error thrown while parsing the service error, just wrap the service error in a StorageException.
                // no op
            }

            // Just wrap in StorageException
            return new StorageException(reqResult, ex.Message, ex);
        }
        private static void PopulateRequestResult(RequestResult reqResult, HttpWebResponse response)
        {
            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
            if (response.ContentLength > 0) 
            {
                reqResult.IngressBytes += response.ContentLength;
            }
#endif
        }
Exemplo n.º 16
0
        /// <summary>
        /// Translates the specified exception into a storage exception.
        /// </summary>
        /// <param name="ex">The exception to translate.</param>
        /// <param name="reqResult">The request result.</param>
        /// <param name="parseError">The delegate used to parse the error to get extended error information.</param>
        /// <param name="responseStream">The error stream that contains the error information.</param>
        /// <returns>The storage exception.</returns>
        internal static StorageException TranslateExceptionWithPreBufferedStream(Exception ex, RequestResult reqResult, Func <Stream, StorageExtendedErrorInformation> parseError, Stream responseStream)
        {
            StorageException storageException;

            try
            {
                if ((storageException = CoreTranslate(ex, reqResult, ref parseError)) != null)
                {
                    return(storageException);
                }

#if !(NETCORE)
                WebException we = ex as WebException;
                if (we != null)
                {
                    HttpWebResponse response = we.Response as HttpWebResponse;
                    if (response != null)
                    {
                        PopulateRequestResult(reqResult, response);
                        reqResult.ExtendedErrorInformation = parseError(responseStream);
                    }
                }
#endif
            }
            catch (Exception)
            {
                // if there is an error thrown while parsing the service error, just wrap the service error in a StorageException.
                // no op
            }

            // Just wrap in StorageException
            return(new StorageException(reqResult, ex.Message, ex));
        }
        public void RequestResultVerifyXml()
        {
            Uri baseAddressUri = new Uri(TestBase.TargetTenantConfig.BlobServiceEndpoint);
            CloudBlobClient blobClient = new CloudBlobClient(baseAddressUri, TestBase.StorageCredentials);
            CloudBlobContainer container = blobClient.GetContainerReference(Guid.NewGuid().ToString("N"));

            OperationContext opContext = new OperationContext();
            Assert.IsNull(opContext.LastResult);
            container.Exists(null, opContext);
            Assert.IsNotNull(opContext.LastResult);

            // We do not have precision at milliseconds level. Hence, we need
            // to recreate the start DateTime to be able to compare it later.
            DateTime start = opContext.LastResult.StartTime;
            start = new DateTime(start.Year, start.Month, start.Day, start.Hour, start.Minute, start.Second);

            DateTime end = opContext.LastResult.EndTime;
            end = new DateTime(end.Year, end.Month, end.Day, end.Hour, end.Minute, end.Second);

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            StringBuilder sb = new StringBuilder();
            using (XmlWriter writer = XmlWriter.Create(sb, settings))
            {
                opContext.LastResult.WriteXml(writer);
            }

            RequestResult retrResult = new RequestResult();
            using (XmlReader reader = XmlReader.Create(new StringReader(sb.ToString())))
            {
                retrResult.ReadXml(reader);
            }

            Assert.AreEqual(opContext.LastResult.RequestDate, retrResult.RequestDate);
            Assert.AreEqual(opContext.LastResult.ServiceRequestID, retrResult.ServiceRequestID);
            Assert.AreEqual(start, retrResult.StartTime);
            Assert.AreEqual(end, retrResult.EndTime);
            Assert.AreEqual(opContext.LastResult.HttpStatusCode, retrResult.HttpStatusCode);
            Assert.AreEqual(opContext.LastResult.HttpStatusMessage, retrResult.HttpStatusMessage);
            Assert.AreEqual(opContext.LastResult.ContentMd5, retrResult.ContentMd5);
            Assert.AreEqual(opContext.LastResult.Etag, retrResult.Etag);

            // Now test with no indentation
            sb = new StringBuilder();
            using (XmlWriter writer = XmlWriter.Create(sb))
            {
                opContext.LastResult.WriteXml(writer);
            }

            retrResult = new RequestResult();
            using (XmlReader reader = XmlReader.Create(new StringReader(sb.ToString())))
            {
                retrResult.ReadXml(reader);
            }

            Assert.AreEqual(opContext.LastResult.RequestDate, retrResult.RequestDate);
            Assert.AreEqual(opContext.LastResult.ServiceRequestID, retrResult.ServiceRequestID);
            Assert.AreEqual(start, retrResult.StartTime);
            Assert.AreEqual(end, retrResult.EndTime);
            Assert.AreEqual(opContext.LastResult.HttpStatusCode, retrResult.HttpStatusCode);
            Assert.AreEqual(opContext.LastResult.HttpStatusMessage, retrResult.HttpStatusMessage);
            Assert.AreEqual(opContext.LastResult.ContentMd5, retrResult.ContentMd5);
            Assert.AreEqual(opContext.LastResult.Etag, retrResult.Etag);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Translates the specified exception into a storage exception.
        /// </summary>
        /// <param name="ex">The exception to translate.</param>
        /// <param name="reqResult">The request result.</param>
        /// <param name="parseError">The delegate used to parse the error to get extended error information.</param>
        /// <param name="responseStream">The error stream that contains the error information.</param>
        /// <param name="response">HTTP response message</param>
        /// <returns>The storage exception.</returns>
        internal static StorageException TranslateExceptionWithPreBufferedStream(Exception ex, RequestResult reqResult, Func <Stream, StorageExtendedErrorInformation> parseError, Stream responseStream, HttpResponseMessage response)
        {
            StorageException storageException;

            try
            {
                if ((storageException = CoreTranslate(ex, reqResult, ref parseError)) != null)
                {
                    return(storageException);
                }

                if (response != null)
                {
                    PopulateRequestResult(reqResult, response);
                    reqResult.ExtendedErrorInformation = StorageExtendedErrorInformation.ReadFromStream(responseStream);
                }
            }
            catch (Exception)
            {
                // if there is an error thrown while parsing the service error, just wrap the service error in a StorageException.
                // no op
            }

            // Just wrap in StorageException
            return(new StorageException(reqResult, ex.Message, ex));
        }
        /// <summary>
        /// Translates the specified exception into a storage exception.
        /// </summary>
        /// <param name="ex">The exception to translate.</param>
        /// <param name="reqResult">The request result.</param>
        /// <param name="parseError">The delegate used to parse the error to get extended error information.</param>
        /// <param name="responseStream">The error stream that contains the error information.</param>
        /// <returns>The storage exception.</returns>
        internal static StorageException TranslateExceptionWithPreBufferedStream(Exception ex, RequestResult reqResult, Func<Stream, StorageExtendedErrorInformation> parseError, Stream responseStream)
        {
            StorageException storageException;
            if ((storageException = CoreTranslate(ex, reqResult, ref parseError)) != null)
            {
                return storageException;
            }

            WebException we = ex as WebException;
            if (we != null)
            {
                try
                {
                    HttpWebResponse response = we.Response as HttpWebResponse;
                    if (response != null)
                    {
                        PopulateRequestResult(reqResult, response);

#if WINDOWS_RT
                        reqResult.ExtendedErrorInformation = StorageExtendedErrorInformation.ReadFromStream(responseStream);
#else
                        reqResult.ExtendedErrorInformation = parseError(responseStream);
#endif
                    }
                }
                catch (Exception)
                {
                    // no op
                }
            }

            // Just wrap in StorageException
            return new StorageException(reqResult, ex.Message, ex);
        }
        /// <summary>
        /// Translates the specified exception into a storage exception.
        /// </summary>
        /// <param name="ex">The exception to translate.</param>
        /// <param name="reqResult">The request result.</param>
        /// <param name="parseError">The delegate used to parse the error to get extended error information.</param>
        /// <returns>The storage exception.</returns>
        public static StorageException TranslateException(Exception ex, RequestResult reqResult, Func<Stream, StorageExtendedErrorInformation> parseError)
        {
            StorageException storageException;

            try
            {
                if ((storageException = CoreTranslate(ex, reqResult, ref parseError)) != null)
                {
                    return storageException;
                }

#if !(ASPNET_K || PORTABLE)
                WebException we = ex as WebException;
                if (we != null)
                {
                    HttpWebResponse response = we.Response as HttpWebResponse;
                    if (response != null)
                    {
                        StorageException.PopulateRequestResult(reqResult, response);
#if WINDOWS_RT
                        reqResult.ExtendedErrorInformation = StorageExtendedErrorInformation.ReadFromStream(response.GetResponseStream().AsInputStream());
#else
                        reqResult.ExtendedErrorInformation = parseError(response.GetResponseStream());
#endif
                    }
                }
#endif
            }
            catch (Exception)
            {
                // if there is an error thrown while parsing the service error, just wrap the service error in a StorageException.
                // no op
            }

            // Just wrap in StorageException
            return new StorageException(reqResult, ex.Message, ex);
        }
        private static Mock<ICloudBlob> SetupBlobMock(bool? isFetchSuccess = null)
        {
            Dictionary<string, string> metadata = new Dictionary<string, string>();
            var blobMock = new Mock<ICloudBlob>(MockBehavior.Strict);
            blobMock.Setup(s => s.Metadata).Returns(metadata);
            
            if (isFetchSuccess.HasValue)
            {
                var fetchAttributesSetup = blobMock.Setup(s => s.FetchAttributesAsync(It.IsAny<CancellationToken>()));
                if (isFetchSuccess.Value)
                {
                    fetchAttributesSetup.Returns(Task.FromResult(0));
                }
                else
                {
                    RequestResult requestResult = new RequestResult();
                    requestResult.HttpStatusCode = 404;
                    StorageException blobNotFoundException = new StorageException(requestResult, String.Empty, null);
                    fetchAttributesSetup.Throws(blobNotFoundException);
                }
                fetchAttributesSetup.Verifiable();
            }

            return blobMock;
        }
        /// <summary>
        /// Translates the specified exception into a storage exception.
        /// </summary>
        /// <param name="ex">The exception to translate.</param>
        /// <param name="reqResult">The request result.</param>
        /// <param name="parseError">The delegate used to parse the error to get extended error information.</param>
        /// <param name="response">HTTP response message</param>
        /// <returns>The storage exception.</returns>
        public static StorageException TranslateException(Exception ex, RequestResult reqResult, Func<Stream, StorageExtendedErrorInformation> parseError, HttpResponseMessage response)
        {
            StorageException storageException;

            try
            {
                if ((storageException = CoreTranslate(ex, reqResult, ref parseError)) != null)
                {
                    return storageException;
                }

                if (response != null)
                {
                    StorageException.PopulateRequestResult(reqResult, response);
                    reqResult.ExtendedErrorInformation = CommonUtility.RunWithoutSynchronizationContext(() => StorageExtendedErrorInformation.ReadFromStream(response.Content.ReadAsStreamAsync().Result));
                }
            }
            catch (Exception)
            {
                // if there is an error thrown while parsing the service error, just wrap the service error in a StorageException.
                // no op
            }

            // Just wrap in StorageException
            return new StorageException(reqResult, ex.Message, ex);
        }
        /// <summary>
        /// Translates the specified exception into a storage exception.
        /// </summary>
        /// <param name="ex">The exception to translate.</param>
        /// <param name="reqResult">The request result.</param>
        /// <param name="parseError">The delegate used to parse the error to get extended error information.</param>
        /// <param name="responseStream">The error stream that contains the error information.</param>
        /// <returns>The storage exception.</returns>
        internal static StorageException TranslateExceptionWithPreBufferedStream(Exception ex, RequestResult reqResult, Func<Stream, StorageExtendedErrorInformation> parseError, Stream responseStream)
        {
            StorageException storageException;

            try
            {
                if ((storageException = CoreTranslate(ex, reqResult, ref parseError)) != null)
                {
                    return storageException;
                }

#if !(ASPNET_K || PORTABLE)
                WebException we = ex as WebException;
                if (we != null)
                {
                    HttpWebResponse response = we.Response as HttpWebResponse;
                    if (response != null)
                    {
                        PopulateRequestResult(reqResult, response);
                        reqResult.ExtendedErrorInformation = parseError(responseStream);
                    }
                }
#endif
            }
            catch (Exception)
            {
                // if there is an error thrown while parsing the service error, just wrap the service error in a StorageException.
                // no op
            }

            // Just wrap in StorageException
            return new StorageException(reqResult, ex.Message, ex);
        }
Exemplo n.º 24
0
 /// <summary>
 /// Translates the specified exception into a <see cref="StorageException"/>.
 /// </summary>
 /// <param name="ex">The exception to translate.</param>
 /// <param name="reqResult">The request result.</param>
 /// <returns>The storage exception.</returns>
 /// <returns>An exception of type <see cref="StorageException"/>.</returns>
 public static StorageException TranslateException(Exception ex, RequestResult reqResult)
 {
     return(TranslateException(ex, reqResult, null));
 }
        /// <summary>
        /// Tries to translate the specified exception into a storage exception.
        /// </summary>
        /// <param name="ex">The exception to translate.</param>
        /// <param name="reqResult">The request result.</param>
        /// <param name="parseError">The delegate used to parse the error to get extended error information.</param>
        /// <returns>The storage exception or <c>null</c>.</returns>
        private static StorageException CoreTranslate(Exception ex, RequestResult reqResult, ref Func<Stream, StorageExtendedErrorInformation> parseError)
        {
            CommonUtility.AssertNotNull("reqResult", reqResult);
            CommonUtility.AssertNotNull("ex", ex);

            if (parseError == null)
            {
                parseError = StorageExtendedErrorInformation.ReadFromStream;
            }

            // Dont re-wrap storage exceptions
            if (ex is StorageException)
            {
                return (StorageException)ex;
            }
            else if (ex is TimeoutException)
            {
                reqResult.HttpStatusMessage = null;
                reqResult.HttpStatusCode = (int)HttpStatusCode.RequestTimeout;
                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 || ASPNET_K || PORTABLE
            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
            {
                // Should never get to this one since we will call TranslateDataServiceException for DataService operations.
                StorageException tableEx = TableUtilities.TranslateDataServiceException(ex, reqResult, null);

                if (tableEx != null)
                {
                    return tableEx;
                }
            }
#endif
            // return null and check in the caller
            return null;
        }
        public async Task TryLockAsync_CreatesBlob_WhenItDoesNotExist()
        {
            CancellationToken cancellationToken = new CancellationToken();
            RequestResult storageResult = new RequestResult
            {
                HttpStatusCode = 404
            };
            StorageException storageException = new StorageException(storageResult, null, null);

            int count = 0;
            _mockStorageBlob.Setup(p => p.AcquireLeaseAsync(_singletonConfig.LockPeriod, null, cancellationToken)).Returns(() =>
            {
                if (count++ == 0)
                {
                    throw storageException;
                }
                return Task.FromResult(TestLeaseId);
            });

            _mockStorageBlob.Setup(p => p.UploadTextAsync(string.Empty, null, null, null, null, cancellationToken)).Returns(Task.FromResult(true));
            _mockStorageBlob.SetupGet(p => p.Metadata).Returns(_mockBlobMetadata);
            _mockStorageBlob.Setup(p => p.SetMetadataAsync(It.Is<AccessCondition>(q => q.LeaseId == TestLeaseId), null, null, cancellationToken)).Returns(Task.FromResult(true));
            _mockStorageBlob.Setup(p => p.ReleaseLeaseAsync(It.Is<AccessCondition>(q => q.LeaseId == TestLeaseId), null, null, cancellationToken)).Returns(Task.FromResult(true));

            SingletonAttribute attribute = new SingletonAttribute();
            SingletonManager.SingletonLockHandle lockHandle = (SingletonManager.SingletonLockHandle)await _singletonManager.TryLockAsync(TestLockId, TestInstanceId, attribute, cancellationToken);

            Assert.Same(_mockStorageBlob.Object, lockHandle.Blob);
            Assert.Equal(TestLeaseId, lockHandle.LeaseId);
            Assert.Equal(1, _mockStorageBlob.Object.Metadata.Keys.Count);
            Assert.Equal(_mockStorageBlob.Object.Metadata[SingletonManager.FunctionInstanceMetadataKey], TestInstanceId);
        }
        /// <summary>
        /// Populate the RequestResult.
        /// </summary>
        /// <param name="reqResult">The request result.</param>
        /// <param name="response">The web response.</param>
#if ASPNET_K || PORTABLE
        private static void PopulateRequestResult(RequestResult reqResult, HttpResponseMessage response)
        {
            reqResult.HttpStatusMessage = response.StatusCode.ToString();
            reqResult.HttpStatusCode = (int)response.StatusCode;
        }
Exemplo n.º 28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RequestEventArgs"/> class by using the specified <see cref="RequestResult"/> parameter.
 /// </summary>
 /// <param name="res">The <see cref="RequestResult"/> object.</param>
 public RequestEventArgs(RequestResult res)
 {
     this.RequestInformation = res;
 }
        private StorageException GetSimulatedStorageTransientErrorDetectionStrategy(string errorString)
        {
            string requestResultAsXml = String.Format("<RequestResult><HTTPStatusCode>500</HTTPStatusCode><HttpStatusMessage>fake status message</HttpStatusMessage><TargetLocation>Primary</TargetLocation><ServiceRequestID>fake requestId</ServiceRequestID><ContentMd5>fake md5</ContentMd5><Etag>fake etag</Etag><RequestDate>fake request date</RequestDate><StartTime>{1}</StartTime><EndTime>{1}</EndTime><ExtendedErrorInformation><Code>{0}</Code></ExtendedErrorInformation></RequestResult>", errorString, DateTime.UtcNow);

            RequestResult requestResult = new RequestResult();
            XmlTextReader reader = new XmlTextReader(new StringReader(requestResultAsXml));
            requestResult.ReadXml(reader);
            Exception innerException = null;

            return new StorageException(requestResult, "Simulated StorageException", innerException);
        }
        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);
        }
Exemplo n.º 31
0
        public static RequestResult TranslateFromExceptionMessage(string message)
        {
            RequestResult res = new RequestResult();

            using (XmlReader reader = XmlReader.Create(new StringReader(message)))
            {
                res.ReadXml(reader);
            }

            return res;
        }
Exemplo n.º 32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StorageException"/> class by using the specified parameters.
 /// </summary>
 /// <param name="res">The request result.</param>
 /// <param name="message">The exception message.</param>
 /// <param name="inner">The inner exception.</param>
 public StorageException(RequestResult res, string message, Exception inner)
     : base(message, inner)
 {
     this.RequestInformation = res;
     this.IsRetryable        = true;
 }