Пример #1
0
        /// <summary>
        /// Process a <see cref="DataServiceRequestException"/> and converts it to a PowerShell
        /// <see cref="ErrorRecord"/>, or <c>null</c> if that is not availaible.
        /// </summary>
        /// <param name="ex">The <see cref="DataServiceRequestException"/> that was thrown.</param>
        private static ErrorRecord AsErrorRecord(this DataServiceRequestException ex)
        {
            ErrorRecord errorRecord      = null;
            Exception   exceptionToThrow = ex;

            // Look for Sql exception message in response, return that message if found.
            foreach (ChangeOperationResponse change in ex.Response)
            {
                // Try to parse the extended properties in the Exception
                ManagementServiceExceptionInfo info;
                if (ManagementServiceExceptionInfo.TryParse(change, out info))
                {
                    if (info.PropertyBag.Contains(DataServiceConstants.SqlMessageTextKey))
                    {
                        // Set the exception to throw as a new exception with the server message
                        string errorDetails =
                            info.PropertyBag[DataServiceConstants.SqlMessageTextKey].ToString();

                        errorRecord = new ErrorRecord(
                            new CommunicationException(errorDetails, ex),
                            string.Empty,
                            ErrorCategory.InvalidOperation,
                            null);
                        break;
                    }
                }
            }

            // Fall back to use the message in the message element if availiable
            if (errorRecord == null)
            {
                foreach (ChangeOperationResponse change in ex.Response)
                {
                    try
                    {
                        XElement errorRoot      = XElement.Parse(change.Error.Message);
                        XElement messageElement = errorRoot.Descendants().Single(x => string.Equals(x.Name.LocalName, "message", StringComparison.OrdinalIgnoreCase));

                        errorRecord = new ErrorRecord(
                            new CommunicationException(messageElement.Value, ex),
                            string.Empty,
                            ErrorCategory.InvalidOperation,
                            null);
                        break;
                    }
                    catch (Exception)
                    {
                        // we hide any parsing error that might have happened because there is no need to expose
                        // additional errors
                    }
                }
            }

            // Return the resulting error record
            return(errorRecord);
        }
Пример #2
0
        /// <summary>
        /// Tries to convert the given exception response to a <see cref="ManagementServiceExceptionInfo"/>.
        /// </summary>
        /// <param name="response">The response containing the xml serialized error information.</param>
        /// <param name="info">The converted <see cref="ManagementServiceExceptionInfo"/> containing errors from the exception.</param>
        /// <returns><c>true</c> if parsing succeeded.</returns>
        public static bool TryParse(OperationResponse response, out ManagementServiceExceptionInfo info)
        {
            if (response != null && response.Error != null)
            {
                return(ManagementServiceExceptionInfo.TryParse(response.Error.Message, out info));
            }

            info = default(ManagementServiceExceptionInfo);
            return(false);
        }
Пример #3
0
        /// <summary>
        /// Converts the given exception message to a <see cref="ManagementServiceExceptionInfo"/>.
        /// </summary>
        /// <param name="message">The message containing the xml serialized error information.</param>
        /// <returns>The converted <see cref="ManagementServiceExceptionInfo"/> containing errors from the exception</returns>
        public static ManagementServiceExceptionInfo Parse(string message)
        {
            if (string.IsNullOrEmpty(message))
            {
                throw new ArgumentException("message");
            }

            ManagementServiceExceptionInfo info;

            if (ManagementServiceExceptionInfo.TryParse(message, out info))
            {
                return(info);
            }
            else
            {
                throw new FormatException(Resources.InvalidExceptionMessageFormat);
            }
        }
Пример #4
0
        /// <summary>
        /// Converts the given exception response to a <see cref="ManagementServiceExceptionInfo"/>.
        /// </summary>
        /// <param name="response">The response containing the xml serialized error information.</param>
        /// <returns>The converted <see cref="ManagementServiceExceptionInfo"/> containing errors from the exception.</returns>
        public static ManagementServiceExceptionInfo Parse(OperationResponse response)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }

            if (response.Error == null)
            {
                throw new ArgumentException(Resources.InvalidErrorInResponse, "response");
            }

            ManagementServiceExceptionInfo info;

            if (ManagementServiceExceptionInfo.TryParse(response, out info))
            {
                return(info);
            }
            else
            {
                throw new FormatException(Resources.InvalidExceptionMessageFormat);
            }
        }
