Exemplo n.º 1
0
        /// <summary>
        /// Initializes a new <see cref="QueryComponents"/> instance that can
        /// be used for this continuation.
        /// </summary>
        /// <returns>A new initializes <see cref="QueryComponents"/>.</returns>
        internal QueryComponents CreateQueryComponents()
        {
            // DSV needs to be 2.0 since $skiptoken will be on the uri.
            QueryComponents result = new QueryComponents(this.NextLinkUri, Util.DataServiceVersionEmpty, this.Plan.LastSegmentType, null, null);

            return(result);
        }
#pragma warning restore 649
#endif

        #endregion Private fields.

        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="context">originating context</param>
        /// <param name="reader">reader</param>
        /// <param name="queryComponents">Query components (projection, expected type)</param>
        /// <param name="plan">Projection plan (if compiled in an earlier query).</param>
        /// <param name="mergeOption">merge option to use for this materialization pass</param>
        internal MaterializeAtom(DataServiceContext context, XmlReader reader, QueryComponents queryComponents, ProjectionPlan plan, MergeOption mergeOption)
        {
            Debug.Assert(queryComponents != null, "queryComponents != null");

            this.context                 = context;
            this.elementType             = queryComponents.LastSegmentType;
            this.MergeOptionValue        = mergeOption;
            this.ignoreMissingProperties = context.IgnoreMissingProperties;
            this.reader               = (reader == null) ? null : new System.Data.Services.Client.Xml.XmlAtomErrorReader(reader);
            this.countValue           = CountStateInitial;
            this.expectingSingleValue = ClientConvert.IsKnownNullableType(elementType);

            Debug.Assert(reader != null, "Materializer reader is null! Did you mean to use Materializer.ResultsWrapper/EmptyResults?");

            // NOTE: dataNamespace is used for reference equality, and while it looks like
            // a variable, it appears that it will only get set to XmlConstants.DataWebNamespace
            // at runtime. Therefore we remove string dataNamespace as a field here.
            // this.dataNamespace = reader != null ? reader.Settings.NameTable.Add(context.DataNamespace) : null;
            reader.Settings.NameTable.Add(context.DataNamespace);

            string typeScheme = this.context.TypeScheme.OriginalString;

            this.parser = new AtomParser(this.reader, AtomParser.XElementBuilderCallback, typeScheme, context.DataNamespace);
            AtomMaterializerLog log = new AtomMaterializerLog(this.context, mergeOption);
            Type implementationType;
            Type materializerType = GetTypeForMaterializer(this.expectingSingleValue, this.elementType, out implementationType);

            this.materializer = new AtomMaterializer(parser, context, materializerType, this.ignoreMissingProperties, mergeOption, log, this.MaterializedObjectCallback, queryComponents, plan);
        }
Exemplo n.º 3
0
#pragma warning restore 649
#endif

        #endregion Private fields.

        internal MaterializeAtom(DataServiceContext context, XmlReader reader, QueryComponents queryComponents, ProjectionPlan plan, MergeOption mergeOption)
        {
            Debug.Assert(queryComponents != null, "queryComponents != null");

            this.context                 = context;
            this.elementType             = queryComponents.LastSegmentType;
            this.MergeOptionValue        = mergeOption;
            this.ignoreMissingProperties = context.IgnoreMissingProperties;
            this.reader               = (reader == null) ? null : new System.Data.Services.Client.Xml.XmlAtomErrorReader(reader);
            this.countValue           = CountStateInitial;
            this.expectingSingleValue = ClientConvert.IsKnownNullableType(elementType);

            Debug.Assert(reader != null, "Materializer reader is null! Did you mean to use Materializer.ResultsWrapper/EmptyResults?");

            reader.Settings.NameTable.Add(context.DataNamespace);

            string typeScheme = this.context.TypeScheme.OriginalString;

            this.parser = new AtomParser(this.reader, AtomParser.XElementBuilderCallback, typeScheme, context.DataNamespace);
            AtomMaterializerLog log = new AtomMaterializerLog(this.context, mergeOption);
            Type implementationType;
            Type materializerType = GetTypeForMaterializer(this.expectingSingleValue, this.elementType, out implementationType);

            this.materializer = new AtomMaterializer(parser, context, materializerType, this.ignoreMissingProperties, mergeOption, log, this.MaterializedObjectCallback, queryComponents, plan);
        }
