Ejemplo n.º 1
0
		public void CtorMessageAndInner()
		{
			Exception inner = new Exception ("inner");
			var ex = new DataServiceException ("message", inner);

			Assert.AreEqual ("message", ex.Message);
			Assert.AreEqual (inner, ex.InnerException);
		}
Ejemplo n.º 2
0
		public void CtorStatusAndErrorMessageLanguageException()
		{
			Exception inner = new Exception ("inner");
			var ex = new DataServiceException (404, "error", "message", "language", inner);
			Assert.AreEqual ("message", ex.Message);
			Assert.AreEqual (404, ex.StatusCode);
			Assert.AreEqual ("language", ex.MessageLanguage);
			Assert.AreEqual (inner, ex.InnerException);
		}
Ejemplo n.º 3
0
        /// <summary>Gets the value for the specified item in the request query string.</summary>
        /// <param name="item">Item to return.</param>
        /// <returns>
        /// The value for the specified item in the request query string;
        /// null if <paramref name="item"/> is not found.
        /// </returns>
        string IDataServiceHost.GetQueryStringItem(string item)
        {
            Debug.Assert(item != null, "item != null");
            Debug.Assert(item.Trim() == item, "item.Trim() == item - otherwise, there are leading/trailing spaces in the name");

            System.Collections.Specialized.NameValueCollection collection = this.operationContext.IncomingRequest.UriTemplateMatch.QueryParameters;
            string[] values = collection.GetValues(item);
            if (values == null || values.Length == 0)
            {
                // Do a scan of arguments ignoring whitespace (SQLBUDT #555944).
                string keyFound = null;
                foreach (string key in collection.Keys)
                {
                    if (key != null && StringComparer.OrdinalIgnoreCase.Equals(key.Trim(), item))
                    {
                        if (keyFound != null)
                        {
                            throw DataServiceException.CreateBadRequestError(Strings.HttpContextServiceHost_AmbiguousItemName(item, keyFound, key));
                        }

                        keyFound = key;
                        values   = collection.GetValues(key);
                    }
                }

                if (values == null || values.Length == 0)
                {
                    return(null);
                }
            }

            Debug.Assert(values != null && values.Length > 0, "values != null && values.Length > 0 - otherwise we should have returned already");
            if (values.Length == 1)
            {
                return(values[0]);
            }
            else
            {
                throw DataServiceException.CreateSyntaxError();
            }
        }
Ejemplo n.º 4
0
        private static ExpandedProjectionNode ApplyProjectionForProperty(ExpandedProjectionNode parentNode, string propertyName, ResourceProperty property, ResourceType targetResourceType, bool lastPathSegment)
        {
            if (property != null)
            {
                switch (property.TypeKind)
                {
                case ResourceTypeKind.ComplexType:
                    if (!lastPathSegment)
                    {
                        throw DataServiceException.CreateBadRequestError(System.Data.Services.Strings.RequestQueryProcessor_ComplexPropertyAsInnerSelectSegment(targetResourceType.FullName, propertyName));
                    }
                    break;

                case ResourceTypeKind.Primitive:
                    if (!lastPathSegment)
                    {
                        if (property.IsOfKind(ResourcePropertyKind.Stream))
                        {
                            throw DataServiceException.CreateBadRequestError(System.Data.Services.Strings.RequestQueryProcessor_NamedStreamMustBeLastSegmentInSelect(propertyName));
                        }
                        throw DataServiceException.CreateBadRequestError(System.Data.Services.Strings.RequestQueryProcessor_PrimitivePropertyUsedAsNavigationProperty(targetResourceType.FullName, propertyName));
                    }
                    break;

                case ResourceTypeKind.Collection:
                    if (!lastPathSegment)
                    {
                        throw DataServiceException.CreateBadRequestError(System.Data.Services.Strings.RequestQueryProcessor_CollectionPropertyAsInnerSelectSegment(targetResourceType.FullName, propertyName));
                    }
                    break;
                }
            }
            ExpandedProjectionNode node = parentNode.AddProjectionNode(propertyName, property, targetResourceType, lastPathSegment);

            if (lastPathSegment && (node != null))
            {
                node.ProjectionFound = true;
                node.MarkSubtreeAsProjected();
            }
            return(node);
        }