Пример #5
0
        /// <summary>
        /// Process a <see cref="WebException"/> and converts it to a PowerShell
        /// <see cref="ErrorRecord"/>, or <c>null</c> if that is not availaible.
        /// </summary>
        /// <param name="ex">The <see cref="WebException"/> that was thrown.</param>
        /// <param name="requestId">The request Id from the response, if it's availiable.</param>
        /// <returns>An <see cref="ErrorRecord"/> containing the exception details,
        /// or <c>null</c> if the exception cannot be parsed.</returns>
        private static ErrorRecord AsErrorRecord(
            this WebException ex,
            out string requestId)
        {
            ErrorRecord errorRecord = null;

            requestId = null;

            if (ex.Response != null)
            {
                HttpWebResponse response = ex.Response as HttpWebResponse;

                // Extract the request Ids
                if (response.Headers != null)
                {
                    requestId = response.Headers[Constants.RequestIdHeaderName];
                }

                // Retrieve the full exception response
                Stream responseStream = response.GetResponseStream();
                string exceptionResponse;
                using (StreamReader responseReader = new StreamReader(responseStream))
                {
                    exceptionResponse = responseReader.ReadToEnd();
                }

                // Check if it's a service resource error message
                ServiceResourceError serviceResourceError;
                if (errorRecord == null &&
                    ServiceResourceError.TryParse(exceptionResponse, out serviceResourceError))
                {
                    errorRecord = new ErrorRecord(
                        new CommunicationException(serviceResourceError.Message, ex),
                        string.Empty,
                        ErrorCategory.InvalidOperation,
                        null);
                }

                // Check if it's a management service error message
                ManagementServiceExceptionInfo info;
                if (errorRecord == null &&
                    ManagementServiceExceptionInfo.TryParse(exceptionResponse, out info))
                {
                    if (info.PropertyBag.Contains(DataServiceConstants.SqlMessageTextKey))
                    {
                        // Set the exception to throw as a new exception with the server message
                        string errorDetails =
                            info.PropertyBag[DataServiceConstants.SqlMessageTextKey].ToString();

                        errorRecord = new ErrorRecord(
                            new CommunicationException(errorDetails, ex),
                            string.Empty,
                            ErrorCategory.InvalidOperation,
                            null);
                    }
                }

                // Check if it's a database management error message
                SqlDatabaseManagementError databaseManagementError;
                if (errorRecord == null &&
                    SqlDatabaseManagementError.TryParse(exceptionResponse, out databaseManagementError))
                {
                    string errorDetails = string.Format(
                        CultureInfo.InvariantCulture,
                        Resources.DatabaseManagementErrorFormat,
                        databaseManagementError.Code,
                        databaseManagementError.Message);

                    errorRecord = new ErrorRecord(
                        new CommunicationException(errorDetails, ex),
                        string.Empty,
                        ErrorCategory.InvalidOperation,
                        null);
                }

                // Check if it's a not found message
                if (errorRecord == null &&
                    response.StatusCode == HttpStatusCode.NotFound)
                {
                    string message = string.Format(
                        CultureInfo.InvariantCulture,
                        Resources.UriDoesNotExist,
                        response.ResponseUri.AbsoluteUri);
                    string errorDetails = string.Format(
                        CultureInfo.InvariantCulture,
                        Resources.DatabaseManagementErrorFormat,
                        response.StatusCode.ToString(),
                        message);

                    errorRecord = new ErrorRecord(
                        new CommunicationException(errorDetails, ex),
                        string.Empty,
                        ErrorCategory.InvalidOperation,
                        null);
                }
            }

            // Return the resulting error record
            return(errorRecord);
        }