Exemplo n.º 4
0
        /// <summary>Create a request for a specific Uri</summary>
        /// <param name="requestUri">The URI for the request.</param>
        public DataServiceRequest(Uri requestUri)
        {
            Util.CheckArgumentNull(requestUri, "requestUri");
            Type elementType = typeof(TElement);

            elementType          = ClientConvert.IsKnownType(elementType) ? elementType : TypeSystem.GetElementType(elementType);
            this.queryComponents = new QueryComponents(requestUri, Util.DataServiceVersionEmpty, elementType, null, null);
        }
Exemplo n.º 5
0
        /// <summary>
        /// gets the query components for the query after translating
        /// </summary>
        /// <returns>QueryComponents for query</returns>
        private QueryComponents Translate()
        {
            if (this.queryComponents == null)
            {
                this.queryComponents = this.queryProvider.Translate(this.queryExpression);
            }

            return(this.queryComponents);
        }
Exemplo n.º 6
0
        /// <summary>Create a request for a specific Uri</summary>
        /// <param name="requestUri">The URI for the request.</param>
        /// <param name="queryComponents">The query components for the request</param>
        /// <param name="plan">Projection plan to reuse (possibly null).</param>
        internal DataServiceRequest(Uri requestUri, QueryComponents queryComponents, ProjectionPlan plan)
            : this(requestUri)
        {
            Debug.Assert(requestUri != null, "requestUri != null");
            Debug.Assert(queryComponents != null, "queryComponents != null");

            this.queryComponents = queryComponents;
            this.plan            = plan;
        }
Exemplo n.º 7
0
 internal MaterializeAtom(ResponseInfo responseInfo, QueryComponents queryComponents, ProjectionPlan plan, IODataResponseMessage responseMessage, ODataPayloadKind payloadKind)
 {
     Type type;
     this.responseInfo = responseInfo;
     this.elementType = queryComponents.LastSegmentType;
     this.MergeOptionValue = responseInfo.MergeOption;
     this.expectingPrimitiveValue = PrimitiveType.IsKnownNullableType(this.elementType);
     Type materializerType = GetTypeForMaterializer(this.expectingPrimitiveValue, this.elementType, responseInfo.MaxProtocolVersion, out type);
     this.materializer = ODataMaterializer.CreateMaterializerForMessage(responseMessage, responseInfo, materializerType, queryComponents, plan, payloadKind);
 }
Exemplo n.º 8
0
 internal MaterializeAtom(ResponseInfo responseInfo, IEnumerable<ODataEntry> entries, Type elementType)
 {
     Type type;
     this.responseInfo = responseInfo;
     this.elementType = elementType;
     this.MergeOptionValue = responseInfo.MergeOption;
     this.expectingPrimitiveValue = PrimitiveType.IsKnownNullableType(elementType);
     Type expectedType = GetTypeForMaterializer(this.expectingPrimitiveValue, this.elementType, responseInfo.MaxProtocolVersion, out type);
     QueryComponents queryComponents = new QueryComponents(null, Util.DataServiceVersionEmpty, elementType, null, null);
     this.materializer = new ODataEntriesEntityMaterializer(entries, responseInfo, queryComponents, expectedType, null);
 }
Exemplo n.º 9
0
        internal MaterializeAtom(ResponseInfo responseInfo, QueryComponents queryComponents, ProjectionPlan plan, IODataResponseMessage responseMessage, ODataPayloadKind payloadKind)
        {
            Type type;

            this.responseInfo            = responseInfo;
            this.elementType             = queryComponents.LastSegmentType;
            this.MergeOptionValue        = responseInfo.MergeOption;
            this.expectingPrimitiveValue = PrimitiveType.IsKnownNullableType(this.elementType);
            Type materializerType = GetTypeForMaterializer(this.expectingPrimitiveValue, this.elementType, responseInfo.MaxProtocolVersion, out type);

            this.materializer = ODataMaterializer.CreateMaterializerForMessage(responseMessage, responseInfo, materializerType, queryComponents, plan, payloadKind);
        }