Ejemplo n.º 5
0
 private Version GetMinDataServiceVersion(Version maxProtocolVersion)
 {
     if (this.requestMinVersion == null)
     {
         this.TryGetMinDataServiceVersionFromWrappedHost(out this.requestMinVersion);
         if ((maxProtocolVersion < RequestDescription.Version3Dot0) || (this.requestMinVersion == null))
         {
             this.requestMinVersion = RequestDescription.DataServiceDefaultResponseVersion;
         }
         else
         {
             if (this.requestMinVersion > maxProtocolVersion)
             {
                 throw DataServiceException.CreateBadRequestError(Strings.DataService_MinDSVGreaterThanMPV(this.requestMinVersion.ToString(2), maxProtocolVersion.ToString(2)));
             }
             if (!RequestDescription.IsKnownRequestVersion(this.requestMinVersion))
             {
                 throw DataServiceException.CreateBadRequestError(Strings.DataService_InvalidMinDSV(this.requestMinVersion.ToString(2), KnownDataServiceVersionsToString(GetMaxRequestVersionAllowed(maxProtocolVersion))));
             }
         }
     }
     return(this.requestMinVersion);
 }
Ejemplo n.º 6
0
 private void CheckExpandPaths()
 {
     if (this.expandPathsAsText.Count > 0)
     {
         if (this.queryExpression == null)
         {
             throw DataServiceException.CreateBadRequestError(System.Data.Services.Strings.RequestQueryProcessor_QueryExpandOptionNotApplicable);
         }
         if (this.description.TargetResourceType.ResourceTypeKind == ResourceTypeKind.Collection)
         {
             throw DataServiceException.CreateBadRequestError(System.Data.Services.Strings.RequestQueryProcessor_QueryExpandOptionNotApplicable);
         }
     }
     this.expandPaths = new List <ExpandSegmentCollection>(this.expandPathsAsText.Count);
     for (int i = this.expandPathsAsText.Count - 1; i >= 0; i--)
     {
         ExpandSegmentCollection item = this.CheckSingleExpandPath(this.expandPathsAsText[i]);
         if (item == null)
         {
             this.expandPathsAsText.RemoveAt(i);
         }
         else
         {
             this.expandPaths.Add(item);
             ExpandedProjectionNode rootProjectionNode = this.GetRootProjectionNode();
             for (int j = 0; j < item.Count; j++)
             {
                 ExpandSegment          segment = item[j];
                 ExpandedProjectionNode node2   = rootProjectionNode.AddExpandedNode(segment);
                 this.GetRootProjectionNode().ExpansionOnDerivedTypesSpecified |= rootProjectionNode.HasExpandedPropertyOnDerivedType;
                 rootProjectionNode = node2;
             }
             this.GetRootProjectionNode().ExpansionsSpecified = true;
         }
     }
 }