Пример #6
0
        /// <summary>
        /// Tries to convert the given exception message to a <see cref="ManagementServiceExceptionInfo"/>.
        /// </summary>
        /// <param name="message">The message containing the xml serialized error information.</param>
        /// <param name="info">The converted <see cref="ManagementServiceExceptionInfo"/> containing errors from the exception.</param>
        /// <returns><c>true</c> if parsing succeeded.</returns>
        public static bool TryParse(string message, out ManagementServiceExceptionInfo info)
        {
            string      errorType;
            Guid        activityId;
            IDictionary propertyBag;

            if (string.IsNullOrEmpty(message))
            {
                // Empty message
                info = default(ManagementServiceExceptionInfo);
                return(false);
            }

            XDocument errorDocument;

            try
            {
                errorDocument = XDocument.Parse(message);
            }
            catch (XmlException)
            {
                // Invalid xml
                info = default(ManagementServiceExceptionInfo);
                return(false);
            }

            if (errorDocument == null)
            {
                // Invalid xml
                info = default(ManagementServiceExceptionInfo);
                return(false);
            }

            // Attempt to get error information from the standard location in a DataServiceException.
            XElement errorMessage;

            errorMessage = errorDocument.Descendants().Where(x => x.Name.LocalName == "code").FirstOrDefault();

            if (errorMessage == null)
            {
                // Attempt to get error information from the exception Message.  This happens in the case of a WebServiceAuthenticationException
                // being thrown by Management Service.
                errorMessage = errorDocument.Descendants().Where(x => x.Name.LocalName == "Message").FirstOrDefault();

                if (errorMessage == null)
                {
                    // Unable to find an error message.
                    info = default(ManagementServiceExceptionInfo);
                    return(false);
                }
            }

            // Use Regex to parse the message
            Match code = errorCodeParser.Match(errorMessage.Value);

            if (code == null)
            {
                // Regex parsing failed
                info = default(ManagementServiceExceptionInfo);
                return(false);
            }

            errorType = code.Groups["ErrorType"].Value;

            try
            {
                activityId = new Guid(code.Groups["ActivityId"].Value);
            }
            catch (FormatException)
            {
                // Guid parsing failed
                info = default(ManagementServiceExceptionInfo);
                return(false);
            }

            // Only parse the property bag if it exists
            if (code.Groups["KeyValuePairs"].Success)
            {
                try
                {
                    string dataStr = code.Groups["KeyValuePairs"].Value;
                    propertyBag = (IDictionary)Deserialize(dataStr);
                }
                catch (Exception)
                {
                    // Invalid property bag
                    info = default(ManagementServiceExceptionInfo);
                    return(false);
                }
            }
            else
            {
                // create an empty property bag
                propertyBag = (IDictionary) new Dictionary <string, string>();
            }

            info = new ManagementServiceExceptionInfo(errorType, activityId, propertyBag);
            return(true);
        }
        /// <summary>
        /// Tries to convert the given exception response to a <see cref="ManagementServiceExceptionInfo"/>.
        /// </summary>
        /// <param name="response">The response containing the xml serialized error information.</param>
        /// <param name="info">The converted <see cref="ManagementServiceExceptionInfo"/> containing errors from the exception.</param>
        /// <returns><c>true</c> if parsing succeeded.</returns>
        public static bool TryParse(OperationResponse response, out ManagementServiceExceptionInfo info)
        {
            if (response != null && response.Error != null)
            {
                return ManagementServiceExceptionInfo.TryParse(response.Error.Message, out info);
            }

            info = default(ManagementServiceExceptionInfo);
            return false;
        }
        /// <summary>
        /// Tries to convert the given exception message to a <see cref="ManagementServiceExceptionInfo"/>.
        /// </summary>
        /// <param name="message">The message containing the xml serialized error information.</param>
        /// <param name="info">The converted <see cref="ManagementServiceExceptionInfo"/> containing errors from the exception.</param>
        /// <returns><c>true</c> if parsing succeeded.</returns>
        public static bool TryParse(string message, out ManagementServiceExceptionInfo info)
        {
            string errorType;
            Guid activityId;
            IDictionary propertyBag;

            if (string.IsNullOrEmpty(message))
            {
                // Empty message
                info = default(ManagementServiceExceptionInfo);
                return false;
            }

            XDocument errorDocument;
            try
            {
                errorDocument = XDocument.Parse(message);
            }
            catch (XmlException)
            {
                // Invalid xml
                info = default(ManagementServiceExceptionInfo);
                return false;
            }

            if (errorDocument == null)
            {
                // Invalid xml
                info = default(ManagementServiceExceptionInfo);
                return false;
            }

            // Attempt to get error information from the standard location in a DataServiceException.
            XElement errorMessage;
            errorMessage = errorDocument.Descendants().Where(x => x.Name.LocalName == "code").FirstOrDefault();

            if (errorMessage == null)
            {
                // Attempt to get error information from the exception Message.  This happens in the case of a WebServiceAuthenticationException
                // being thrown by Management Service.
                errorMessage = errorDocument.Descendants().Where(x => x.Name.LocalName == "Message").FirstOrDefault();

                if (errorMessage == null)
                {
                    // Unable to find an error message.
                    info = default(ManagementServiceExceptionInfo);
                    return false;
                }
            }

            // Use Regex to parse the message
            Match code = errorCodeParser.Match(errorMessage.Value);
            if (code == null)
            {
                // Regex parsing failed
                info = default(ManagementServiceExceptionInfo);
                return false;
            }

            errorType = code.Groups["ErrorType"].Value;

            try
            {
                activityId = new Guid(code.Groups["ActivityId"].Value);
            }
            catch (FormatException)
            {
                // Guid parsing failed
                info = default(ManagementServiceExceptionInfo);
                return false;
            }

            // Only parse the property bag if it exists
            if (code.Groups["KeyValuePairs"].Success)
            {
                try
                {
                    string dataStr = code.Groups["KeyValuePairs"].Value;
                    propertyBag = (IDictionary)Deserialize(dataStr);
                }
                catch (Exception)
                {
                    // Invalid property bag
                    info = default(ManagementServiceExceptionInfo);
                    return false;
                }
            }
            else
            {
                // create an empty property bag
                propertyBag = (IDictionary)new Dictionary<string, string>();
            }

            info = new ManagementServiceExceptionInfo(errorType, activityId, propertyBag);
            return true;
        }