Exemplo n.º 10
0
        internal MaterializeAtom(ResponseInfo responseInfo, IEnumerable <ODataEntry> entries, Type elementType)
        {
            Type type;

            this.responseInfo            = responseInfo;
            this.elementType             = elementType;
            this.MergeOptionValue        = responseInfo.MergeOption;
            this.expectingPrimitiveValue = PrimitiveType.IsKnownNullableType(elementType);
            Type            expectedType    = GetTypeForMaterializer(this.expectingPrimitiveValue, this.elementType, responseInfo.MaxProtocolVersion, out type);
            QueryComponents queryComponents = new QueryComponents(null, Util.DataServiceVersionEmpty, elementType, null, null);

            this.materializer = new ODataEntriesEntityMaterializer(entries, responseInfo, queryComponents, expectedType, null);
        }
Exemplo n.º 11
0
        /// <summary>The QueryComponents associated with this request</summary>
        /// <param name="model">The client model.</param>
        /// <returns>an instance of QueryComponents.</returns>
        internal override QueryComponents QueryComponents(ClientEdmModel model)
        {
            if (this.queryComponents == null)
            {
                Type elementType = typeof(TElement);

                // for 1..* navigation properties we need the type of the entity of the collection that is being navigated to. Otherwise we use TElement.
                elementType          = PrimitiveType.IsKnownType(elementType) || WebUtil.IsCLRTypeCollection(elementType, model) ? elementType : TypeSystem.GetElementType(elementType);
                this.queryComponents = new QueryComponents(this.requestUri, Util.DataServiceVersionEmpty, elementType, null, null);
            }

            return(this.queryComponents);
        }
Exemplo n.º 12
0
        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="responseInfo">originating context</param>
        /// <param name="entries">entries that needs to be materialized.</param>
        /// <param name="elementType">result type.</param>
        /// <param name="format">The format of the response being materialized from.</param>
        internal MaterializeAtom(ResponseInfo responseInfo, IEnumerable <ODataEntry> entries, Type elementType, ODataFormat format)
        {
            this.responseInfo            = responseInfo;
            this.elementType             = elementType;
            this.expectingPrimitiveValue = PrimitiveType.IsKnownNullableType(elementType);

            Type                     implementationType;
            Type                     materializerType = GetTypeForMaterializer(this.expectingPrimitiveValue, this.elementType, responseInfo.Model, out implementationType);
            QueryComponents          qc      = new QueryComponents(null, Util.DataServiceVersionEmpty, elementType, null, null);
            ODataMaterializerContext context = new ODataMaterializerContext(responseInfo);
            EntityTrackingAdapter    entityTrackingAdapter = new EntityTrackingAdapter(responseInfo.EntityTracker, responseInfo.MergeOption, responseInfo.Model, responseInfo.Context);

            this.materializer = new ODataEntriesEntityMaterializer(entries, context, entityTrackingAdapter, qc, materializerType, null, format);
        }
Exemplo n.º 13
0
        internal static MaterializeAtom Materialize(
            ResponseInfo responseInfo,
            QueryComponents queryComponents,
            ProjectionPlan plan,
            string contentType,
            IODataResponseMessage message,
            ODataPayloadKind expectedPayloadKind)
        {
            Debug.Assert(null != queryComponents, "querycomponents");
            Debug.Assert(null != message, "message");

            // If there is no content (For e.g. /Customers(1)/BestFriend is null), we need to return empty results.
            if (message.StatusCode == (int)HttpStatusCode.NoContent || String.IsNullOrEmpty(contentType))
            {
                return(MaterializeAtom.EmptyResults);
            }

            return(new MaterializeAtom(responseInfo, queryComponents, plan, message, expectedPayloadKind));
        }
Exemplo n.º 14
0
#pragma warning restore 649
#endif

        #endregion Private fields

        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="responseInfo">originating context</param>
        /// <param name="queryComponents">Query components (projection, expected type)</param>
        /// <param name="plan">Projection plan (if compiled in an earlier query).</param>
        /// <param name="responseMessage">responseMessage</param>
        /// <param name="payloadKind">The kind of the payload to materialize.</param>
        internal MaterializeAtom(
            ResponseInfo responseInfo,
            QueryComponents queryComponents,
            ProjectionPlan plan,
            IODataResponseMessage responseMessage,
            ODataPayloadKind payloadKind)
        {
            Debug.Assert(queryComponents != null, "queryComponents != null");

            this.responseInfo            = responseInfo;
            this.elementType             = queryComponents.LastSegmentType;
            this.expectingPrimitiveValue = PrimitiveType.IsKnownNullableType(elementType);

            Debug.Assert(responseMessage != null, "Response message is null! Did you mean to use Materializer.ResultsWrapper/EmptyResults?");
            this.responseMessage = responseMessage;

            Type implementationType;
            Type materializerType = GetTypeForMaterializer(this.expectingPrimitiveValue, this.elementType, responseInfo.Model, out implementationType);

            this.materializer = ODataMaterializer.CreateMaterializerForMessage(responseMessage, responseInfo, materializerType, queryComponents, plan, payloadKind);
        }