Ejemplo n.º 7
0
        private void SerializeXmlError(XmlWriter writer)
        {
            string str;
            string str2;
            string str3;

            writer.WriteStartElement("error", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
            DataServiceException exception = ExtractErrorValues(this.exceptionArgs.Exception, out str, out str2, out str3);

            writer.WriteStartElement("code", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
            writer.WriteString(str);
            writer.WriteEndElement();
            writer.WriteStartElement("message", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
            writer.WriteAttributeString("xml", "lang", null, str3);
            writer.WriteString(str2);
            writer.WriteEndElement();
            if (this.exceptionArgs.UseVerboseErrors)
            {
                Exception exception2 = (exception == null) ? this.exceptionArgs.Exception : exception.InnerException;
                SerializeXmlException(writer, exception2);
            }
            writer.WriteEndElement();
            writer.Flush();
        }
Ejemplo n.º 8
0
 /// <summary>create exception when CUD operation is specified in batch</summary>
 /// <returns>exception to throw</returns>
 internal static DataServiceException BatchStreamOnlyGETOperationsCanBeSpecifiedInBatch()
 {
     return(Trace(DataServiceException.CreateBadRequestError(Strings.BatchStream_OnlyGETOperationsCanBeSpecifiedInBatch)));
 }
Ejemplo n.º 9
0
 /// <summary>create exception when content length is not valid</summary>
 /// <param name="contentLength">content length as specified in the request.</param>
 /// <returns>exception to throw</returns>
 internal static DataServiceException BatchStreamInvalidContentLengthSpecified(string contentLength)
 {
     return(Trace(DataServiceException.CreateBadRequestError(Strings.BatchStream_InvalidContentLengthSpecified(contentLength))));
 }
Ejemplo n.º 10
0
 /// <summary>create exception when http method name is not valid</summary>
 /// <param name="methodName">name of the http method as specified in the request.</param>
 /// <returns>exception to throw</returns>
 internal static DataServiceException BatchStreamInvalidHttpMethodName(string methodName)
 {
     return(Trace(DataServiceException.CreateBadRequestError(Strings.BatchStream_InvalidHttpMethodName(methodName))));
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Parse the given etag value in the If-Match request header.
        /// </summary>
        /// <param name="etagProperties">List of etag properties for the type whose etag values we are parsing.</param>
        /// <param name="ifMatchHeaderValue">value of the If-Match header as specified in the request.</param>
        /// <returns>returns the etag value as a list containing the property name and its corresponding value. If the If-Match header value is '*', then returns an empty collection.</returns>
        private static IEnumerable <KeyValuePair <string, object> > ParseETagValue(IList <ResourceProperty> etagProperties, string ifMatchHeaderValue)
        {
            Debug.Assert(etagProperties != null && etagProperties.Count != 0, "There must be atleast one etag property specified");
            Debug.Assert(!String.IsNullOrEmpty(ifMatchHeaderValue), "IfMatch header cannot be null");

            if (ifMatchHeaderValue == XmlConstants.HttpAnyETag)
            {
                // if the value is '*', then we return an empty IEnumerable.
                return(new KeyValuePair <string, object> [0]);
            }

            Debug.Assert(ifMatchHeaderValue.StartsWith(XmlConstants.HttpWeakETagPrefix, StringComparison.Ordinal), "If-Match header must be properly formatted - this check is done in DataService.CheckETagValues method");
            Debug.Assert(ifMatchHeaderValue.Length >= XmlConstants.HttpWeakETagPrefix.Length + 1, "If-Match header must be properly formatted - this check is done in DataService.CheckETagValues method");

            // Just get the etag value - we need to ignore the 'W/"' and the last '"' character from the etag
            string strippedETag = ifMatchHeaderValue.Substring(XmlConstants.HttpWeakETagPrefix.Length, ifMatchHeaderValue.Length - XmlConstants.HttpWeakETagPrefix.Length - 1);

            KeyInstance keyInstance = null;
            bool        success;
            Exception   innerException = null;

            // In V1, when we didn't have IConcurrencyProvider interface, we always used to compute the
            // latest etag from the entity instance we got from IUpdatable.GetResource and then comparing
            // it with the If-Match request header. Hence all invalid cases always used to throw
            // DataServiceException with 412, since the etags didn't match.
            // In V1.5, we have added the support for IConcurrencyProvider, which means we need to parse
            // the etag values and parse it to the provider, if it has implement this interface. To avoid
            // breaking changes, we need to catch all parsing errors and report them as 412 instead of 400
            // to avoid it from becoming a breaking change.
            try
            {
                success = KeyInstance.TryParseNullableTokens(Uri.UnescapeDataString(strippedETag), out keyInstance);
            }
            catch (DataServiceException e)
            {
                success        = false;
                innerException = e;
            }

            if (!success)
            {
                // We could have throwed BadRequest here since the etag value is not properly formattted. But since
                // we used to do throw 412 in V1, keeping it that way to avoid breaking change.
                throw DataServiceException.CreatePreConditionFailedError(Strings.Serializer_ETagValueDoesNotMatch, innerException);
            }

            if (keyInstance.PositionalValues.Count != etagProperties.Count)
            {
                // We could have throwed BadRequest here since the etag value is not properly formattted. But since
                // we used to do throw 412 in V1, keeping it that way to avoid breaking change.
                throw DataServiceException.CreatePreConditionFailedError(Strings.Serializer_ETagValueDoesNotMatch);
            }

            KeyValuePair <string, object>[] etagPropertyInfo = new KeyValuePair <string, object> [etagProperties.Count];
            for (int i = 0; i < etagPropertyInfo.Length; i++)
            {
                ResourceProperty etagProperty  = etagProperties[i];
                object           propertyValue = null;
                string           value         = (string)keyInstance.PositionalValues[i];

                if (value != XmlConstants.NullLiteralInETag)
                {
                    // The reason we need to catch the Overflow Exception here is because of the Bug #679728.
                    // In V1, when we didn't have IConcurrencyProvider interface, we always used to compute the
                    // latest etag from the entity instance we got from IUpdatable.GetResource and then comparing
                    // it with the If-Match request header. Hence all invalid cases always used to throw
                    // DataServiceException with 412, since the etags didn't match.
                    // In V1.5, we have added the support for IConcurrencyProvider, which means we need to parse
                    // the etag values and parse it to the provider, if it has implement this interface. To avoid
                    // breaking changes, we need to catch all parsing errors and report them as 412 instead of 400
                    // to avoid it from becoming a breaking change.
                    try
                    {
                        success = System.Data.Services.Parsing.WebConvert.TryKeyStringToPrimitive(value, etagProperty.Type, out propertyValue);
                    }
                    catch (OverflowException e)
                    {
                        success        = false;
                        innerException = e;
                    }

                    if (!success)
                    {
                        // We could have throwed BadRequest here since the etag value is not properly formattted. But since
                        // we used to do throw 412 in V1, keeping it that way to avoid breaking change.
                        throw DataServiceException.CreatePreConditionFailedError(Strings.Serializer_ETagValueDoesNotMatch, innerException);
                    }
                }

                etagPropertyInfo[i] = new KeyValuePair <string, object>(etagProperties[i].Name, propertyValue);
            }

            return(etagPropertyInfo);
        }
Ejemplo n.º 12
0
 /// <summary>internal error where the first request header is not of the form: 'MethodName' 'Url' 'Version'</summary>
 /// <param name="header">actual header value specified in the payload.</param>
 /// <returns>exception to throw</returns>
 internal static InvalidOperationException BatchStreamInvalidMethodHeaderSpecified(string header)
 {
     return(Trace(DataServiceException.CreateBadRequestError(Strings.BatchStream_InvalidMethodHeaderSpecified(header))));
 }
Ejemplo n.º 13
0
 /// <summary>create exception when more data is specified after end of batch delimiter.</summary>
 /// <returns>exception to throw</returns>
 internal static DataServiceException BatchStreamMoreDataAfterEndOfBatch()
 {
     return(Trace(DataServiceException.CreateBadRequestError(Strings.BatchStream_MoreDataAfterEndOfBatch)));
 }
Ejemplo n.º 14
0
		internal static Exception CheckPowershellForException(string cmdletName, CommandType commandType, System.Management.Automation.PowerShell powerShell)
		{
			Exception streamException = PSCommand.CheckInvocationStateInfoForException(powerShell.InvocationStateInfo);
			if (streamException == null)
			{
				streamException = PSCommand.GetStreamException(cmdletName, powerShell.Streams);
			}
			string commandText = powerShell.Commands.Commands[0].CommandText;
			if (streamException != null)
			{
				if (!(streamException.GetType() == typeof(ItemNotFoundException)) || commandType != CommandType.Read && commandType != CommandType.Delete && commandType != CommandType.Update)
				{
					streamException = new CommandInvocationFailedException(commandText, streamException);
				}
				else
				{
					if (commandType == CommandType.Read || commandType == CommandType.Delete)
					{
						string[] str = new string[7];
						str[0] = "Cmdlet ";
						str[1] = cmdletName;
						str[2] = " generated ItemNotFoundException exception. Command string was ";
						str[3] = commandText;
						str[4] = ". But this is a ";
						str[5] = commandType.ToString();
						str[6] = "operation, so suppressing that message";
						TraceHelper.Current.DebugMessage(string.Concat(str));
						streamException = null;
					}
					else
					{
						string[] strArrays = new string[5];
						strArrays[0] = "Cmdlet ";
						strArrays[1] = cmdletName;
						strArrays[2] = " generated ItemNotFoundException exception. Command string was ";
						strArrays[3] = commandText;
						strArrays[4] = ". But the operation is Update, so throwing DataServiceException with 404";
						TraceHelper.Current.DebugMessage(string.Concat(strArrays));
						streamException = new DataServiceException(0x194, null, Resources.ResourceNotFoundException, null, streamException);
					}
				}
			}
			return streamException;
		}
 /// <summary>Creates a new "Bad Request" exception for recursion limit exceeded.</summary>
 /// <param name="recursionLimit">Recursion limit that was reaced.</param>
 /// <returns>A new exception to indicate that the request is rejected.</returns>
 internal static DataServiceException CreateDeepRecursion(int recursionLimit)
 {
     return(DataServiceException.CreateBadRequestError(Strings.BadRequest_DeepRecursion(recursionLimit)));
 }
Ejemplo n.º 16
0
 /// <summary>internal error when content type header is missing</summary>
 /// <param name="headerName">name of the missing header</param>
 /// <returns>exception to throw</returns>
 internal static InvalidOperationException BatchStreamMissingContentTypeHeader(string headerName)
 {
     return(Trace(DataServiceException.CreateBadRequestError(Strings.BatchStream_MissingContentTypeHeader(headerName))));
 }
Ejemplo n.º 17
0
        private ExpandSegmentCollection CheckSingleExpandPath(List <string> path)
        {
            ResourceType            targetResourceType = this.description.TargetResourceType;
            ResourceSetWrapper      targetContainer    = this.description.LastSegmentInfo.TargetContainer;
            ExpandSegmentCollection segments           = new ExpandSegmentCollection(path.Count);
            bool flag = false;
            bool previousSegmentIsTypeSegment = false;

            for (int i = 0; i < path.Count; i++)
            {
                string propertyName                     = path[i];
                ResourcePropertyKind stream             = ResourcePropertyKind.Stream;
                ResourceProperty     navigationProperty = targetResourceType.TryResolvePropertyName(propertyName, stream);
                if (navigationProperty == null)
                {
                    ResourceType type2 = WebUtil.ResolveTypeIdentifier(this.service.Provider, propertyName, targetResourceType, previousSegmentIsTypeSegment);
                    if (type2 == null)
                    {
                        if (targetResourceType.IsOpenType)
                        {
                            throw DataServiceException.CreateBadRequestError(System.Data.Services.Strings.OpenNavigationPropertiesNotSupportedOnOpenTypes(propertyName));
                        }
                        throw DataServiceException.CreateSyntaxError(System.Data.Services.Strings.RequestUriProcessor_PropertyNotFound(targetResourceType.FullName, propertyName));
                    }
                    this.description.VerifyProtocolVersion(RequestDescription.Version3Dot0, this.service);
                    targetResourceType           = type2;
                    previousSegmentIsTypeSegment = true;
                }
                else
                {
                    previousSegmentIsTypeSegment = false;
                    if (navigationProperty.TypeKind == ResourceTypeKind.EntityType)
                    {
                        targetContainer = this.service.Provider.GetContainer(targetContainer, targetResourceType, navigationProperty);
                        if (targetContainer == null)
                        {
                            throw DataServiceException.CreateBadRequestError(System.Data.Services.Strings.BadRequest_InvalidPropertyNameSpecified(navigationProperty.Name, targetResourceType.FullName));
                        }
                        bool singleResult = navigationProperty.Kind == ResourcePropertyKind.ResourceReference;
                        DataServiceConfiguration.CheckResourceRightsForRead(targetContainer, singleResult);
                        Expression filter = DataServiceConfiguration.ComposeQueryInterceptors(this.service, targetContainer);
                        if (((targetContainer.PageSize != 0) && !singleResult) && !this.IsCustomPaged)
                        {
                            OrderingInfo        orderingInfo = new OrderingInfo(true);
                            ParameterExpression expression   = Expression.Parameter(targetContainer.ResourceType.InstanceType, "p");
                            foreach (ResourceProperty property2 in targetContainer.GetKeyPropertiesForOrderBy())
                            {
                                Expression expression3;
                                if (property2.CanReflectOnInstanceTypeProperty)
                                {
                                    expression3 = Expression.Property(expression, targetContainer.ResourceType.GetPropertyInfo(property2));
                                }
                                else
                                {
                                    expression3 = Expression.Convert(Expression.Call(null, DataServiceProviderMethods.GetValueMethodInfo, expression, Expression.Constant(property2)), property2.Type);
                                }
                                orderingInfo.Add(new OrderingExpression(Expression.Lambda(expression3, new ParameterExpression[] { expression }), true));
                            }
                            segments.Add(new ExpandSegment(navigationProperty.Name, filter, targetContainer.PageSize, targetContainer, targetResourceType, navigationProperty, orderingInfo));
                            this.description.VerifyProtocolVersion(RequestDescription.Version2Dot0, this.service);
                            this.description.VerifyAndRaiseResponseVersion(RequestDescription.Version2Dot0, this.service);
                        }
                        else
                        {
                            if (!singleResult && this.IsCustomPaged)
                            {
                                this.CheckAndApplyCustomPaging(null);
                            }
                            segments.Add(new ExpandSegment(navigationProperty.Name, filter, this.service.Configuration.MaxResultsPerCollection, targetContainer, targetResourceType, navigationProperty, null));
                        }
                        this.description.UpdateAndCheckEpmFeatureVersion(targetContainer, this.service);
                        this.description.UpdateVersions(this.service.OperationContext.Host.RequestAccept, targetContainer, this.service);
                        flag = false;
                        targetResourceType = navigationProperty.ResourceType;
                    }
                    else
                    {
                        flag = true;
                    }
                }
            }
            if (previousSegmentIsTypeSegment)
            {
                throw DataServiceException.CreateBadRequestError(System.Data.Services.Strings.RequestQueryProcessor_QueryParametersPathCannotEndInTypeIdentifier("$expand", targetResourceType.FullName));
            }
            if (!flag)
            {
                return(segments);
            }
            return(null);
        }
Ejemplo n.º 18
0
 /// <summary>internal error number of headers at the start of changeset is not correct</summary>
 /// <param name="header1">First valid header name</param>
 /// <param name="header2">Second valid header name</param>
 /// <returns>exception to throw</returns>
 internal static InvalidOperationException BatchStreamInvalidNumberOfHeadersAtChangeSetStart(string header1, string header2)
 {
     return(Trace(DataServiceException.CreateBadRequestError(Strings.BatchStream_InvalidNumberOfHeadersAtChangeSetStart(header1, header2))));
 }
Ejemplo n.º 19
0
 /// <summary>internal error Content-Transfer-Encoding is not specified or its value is not 'binary'</summary>
 /// <param name="headerName">name of the header</param>
 /// <param name="headerValue">expected value of the header</param>
 /// <returns>exception to throw</returns>
 internal static InvalidOperationException BatchStreamMissingOrInvalidContentEncodingHeader(string headerName, string headerValue)
 {
     return(Trace(DataServiceException.CreateBadRequestError(Strings.BatchStream_MissingOrInvalidContentEncodingHeader(headerName, headerValue))));
 }
Ejemplo n.º 20
0
 /// <summary>internal error when http version in batching request is not valid</summary>
 /// <param name="actualVersion">actual version as specified in the payload.</param>
 /// <param name="expectedVersion">expected version value.</param>
 /// <returns>exception to throw</returns>
 internal static InvalidOperationException BatchStreamInvalidHttpVersionSpecified(string actualVersion, string expectedVersion)
 {
     return(Trace(DataServiceException.CreateBadRequestError(Strings.BatchStream_InvalidHttpVersionSpecified(actualVersion, expectedVersion))));
 }
Ejemplo n.º 21
0
 internal static DataServiceException CreateMethodNotAllowed(string message, string allow)
 {
     DataServiceException exception = new DataServiceException(0x195, message);
     exception.state.ResponseAllowHeader = allow;
     return exception;
 }
 /// <summary>Creates a new exception to indicate a syntax error.</summary>
 /// <param name="message">Plain text error message for this exception.</param>
 /// <returns>A new exception to indicate a syntax error.</returns>
 internal static DataServiceException CreateSyntaxError(string message)
 {
     return(DataServiceException.CreateBadRequestError(message));
 }
Ejemplo n.º 23
0
 /// <summary>internal error when content type header value is invalid.</summary>
 /// <param name="headerName">name of the header whose value is not correct.</param>
 /// <param name="headerValue">actual value as specified in the payload</param>
 /// <param name="mime1">expected value 1</param>
 /// <param name="mime2">expected value 2</param>
 /// <returns>exception to throw</returns>
 internal static InvalidOperationException BatchStreamInvalidContentTypeSpecified(string headerName, string headerValue, string mime1, string mime2)
 {
     return(Trace(DataServiceException.CreateBadRequestError(Strings.BatchStream_InvalidContentTypeSpecified(headerName, headerValue, mime1, mime2))));
 }
Ejemplo n.º 24
0
 /// <summary>internal error where batch stream does do look ahead when read request is smaller than boundary delimiter</summary>
 /// <returns>exception to throw</returns>
 internal static InvalidOperationException BatchStreamInternalBufferRequestTooSmall()
 {
     return(Trace(DataServiceException.CreateBadRequestError(Strings.BatchStream_InternalBufferRequestTooSmall)));
 }
Ejemplo n.º 25
0
 private void ApplyProjectionsToExpandTree(List <List <string> > selectPathsAsText)
 {
     for (int i = selectPathsAsText.Count - 1; i >= 0; i--)
     {
         List <string>          list = selectPathsAsText[i];
         ExpandedProjectionNode rootProjectionNode = this.GetRootProjectionNode();
         ResourceType           type = null;
         for (int j = 0; j < list.Count; j++)
         {
             bool   flag2;
             string containerQualifiedName = list[j];
             bool   lastPathSegment        = j == (list.Count - 1);
             rootProjectionNode.ProjectionFound = true;
             if (containerQualifiedName == "*")
             {
                 rootProjectionNode.ProjectAllImmediateProperties = true;
                 break;
             }
             if (this.service.Provider.GetNameFromContainerQualifiedName(containerQualifiedName, out flag2) == "*")
             {
                 rootProjectionNode.ProjectAllImmediateOperations = true;
                 break;
             }
             ResourceType     previousSegmentResourceType = type ?? rootProjectionNode.ResourceType;
             ResourceProperty property = previousSegmentResourceType.TryResolvePropertyName(containerQualifiedName);
             if (property == null)
             {
                 type = WebUtil.ResolveTypeIdentifier(this.service.Provider, containerQualifiedName, previousSegmentResourceType, type != null);
                 if (type != null)
                 {
                     this.description.VerifyProtocolVersion(RequestDescription.Version3Dot0, this.service);
                     continue;
                 }
                 Func <OperationWrapper, bool> predicate = null;
                 string           serviceActionName      = this.service.Provider.GetNameFromContainerQualifiedName(containerQualifiedName, out flag2);
                 OperationWrapper operation = null;
                 if (!previousSegmentResourceType.IsOpenType || flag2)
                 {
                     if (predicate == null)
                     {
                         predicate = o => o.Name == serviceActionName;
                     }
                     operation = this.service.ActionProvider.GetServiceActionsByBindingParameterType(this.service.OperationContext, previousSegmentResourceType).SingleOrDefault <OperationWrapper>(predicate);
                 }
                 if (operation != null)
                 {
                     rootProjectionNode.AddOperation(operation);
                     if (!lastPathSegment)
                     {
                         throw DataServiceException.CreateBadRequestError(System.Data.Services.Strings.RequestQueryProcessor_ServiceActionMustBeLastSegmentInSelect(containerQualifiedName));
                     }
                     continue;
                 }
                 if (!previousSegmentResourceType.IsOpenType)
                 {
                     throw DataServiceException.CreateSyntaxError(System.Data.Services.Strings.RequestUriProcessor_PropertyNotFound(previousSegmentResourceType.FullName, containerQualifiedName));
                 }
                 if (!lastPathSegment)
                 {
                     throw DataServiceException.CreateBadRequestError(System.Data.Services.Strings.OpenNavigationPropertiesNotSupportedOnOpenTypes(containerQualifiedName));
                 }
             }
             rootProjectionNode = ApplyProjectionForProperty(rootProjectionNode, containerQualifiedName, property, previousSegmentResourceType, lastPathSegment);
             type = null;
         }
         if (type != null)
         {
             throw DataServiceException.CreateBadRequestError(System.Data.Services.Strings.RequestQueryProcessor_QueryParametersPathCannotEndInTypeIdentifier("$select", type.FullName));
         }
     }
 }
Ejemplo n.º 26
0
 /// <summary>create exception when missing an expected batch boundary</summary>
 /// <returns>exception to throw</returns>
 internal static DataServiceException BatchStreamMissingBoundary()
 {
     return(Trace(DataServiceException.CreateBadRequestError(Strings.DataService_InvalidContentTypeForBatchRequest)));
 }
Ejemplo n.º 27
0
		private void ExecutionCompletionEventHandler(IAsyncResult ar)
		{
			Exception dataServiceException;
			lock (this.syncObject)
			{
				this.timer.Stop();
				this.isExecutionCompleted = true;
				if (!this.isExceedsMaxExecutionTime)
				{
					dataServiceException = PSCommand.CheckPowershellForException(this.cmdletInfo.CmdletName, this.commandType, this.powerShell);
				}
				else
				{
					object[] cmdletName = new object[1];
					cmdletName[0] = this.cmdletInfo.CmdletName;
					dataServiceException = new DataServiceException(0x193, ExceptionHelpers.GetDataServiceExceptionMessage(HttpStatusCode.Forbidden, Resources.CmdletExecutionQuotaExceeded, cmdletName));
					TraceHelper.Current.CommandExecutionTimeExceeded(this.cmdletInfo.CmdletName, this.runspace.Borrower.Name, DataServiceController.Current.Configuration.PowerShell.Quotas.MaxExecutionTime, 0);
					DataServiceController.Current.PerfCounters.SystemQuotaViolationsPerSec.Increment();
					DataServiceController.Current.QuotaSystem.SystemQuotaViolation.Increment();
				}
				if (this.output != null && dataServiceException == null)
				{
					foreach (PSObject pSObject in this.output)
					{
						if (pSObject == null)
						{
							continue;
						}
						DSResource dSResource = SerializerBase.SerializeEntity(pSObject, this.entityType);
						this.dataStore.Add(dSResource);
					}
				}
				this.dataStore.Completed(dataServiceException);
				this.powerShell.Trace();
			}
			this.Dispose();
		}
Ejemplo n.º 28
0
 /// <summary>create exception when unexpected content is discovered</summary>
 /// <param name="state">http method operation</param>
 /// <returns>exception to throw</returns>
 internal static DataServiceException BatchStreamContentUnexpected(BatchStreamState state)
 {
     return(Trace(DataServiceException.CreateBadRequestError(Strings.BatchStream_ContentUnexpected(state.ToString()))));
 }
 /// <summary>Creates a new "Bad Request" exception for recursion limit exceeded.</summary>
 /// <returns>A new exception to indicate that the request is rejected.</returns>
 internal static DataServiceException CreateDeepRecursion_General()
 {
     return(DataServiceException.CreateBadRequestError(Strings.BadRequest_DeepRecursion_General));
 }
Ejemplo n.º 30
0
 /// <summary>create exception when Get operation is specified in changeset</summary>
 /// <returns>exception to throw</returns>
 internal static DataServiceException BatchStreamGetMethodNotSupportInChangeset()
 {
     return(Trace(DataServiceException.CreateBadRequestError(Strings.BatchStream_GetMethodNotSupportedInChangeset)));
 }
Ejemplo n.º 31
0
		public void CtorMessage()
		{
			var ex = new DataServiceException ("message");
			Assert.AreEqual ("message", ex.Message);
			Assert.IsNull (ex.InnerException);
		}
Ejemplo n.º 32
0
 /// <summary>create exception when invalid batch request is specified</summary>
 /// <returns>exception to throw</returns>
 internal static DataServiceException BatchStreamInvalidBatchFormat()
 {
     return(Trace(DataServiceException.CreateBadRequestError(Strings.BatchStream_InvalidBatchFormat)));
 }
Ejemplo n.º 33
0
		public void CtorStatusAndMessage()
		{
			var ex = new DataServiceException (404, "message");
			Assert.AreEqual (404, ex.StatusCode);
			Assert.AreEqual ("message", ex.Message);
		}
Ejemplo n.º 34
0
 /// <summary>create exception when boundary delimiter is not valid</summary>
 /// <param name="delimiter">delimiter specified as specified in the request.</param>
 /// <returns>exception to throw</returns>
 internal static DataServiceException BatchStreamInvalidDelimiter(string delimiter)
 {
     return(Trace(DataServiceException.CreateBadRequestError(Strings.BatchStream_InvalidDelimiter(delimiter))));
 }
Ejemplo n.º 35
0
        /// <summary>
        /// If the provider implements IConcurrencyProvider, then this method passes the etag values
        /// to the provider, otherwise compares the etag itself.
        /// </summary>
        /// <param name="resourceCookie">etag values for the given resource.</param>
        /// <param name="container">container for the given resource.</param>
        internal void SetETagValues(object resourceCookie, ResourceSetWrapper container)
        {
            Debug.Assert(resourceCookie != null, "resourceCookie != null");
            Debug.Assert(container != null, "container != null");
            DataServiceHostWrapper host = this.service.OperationContext.Host;

            Debug.Assert(String.IsNullOrEmpty(host.RequestIfNoneMatch), "IfNoneMatch header cannot be specified for Update/Delete operations");

            // Resolve the cookie first to the actual resource type
            object actualEntity = this.ResolveResource(resourceCookie);

            Debug.Assert(actualEntity != null, "actualEntity != null");

            ResourceType resourceType = WebUtil.GetNonPrimitiveResourceType(this.service.Provider, actualEntity);

            Debug.Assert(resourceType != null, "resourceType != null");

            IList <ResourceProperty> etagProperties = this.service.Provider.GetETagProperties(container.Name, resourceType);

            if (etagProperties.Count == 0)
            {
                if (!String.IsNullOrEmpty(host.RequestIfMatch))
                {
                    throw DataServiceException.CreateBadRequestError(Strings.Serializer_NoETagPropertiesForType);
                }

                // If the type has no etag properties, then we do not need to do any etag checks
                return;
            }

            // If the provider implements IConcurrencyProvider, then we need to call the provider
            // and pass the etag values. Else, we need to compare the etag values ourselves.
            IDataServiceUpdateProvider concurrencyProvider = this.updateProvider as IDataServiceUpdateProvider;

            if (concurrencyProvider != null)
            {
                bool?checkForEquality = null;
                IEnumerable <KeyValuePair <string, object> > etagValues = null;
                if (!String.IsNullOrEmpty(host.RequestIfMatch))
                {
                    checkForEquality = true;
                    etagValues       = ParseETagValue(etagProperties, host.RequestIfMatch);
                }
                else
                {
                    etagValues = new KeyValuePair <string, object> [0];
                }

                concurrencyProvider.SetConcurrencyValues(resourceCookie, checkForEquality, etagValues);
            }
            else if (String.IsNullOrEmpty(host.RequestIfMatch))
            {
                throw DataServiceException.CreateBadRequestError(Strings.DataService_CannotPerformOperationWithoutETag(resourceType.FullName));
            }
            else if (host.RequestIfMatch != XmlConstants.HttpAnyETag)
            {
                // Compare If-Match header value with the current etag value, if the If-Match header value is not equal to '*'
                string etagValue = WebUtil.GetETagValue(resourceCookie, resourceType, etagProperties, this.service, false /*getMethod*/);
                Debug.Assert(!String.IsNullOrEmpty(etagValue), "etag value can never be null");

                if (etagValue != host.RequestIfMatch)
                {
                    throw DataServiceException.CreatePreConditionFailedError(Strings.Serializer_ETagValueDoesNotMatch);
                }
            }
        }
Ejemplo n.º 36
0
 /// <summary>create exception when end changeset boundary delimiter is missing</summary>
 /// <returns>exception to throw</returns>
 internal static DataServiceException BatchStreamMissingEndChangesetDelimiter()
 {
     return(Trace(DataServiceException.CreateBadRequestError(Strings.BatchStream_MissingEndChangesetDelimiter)));
 }
Ejemplo n.º 37
0
 /// <summary>Creates a new "Method Not Allowed" exception.</summary>
 /// <param name="message">Error message.</param>
 /// <param name="allow">String value for 'Allow' header in response.</param>
 /// <returns>A new exception to indicate the requested method is not allowed on the response.</returns>
 internal static DataServiceException CreateMethodNotAllowed(string message, string allow)
 {
     // 405 - Method Not Allowed
     DataServiceException result = new DataServiceException(405, message);
     result.responseAllowHeader = allow;
     return result;
 }
Ejemplo n.º 38
0
 /// <summary>create exception when header value specified is not valid</summary>
 /// <param name="headerValue">header value as specified in the request.</param>
 /// <returns>exception to throw</returns>
 internal static DataServiceException BatchStreamInvalidHeaderValueSpecified(string headerValue)
 {
     return(Trace(DataServiceException.CreateBadRequestError(Strings.BatchStream_InvalidHeaderValueSpecified(headerValue))));
 }