Exemplo n.º 15
0
        internal static MaterializeAtom Materialize(DataServiceContext context, QueryComponents queryComponents, ProjectionPlan plan, string contentType, Stream response)
        {
            Debug.Assert(null != queryComponents, "querycomponents");

            string mime = null;
            Encoding encoding = null;
            if (!String.IsNullOrEmpty(contentType))
            {
                HttpProcessUtility.ReadContentType(contentType, out mime, out encoding);
            }

            if (String.Equals(mime, XmlConstants.MimeApplicationAtom, StringComparison.OrdinalIgnoreCase) ||
                String.Equals(mime, XmlConstants.MimeApplicationXml, StringComparison.OrdinalIgnoreCase))
            {
                if (null != response)
                {
                    XmlReader reader = XmlUtil.CreateXmlReader(response, encoding);
                    return new MaterializeAtom(context, reader, queryComponents, plan, context.MergeOption);
                }
            }

            return MaterializeAtom.EmptyResults;
        }
Exemplo n.º 16
0
        /// <summary>
        /// Creates an instance of <see cref="MaterializeAtom"/> for the given plan.
        /// </summary>
        /// <param name="plan">The projection plan.</param>
        /// <param name="payloadKind">expected payload kind.</param>
        /// <returns>A new materializer instance</returns>
        private MaterializeAtom CreateMaterializer(ProjectionPlan plan, ODataPayloadKind payloadKind)
        {
            QueryComponents queryComponents = this.ServiceRequest.QueryComponents(this.responseInfo.Model);

            // In V2, in projection path, we did not check for assignability between the expected type and the type returned by the type resolver.
            if (plan != null || queryComponents.Projection != null)
            {
                this.RequestInfo.TypeResolver.IsProjectionRequest();
            }

            var responseMessageWrapper = new HttpWebResponseMessage(
                new HeaderCollection(this.responseMessage), 
                this.responseMessage.StatusCode, 
                this.GetResponseStream,
                this.AllowDirectNetworkStreamReading ? this.responseMessage : null); // If AllowDirectNetworkStreamReading is true, the responseMessage will be disposed later when enumeration has finished.

            return DataServiceRequest.Materialize(
                this.responseInfo,
                queryComponents,
                plan,
                this.ContentType,
                responseMessageWrapper,
                payloadKind);
        }
Exemplo n.º 17
0
 /// <summary>
 /// Sets the value of the Accept header for a query.
 /// </summary>
 /// <param name="headers">The headers to modify.</param>
 /// <param name="components">The query components for the request.</param>
 internal void SetRequestAcceptHeaderForQuery(HeaderCollection headers, QueryComponents components)
 {
     this.SetAcceptHeaderAndCharset(headers, this.ChooseMediaType(/*valueIfUsingAtom*/ MimeApplicationAtomOrXml, components.HasSelectQueryOption));
 }
Exemplo n.º 18
0
        internal QueryOperationResponse<TElement> Execute<TElement>(DataServiceContext context, QueryComponents queryComponents)
        {
            QueryResult result = null;
            try
            {
                DataServiceRequest<TElement> serviceRequest = new DataServiceRequest<TElement>(queryComponents, this.Plan);
                result = serviceRequest.CreateResult(this, context, null, null);
                result.Execute();
                return result.ProcessResult<TElement>(context, this.Plan);
            }
            catch (InvalidOperationException ex)
            {
                QueryOperationResponse operationResponse = result.GetResponse<TElement>(MaterializeAtom.EmptyResults);

                if (null != operationResponse)
                {
                    if (context.IgnoreResourceNotFoundException)
                    {
                        DataServiceClientException cex = ex as DataServiceClientException;
                        if (cex != null && cex.StatusCode == (int)HttpStatusCode.NotFound)
                        {
                            return (QueryOperationResponse<TElement>)operationResponse;
                        }
                    }

                    operationResponse.Error = ex;
                    throw new DataServiceQueryException(Strings.DataServiceException_GeneralError, ex, operationResponse);
                }

                throw;
            }
        }
        /// <summary>
        /// Initializes a new <see cref="QueryComponents"/> instance that can
        /// be used for this continuation.
        /// </summary>
        /// <returns>A new initializes <see cref="QueryComponents"/>.</returns>
        internal QueryComponents CreateQueryComponents()
        {
            QueryComponents result = new QueryComponents(this.NextLinkUri, Util.DataServiceVersionEmpty, this.Plan.LastSegmentType, null, null);

            return(result);
        }
Exemplo n.º 20
0
 public ODataEntriesEntityMaterializer(IEnumerable<ODataEntry> entries, ResponseInfo responseInfo, QueryComponents queryComponents, Type expectedType, ProjectionPlan materializeEntryPlan) : base(responseInfo, queryComponents, expectedType, materializeEntryPlan)
 {
     this.feedEntries = entries.GetEnumerator();
 }
Exemplo n.º 21
0
 internal QueryComponents CreateQueryComponents()
 {
     QueryComponents result = new QueryComponents(this.NextLinkUri, Util.DataServiceVersionEmpty, this.Plan.LastSegmentType, null, null);
     return result;
 }
Exemplo n.º 22
0
 public ODataReaderEntityMaterializer(ODataMessageReader odataMessageReader, ODataReader reader, ResponseInfo responseInfo, QueryComponents queryComponents, Type expectedType, ProjectionPlan materializeEntryPlan) : base(responseInfo, queryComponents, expectedType, materializeEntryPlan)
 {
     this.messageReader = odataMessageReader;
     this.itemReader = new ODataFeedOrEntryReader(reader, responseInfo);
 }
Exemplo n.º 23
0
        public static ODataMaterializer CreateMaterializerForMessage(IODataResponseMessage responseMessage, System.Data.Services.Client.ResponseInfo responseInfo, Type materializerType, QueryComponents queryComponents, ProjectionPlan plan, ODataPayloadKind payloadKind)
        {
            ODataMaterializer materializer2;
            bool projectionQuery = (plan != null) || (queryComponents.Projection != null);
            ODataMessageReader messageReader = CreateODataMessageReader(responseMessage, responseInfo, projectionQuery, ref payloadKind);
            IEdmType expectedType = null;
            try
            {
                ODataMaterializer materializer;
                if (materializerType != typeof(object))
                {
                    expectedType = ClientEdmModel.GetModel(responseInfo.MaxProtocolVersion).GetOrCreateEdmType(materializerType);
                }
                if ((payloadKind == ODataPayloadKind.Entry) || (payloadKind == ODataPayloadKind.Feed))
                {
                    if ((expectedType != null) && (expectedType.TypeKind != EdmTypeKind.Entity))
                    {
                        throw System.Data.Services.Client.Error.InvalidOperation(System.Data.Services.Client.Strings.AtomMaterializer_InvalidNonEntityType(materializerType.FullName));
                    }
                    ODataReader reader = CreateODataReader(messageReader, payloadKind, expectedType, responseInfo.MaxProtocolVersion);
                    materializer = new ODataReaderEntityMaterializer(messageReader, reader, responseInfo, queryComponents, materializerType, plan);
                }
                else
                {
                    switch (payloadKind)
                    {
                        case ODataPayloadKind.Property:
                            if ((expectedType != null) && (expectedType.TypeKind == EdmTypeKind.Entity))
                            {
                                throw System.Data.Services.Client.Error.InvalidOperation(System.Data.Services.Client.Strings.AtomMaterializer_InvalidEntityType(materializerType.FullName));
                            }
                            break;

                        case ODataPayloadKind.EntityReferenceLink:
                        case ODataPayloadKind.EntityReferenceLinks:
                            materializer = new ODataLinksMaterializer(messageReader, responseInfo, materializerType, queryComponents.SingleResult);
                            goto Label_013A;

                        case ODataPayloadKind.Value:
                            materializer = new ODataValueMaterializer(messageReader, responseInfo, materializerType, queryComponents.SingleResult);
                            goto Label_013A;

                        case ODataPayloadKind.BinaryValue:
                        case ODataPayloadKind.Collection:
                        case ODataPayloadKind.ServiceDocument:
                        case ODataPayloadKind.MetadataDocument:
                            goto Label_0129;

                        case ODataPayloadKind.Error:
                        {
                            ODataError error = messageReader.ReadError();
                            throw new ODataErrorException(error.Message, error);
                        }
                        default:
                            goto Label_0129;
                    }
                    materializer = new ODataPropertyMaterializer(messageReader, responseInfo, materializerType, queryComponents.SingleResult);
                }
                goto Label_013A;
            Label_0129:
                throw System.Data.Services.Client.Error.InvalidOperation(System.Data.Services.Client.Strings.AtomMaterializer_InvalidResponsePayload(responseInfo.DataNamespace));
            Label_013A:
                materializer2 = materializer;
            }
            catch (Exception exception)
            {
                if (CommonUtil.IsCatchableExceptionType(exception))
                {
                    messageReader.Dispose();
                }
                throw;
            }
            return materializer2;
        }
Exemplo n.º 24
0
        /// <summary>
        /// Creates the result object for the specified query parameters.
        /// </summary>
        /// <param name="source">The source object for the request.</param>
        /// <param name="context">The data service context.</param>
        /// <param name="callback">The AsyncCallback delegate.</param>
        /// <param name="state">The state object for the callback.</param>
        /// <param name="method">async method name at the source.</param>
        /// <returns>Result representing the create request. The request has not been initiated yet.</returns>
        private QueryResult CreateExecuteResult(object source, DataServiceContext context, AsyncCallback callback, object state, string method)
        {
            Debug.Assert(null != context, "context is null");

            QueryComponents qc          = this.QueryComponents(context.Model);
            RequestInfo     requestInfo = new RequestInfo(context);

            Debug.Assert(
                string.CompareOrdinal(XmlConstants.HttpMethodPost, qc.HttpMethod) == 0 ||
                string.CompareOrdinal(XmlConstants.HttpMethodGet, qc.HttpMethod) == 0,
                "Only get and post are supported in the execute pipeline, which should have been caught earlier");

            if (qc.UriOperationParameters != null)
            {
                Debug.Assert(qc.UriOperationParameters.Any(), "qc.UriOperationParameters.Any()");
                Serializer serializer = new Serializer(requestInfo);
                this.RequestUri = serializer.WriteUriOperationParametersToUri(this.RequestUri, qc.UriOperationParameters);
            }

            HeaderCollection headers = new HeaderCollection();

            if (string.CompareOrdinal(XmlConstants.HttpMethodPost, qc.HttpMethod) == 0)
            {
                if (qc.BodyOperationParameters == null)
                {
                    // set the content length to be 0 if there are no operation parameters.
                    headers.SetHeader(XmlConstants.HttpContentLength, "0");
                }
                else
                {
                    context.Format.SetRequestContentTypeForOperationParameters(headers);
                }
            }

            // Validate and set the request DSV and MDSV header
            headers.SetRequestVersion(qc.Version, requestInfo.MaxProtocolVersionAsVersion);

            requestInfo.Format.SetRequestAcceptHeaderForQuery(headers, qc);

            // We currently do not have a descriptor to expose to the user for invoking something through Execute. Ideally we could expose an OperationDescriptor.
            ODataRequestMessageWrapper requestMessage = new RequestInfo(context).WriteHelper.CreateRequestMessage(context.CreateRequestArgsAndFireBuildingRequest(qc.HttpMethod, this.RequestUri, headers, context.HttpStack, null /*descriptor*/));

            requestMessage.FireSendingRequest2(null /*descriptor*/);

            QueryResult queryResult = null;

            if (qc.BodyOperationParameters != null)
            {
                Debug.Assert(
                    string.CompareOrdinal(XmlConstants.HttpMethodPost, qc.HttpMethod) == 0,
                    "qc.HttpMethod == XmlConstants.HttpMethodPost");
                Debug.Assert(qc.BodyOperationParameters.Any(), "unexpected body operation parameter count of zero.");

                Serializer serializer = new Serializer(requestInfo);
                serializer.WriteBodyOperationParameters(qc.BodyOperationParameters, requestMessage);

                // pass in the request stream so that request payload can be written to the http webrequest.
                queryResult = new QueryResult(source, method, this, requestMessage, requestInfo, callback, state, requestMessage.CachedRequestStream);
            }
            else
            {
                queryResult = new QueryResult(source, method, this, requestMessage, requestInfo, callback, state);
            }

            return(queryResult);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Synchronizely get the query set count from the server by executing the $count=value query
        /// </summary>
        /// <param name="context">The context</param>
        /// <returns>The server side count of the query set</returns>
        internal long GetQuerySetCount(DataServiceContext context)
        {
            Debug.Assert(null != context, "context is null");
            Version requestVersion = this.QueryComponents(context.Model).Version;

            if (requestVersion == null || requestVersion.Major < 2)
            {
                // minimum DSV for $count is V2.
                requestVersion = Util.DataServiceVersion2;
            }

            QueryResult               response       = null;
            QueryComponents           qc             = this.QueryComponents(context.Model);
            Uri                       requestUri     = qc.Uri;
            DataServiceRequest <long> serviceRequest = new DataServiceRequest <long>(requestUri, qc, null);

            HeaderCollection headers = new HeaderCollection();

            // Validate and set the request DSV header
            headers.SetRequestVersion(requestVersion, context.MaxProtocolVersionAsVersion);
            context.Format.SetRequestAcceptHeaderForCount(headers);

            string httpMethod = XmlConstants.HttpMethodGet;
            ODataRequestMessageWrapper request = context.CreateODataRequestMessage(
                context.CreateRequestArgsAndFireBuildingRequest(httpMethod, requestUri, headers, context.HttpStack, null /*descriptor*/),
                new string[] { XmlConstants.HttpRequestAccept } /*headersToReset*/,
                null /*descriptor*/);

            response = new QueryResult(this, Util.ExecuteMethodName, serviceRequest, request, new RequestInfo(context), null, null);
            response.AllowDirectNetworkStreamReading = context.AllowDirectNetworkStreamReading;

            IODataResponseMessage responseMessage = null;

            try
            {
                responseMessage = response.ExecuteQuery();
                if (HttpStatusCode.NoContent != response.StatusCode)
                {
                    StreamReader sr = new StreamReader(response.GetResponseStream());
                    long         r  = -1;

                    try
                    {
                        r = XmlConvert.ToInt64(sr.ReadToEnd());
                    }
                    finally
                    {
                        sr.Close();
                    }

                    return(r);
                }
                else
                {
                    throw new DataServiceQueryException(Strings.DataServiceRequest_FailGetCount, response.Failure);
                }
            }
            catch (InvalidOperationException ex)
            {
                QueryOperationResponse operationResponse = null;
                operationResponse = response.GetResponse <long>(MaterializeAtom.EmptyResults);
                if (null != operationResponse)
                {
                    operationResponse.Error = ex;
                    throw new DataServiceQueryException(Strings.DataServiceException_GeneralError, ex, operationResponse);
                }

                throw;
            }
            finally
            {
                WebUtil.DisposeMessage(responseMessage);
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// execute uri and materialize result
        /// </summary>
        /// <typeparam name="TElement">element type</typeparam>
        /// <param name="context">context</param>
        /// <param name="queryComponents">query components for request to execute</param>
        /// <returns>enumerable of results</returns>
        internal QueryOperationResponse <TElement> Execute <TElement>(DataServiceContext context, QueryComponents queryComponents)
        {
            QueryResult result = null;

            try
            {
                Uri requestUri = queryComponents.Uri;
                DataServiceRequest <TElement> serviceRequest = new DataServiceRequest <TElement>(requestUri, queryComponents, this.Plan);
                result = serviceRequest.CreateExecuteResult(this, context, null, null, Util.ExecuteMethodName);
                result.AllowDirectNetworkStreamReading = context.AllowDirectNetworkStreamReading;
                result.ExecuteQuery();
                return(result.ProcessResult <TElement>(this.Plan));
            }
            catch (InvalidOperationException ex)
            {
                if (result != null)
                {
                    QueryOperationResponse operationResponse = result.GetResponse <TElement>(MaterializeAtom.EmptyResults);

                    if (null != operationResponse)
                    {
                        if (context.IgnoreResourceNotFoundException)
                        {
                            DataServiceClientException cex = ex as DataServiceClientException;
                            if (cex != null && cex.StatusCode == (int)HttpStatusCode.NotFound)
                            {
                                // don't throw
                                return((QueryOperationResponse <TElement>)operationResponse);
                            }
                        }

                        operationResponse.Error = ex;
                        throw new DataServiceQueryException(Strings.DataServiceException_GeneralError, ex, operationResponse);
                    }
                }

                throw;
            }
        }