示例#1
0
 protected static void ApplyPreferences(ODataRequestMessageWrapper requestMessage, string method, DataServiceResponsePreference responsePreference, ref Version requestVersion)
 {
     if (((string.CompareOrdinal("POST", method) == 0) || (string.CompareOrdinal("PUT", method) == 0)) || ((string.CompareOrdinal("MERGE", method) == 0) || (string.CompareOrdinal("PATCH", method) == 0)))
     {
         string preferHeaderAndRequestVersion = WebUtil.GetPreferHeaderAndRequestVersion(responsePreference, ref requestVersion);
         if (preferHeaderAndRequestVersion != null)
         {
             requestMessage.SetHeader("Prefer", preferHeaderAndRequestVersion);
         }
     }
 }
示例#2
0
        private ODataRequestMessageWrapper CheckAndProcessMediaEntryPost(EntityDescriptor entityDescriptor)
        {
            ClientEdmModel       model = ClientEdmModel.GetModel(base.RequestInfo.MaxProtocolVersion);
            ClientTypeAnnotation clientTypeAnnotation = model.GetClientTypeAnnotation(model.GetOrCreateEdmType(entityDescriptor.Entity.GetType()));

            if (!clientTypeAnnotation.IsMediaLinkEntry && !entityDescriptor.IsMediaLinkEntry)
            {
                return(null);
            }
            if ((clientTypeAnnotation.MediaDataMember == null) && (entityDescriptor.SaveStream == null))
            {
                throw System.Data.Services.Client.Error.InvalidOperation(System.Data.Services.Client.Strings.Context_MLEWithoutSaveStream(clientTypeAnnotation.ElementTypeName));
            }
            ODataRequestMessageWrapper mediaResourceRequest = null;

            if (clientTypeAnnotation.MediaDataMember != null)
            {
                string contentType = null;
                int    length      = 0;
                if (clientTypeAnnotation.MediaDataMember.MimeTypeProperty == null)
                {
                    contentType = "application/octet-stream";
                }
                else
                {
                    object obj2 = clientTypeAnnotation.MediaDataMember.MimeTypeProperty.GetValue(entityDescriptor.Entity);
                    string str2 = (obj2 != null) ? obj2.ToString() : null;
                    if (string.IsNullOrEmpty(str2))
                    {
                        throw System.Data.Services.Client.Error.InvalidOperation(System.Data.Services.Client.Strings.Context_NoContentTypeForMediaLink(clientTypeAnnotation.ElementTypeName, clientTypeAnnotation.MediaDataMember.MimeTypeProperty.PropertyName));
                    }
                    contentType = str2;
                }
                object propertyValue = clientTypeAnnotation.MediaDataMember.GetValue(entityDescriptor.Entity);
                if (propertyValue == null)
                {
                    base.mediaResourceRequestStream = null;
                }
                else
                {
                    byte[] bytes = propertyValue as byte[];
                    if (bytes == null)
                    {
                        string   str3;
                        Encoding encoding;
                        HttpProcessUtility.ReadContentType(contentType, out str3, out encoding);
                        if (encoding == null)
                        {
                            encoding    = Encoding.UTF8;
                            contentType = contentType + ";charset=UTF-8";
                        }
                        bytes = encoding.GetBytes(ClientConvert.ToString(propertyValue));
                    }
                    length = bytes.Length;
                    base.mediaResourceRequestStream = new MemoryStream(bytes, 0, bytes.Length, false, true);
                }
                mediaResourceRequest = this.CreateMediaResourceRequest(entityDescriptor.GetResourceUri(base.RequestInfo.BaseUriResolver, false), "POST", Util.DataServiceVersion1, clientTypeAnnotation.MediaDataMember == null, true);
                mediaResourceRequest.SetHeader("Content-Length", length.ToString(CultureInfo.InvariantCulture));
                mediaResourceRequest.SetHeader("Content-Type", contentType);
                mediaResourceRequest.AddHeadersToReset("Content-Length");
                mediaResourceRequest.AddHeadersToReset("Content-Type");
            }
            else
            {
                mediaResourceRequest = this.CreateMediaResourceRequest(entityDescriptor.GetResourceUri(base.RequestInfo.BaseUriResolver, false), "POST", Util.DataServiceVersion1, clientTypeAnnotation.MediaDataMember == null, true);
                this.SetupMediaResourceRequest(mediaResourceRequest, entityDescriptor.SaveStream, null);
            }
            entityDescriptor.State = EntityStates.Modified;
            return(mediaResourceRequest);
        }
示例#3
0
 /// <summary>constructor</summary>
 /// <param name="entity">entity</param>
 /// <param name="propertyName">name of collection or reference property to load</param>
 /// <param name="context">Originating context</param>
 /// <param name="request">Originating WebRequest</param>
 /// <param name="callback">user callback</param>
 /// <param name="state">user state</param>
 /// <param name="dataServiceRequest">request object.</param>
 /// <param name="plan">Projection plan for materialization; possibly null.</param>
 /// <param name="isContinuation">Whether this request is a continuation request.</param>
 internal LoadPropertyResult(object entity, string propertyName, DataServiceContext context, ODataRequestMessageWrapper request, AsyncCallback callback, object state, DataServiceRequest dataServiceRequest, ProjectionPlan plan, bool isContinuation)
     : base(context, Util.LoadPropertyMethodName, dataServiceRequest, request, new RequestInfo(context, isContinuation), callback, state)
 {
     this.entity       = entity;
     this.propertyName = propertyName;
     this.plan         = plan;
 }
示例#4
0
 internal void WriteEntry(EntityDescriptor entityDescriptor, IEnumerable<LinkDescriptor> relatedLinks, ODataRequestMessageWrapper requestMessage)
 {
     ClientEdmModel model = ClientEdmModel.GetModel(this.requestInfo.MaxProtocolVersion);
     ClientTypeAnnotation clientTypeAnnotation = model.GetClientTypeAnnotation(model.GetOrCreateEdmType(entityDescriptor.Entity.GetType()));
     using (ODataMessageWriter writer = CreateMessageWriter(requestMessage, this.requestInfo))
     {
         ODataWriter odataWriter = writer.CreateODataEntryWriter();
         ODataEntry entry = new ODataEntry();
         if (this.requestInfo.HasWritingEventHandlers)
         {
             entry.SetAnnotation<WritingEntityInfo>(new WritingEntityInfo(entityDescriptor.Entity, this.requestInfo));
         }
         string serverTypeName = this.requestInfo.GetServerTypeName(entityDescriptor);
         if (clientTypeAnnotation.ElementTypeName != serverTypeName)
         {
             SerializationTypeNameAnnotation annotation = new SerializationTypeNameAnnotation {
                 TypeName = serverTypeName
             };
             entry.SetAnnotation<SerializationTypeNameAnnotation>(annotation);
         }
         entry.TypeName = clientTypeAnnotation.ElementTypeName;
         if (EntityStates.Modified == entityDescriptor.State)
         {
             entry.Id = entityDescriptor.GetLatestIdentity();
         }
         if (entityDescriptor.IsMediaLinkEntry || clientTypeAnnotation.IsMediaLinkEntry)
         {
             entry.MediaResource = new ODataStreamReferenceValue();
         }
         odataWriter.WriteStart(entry);
         if (EntityStates.Added == entityDescriptor.State)
         {
             this.WriteNavigationLink(entityDescriptor, relatedLinks, odataWriter);
         }
         entry.Properties = this.PopulateProperties(clientTypeAnnotation, entityDescriptor.Entity, null);
         odataWriter.WriteEnd();
     }
 }
示例#5
0
        internal void WriteBodyOperationParameters(List<BodyOperationParameter> operationParameters, ODataRequestMessageWrapper requestMessage)
        {
            using (ODataMessageWriter writer = CreateMessageWriter(requestMessage, this.requestInfo))
            {
                ODataParameterWriter writer2 = writer.CreateODataParameterWriter(null);
                writer2.WriteStart();
                foreach (OperationParameter parameter in operationParameters)
                {
                    IEnumerator enumerator;
                    ODataCollectionWriter writer3;
                    object obj2;
                    if (parameter.Value == null)
                    {
                        writer2.WriteValue(parameter.Name, parameter.Value);
                        continue;
                    }
                    ClientEdmModel model = ClientEdmModel.GetModel(this.requestInfo.MaxProtocolVersion);
                    IEdmType orCreateEdmType = model.GetOrCreateEdmType(parameter.Value.GetType());
                    switch (orCreateEdmType.TypeKind)
                    {
                        case EdmTypeKind.Primitive:
                        {
                            writer2.WriteValue(parameter.Name, parameter.Value);
                            continue;
                        }
                        case EdmTypeKind.Complex:
                        {
                            ODataComplexValue parameterValue = this.CreateODataComplexValue(model.GetClientTypeAnnotation(orCreateEdmType).ElementType, parameter.Value, null, false, null);
                            writer2.WriteValue(parameter.Name, parameterValue);
                            continue;
                        }
                        case EdmTypeKind.Collection:
                        {
                            enumerator = ((ICollection) parameter.Value).GetEnumerator();
                            writer3 = writer2.CreateCollectionWriter(parameter.Name);
                            ODataCollectionStart collectionStart = new ODataCollectionStart();
                            writer3.WriteStart(collectionStart);
                            goto Label_016D;
                        }
                        default:
                            throw new NotSupportedException(System.Data.Services.Client.Strings.Serializer_InvalidParameterType(parameter.Name, orCreateEdmType.TypeKind));
                    }
                Label_00D3:
                    obj2 = enumerator.Current;
                    if (obj2 == null)
                    {
                        throw new NotSupportedException(System.Data.Services.Client.Strings.Serializer_NullCollectionParamterItemValue(parameter.Name));
                    }
                    IEdmType edmType = model.GetOrCreateEdmType(obj2.GetType());
                    switch (edmType.TypeKind)
                    {
                        case EdmTypeKind.Primitive:
                            writer3.WriteItem(obj2);
                            break;

                        case EdmTypeKind.Complex:
                        {
                            ODataComplexValue item = this.CreateODataComplexValue(model.GetClientTypeAnnotation(edmType).ElementType, obj2, null, false, null);
                            writer3.WriteItem(item);
                            break;
                        }
                        default:
                            throw new NotSupportedException(System.Data.Services.Client.Strings.Serializer_InvalidCollectionParamterItemType(parameter.Name, edmType.TypeKind));
                    }
                Label_016D:
                    if (enumerator.MoveNext())
                    {
                        goto Label_00D3;
                    }
                    writer3.WriteEnd();
                    writer3.Flush();
                }
                writer2.WriteEnd();
                writer2.Flush();
            }
        }
示例#6
0
        private ODataRequestMessageWrapper GenerateBatchRequest()
        {
            if ((base.ChangedEntries.Count == 0) && (this.Queries == null))
            {
                base.SetCompleted();
                return(null);
            }
            ODataRequestMessageWrapper requestMessage = this.CreateBatchRequest();

            using (ODataMessageWriter writer = Serializer.CreateMessageWriter(requestMessage, base.RequestInfo))
            {
                ODataUtils.SetHeadersForPayload(writer, ODataPayloadKind.Batch);
                requestMessage.FireSendingRequest2(null);
                this.batchWriter = writer.CreateODataBatchWriter();
                this.batchWriter.WriteStartBatch();
                if (this.Queries != null)
                {
                    for (int i = 0; i < this.Queries.Length; i++)
                    {
                        Uri requestUri = base.RequestInfo.BaseUriResolver.CreateAbsoluteUriIfNeeded(this.Queries[i].QueryComponents(base.RequestInfo.MaxProtocolVersion).Uri);
                        ODataRequestMessageWrapper wrapper2 = this.CreateRequestMessage(requestUri, "GET");
                        Version requestVersion = this.Queries[i].QueryComponents(base.RequestInfo.MaxProtocolVersion).Version;
                        WebUtil.SetOperationVersionHeaders(wrapper2, requestVersion, base.RequestInfo.MaxProtocolVersionAsVersion);
                        wrapper2.FireSendingRequest2(null);
                    }
                }
                else if (0 < base.ChangedEntries.Count)
                {
                    this.batchWriter.WriteStartChangeset();
                    ClientEdmModel model = ClientEdmModel.GetModel(base.RequestInfo.MaxProtocolVersion);
                    for (int j = 0; j < base.ChangedEntries.Count; j++)
                    {
                        Descriptor descriptor = base.ChangedEntries[j];
                        if (!descriptor.ContentGeneratedForSave)
                        {
                            ODataRequestMessageWrapper wrapper3;
                            EntityDescriptor           entityDescriptor = descriptor as EntityDescriptor;
                            if (descriptor.DescriptorKind == DescriptorKind.Entity)
                            {
                                if (entityDescriptor.State != EntityStates.Added)
                                {
                                    if (((entityDescriptor.State == EntityStates.Unchanged) || (entityDescriptor.State == EntityStates.Modified)) && (entityDescriptor.SaveStream != null))
                                    {
                                        throw System.Data.Services.Client.Error.NotSupported(System.Data.Services.Client.Strings.Context_BatchNotSupportedForMediaLink);
                                    }
                                }
                                else if (model.GetClientTypeAnnotation(model.GetOrCreateEdmType(entityDescriptor.Entity.GetType())).IsMediaLinkEntry || entityDescriptor.IsMediaLinkEntry)
                                {
                                    throw System.Data.Services.Client.Error.NotSupported(System.Data.Services.Client.Strings.Context_BatchNotSupportedForMediaLink);
                                }
                            }
                            else if (descriptor.DescriptorKind == DescriptorKind.NamedStream)
                            {
                                throw System.Data.Services.Client.Error.NotSupported(System.Data.Services.Client.Strings.Context_BatchNotSupportedForNamedStreams);
                            }
                            if (descriptor.DescriptorKind == DescriptorKind.Entity)
                            {
                                wrapper3 = base.CreateRequest(entityDescriptor);
                            }
                            else
                            {
                                wrapper3 = base.CreateRequest((LinkDescriptor)descriptor);
                            }
                            wrapper3.FireSendingRequest2(descriptor);
                            base.CreateChangeData(j, wrapper3);
                        }
                    }
                    this.batchWriter.WriteEndChangeset();
                }
                this.batchWriter.WriteEndBatch();
                this.batchWriter.Flush();
            }
            return(requestMessage);
        }
示例#7
0
 private void CreateRequestData(LinkDescriptor binding, ODataRequestMessageWrapper requestMessage)
 {
     this.SerializerInstance.WriteEntityReferenceLink(binding, requestMessage);
 }
示例#8
0
 protected bool CreateChangeData(int index, ODataRequestMessageWrapper requestMessage)
 {
     Descriptor descriptor = this.ChangedEntries[index];
     if (descriptor.DescriptorKind == DescriptorKind.Entity)
     {
         EntityDescriptor entityDescriptor = (EntityDescriptor) descriptor;
         descriptor.ContentGeneratedForSave = true;
         return this.CreateRequestData(entityDescriptor, requestMessage);
     }
     descriptor.ContentGeneratedForSave = true;
     LinkDescriptor binding = (LinkDescriptor) descriptor;
     if ((EntityStates.Added != binding.State) && ((EntityStates.Modified != binding.State) || (binding.Target == null)))
     {
         return false;
     }
     this.CreateRequestData(binding, requestMessage);
     return true;
 }
示例#9
0
 /// <summary>constructor</summary>
 /// <param name="source">source object of async request</param>
 /// <param name="method">async method name on source object</param>
 /// <param name="serviceRequest">Originating serviceRequest</param>
 /// <param name="request">Originating WebRequest</param>
 /// <param name="requestInfo">The request info of the originating request.</param>
 /// <param name="callback">user callback</param>
 /// <param name="state">user state</param>
 internal QueryResult(object source, string method, DataServiceRequest serviceRequest, ODataRequestMessageWrapper request, RequestInfo requestInfo, AsyncCallback callback, object state)
     : base(source, method, callback, state)
 {
     Debug.Assert(null != request, "null request");
     this.ServiceRequest = serviceRequest;
     this.Request = request;
     this.RequestInfo = requestInfo;
     this.Abortable = request;
 }
示例#10
0
        protected override void AsyncEndGetResponse(IAsyncResult asyncResult)
        {
            Debug.Assert(asyncResult != null && asyncResult.IsCompleted, "asyncResult.IsCompleted");
            AsyncStateBag asyncStateBag = asyncResult.AsyncState as AsyncStateBag;

            PerRequest pereq = asyncStateBag == null ? null : asyncStateBag.PerRequest;

            try
            {
                if (this.IsAborted)
                {
                    if (pereq != null)
                    {
                        pereq.SetComplete();
                    }

                    this.SetCompleted();
                }
                else
                {
                    this.CompleteCheck(pereq, InternalError.InvalidEndGetResponseCompleted);
                    pereq.SetRequestCompletedSynchronously(asyncResult.CompletedSynchronously);
                    this.SetCompletedSynchronously(asyncResult.CompletedSynchronously);

                    ODataRequestMessageWrapper requestMessage = Util.NullCheck(pereq.Request, InternalError.InvalidEndGetResponseRequest);

                    // the httpWebResponse is kept for batching, discarded by non-batch
                    IODataResponseMessage response = this.RequestInfo.EndGetResponse(requestMessage, asyncResult);
                    pereq.ResponseMessage = Util.NullCheck(response, InternalError.InvalidEndGetResponseResponse);

                    this.SetHttpWebResponse(pereq.ResponseMessage);

                    Debug.Assert(null == pereq.ResponseStream, "non-null async ResponseStream");
                    Stream httpResponseStream = null;

                    if (HttpStatusCode.NoContent != (HttpStatusCode)response.StatusCode)
                    {
                        httpResponseStream = response.GetStream();
                        pereq.ResponseStream = httpResponseStream;
                    }

                    if ((null != httpResponseStream) && httpResponseStream.CanRead)
                    {
                        if (null == this.outputResponseStream)
                        {
                            // this is the stream we copy the reponse to
                            this.outputResponseStream = Util.NullCheck(this.GetAsyncResponseStreamCopy(), InternalError.InvalidAsyncResponseStreamCopy);
                        }

                        if (null == this.asyncStreamCopyBuffer)
                        {
                            // this is the buffer we read into and copy out of
                            this.asyncStreamCopyBuffer = Util.NullCheck(this.GetAsyncResponseStreamCopyBuffer(), InternalError.InvalidAsyncResponseStreamCopyBuffer);
                        }

                        // Make async calls to read the response stream
                        this.ReadResponseStream(asyncStateBag);
                    }
                    else
                    {
                        pereq.SetComplete();
                        this.SetCompleted();
                    }
                }
            }
            catch (Exception e)
            {
                if (this.HandleFailure(e))
                {
                    throw;
                }
            }
            finally
            {
                this.HandleCompleted(pereq);
            }
        }
示例#11
0
 /// <summary>constructor</summary>
 /// <param name="source">source object of async request</param>
 /// <param name="method">async method name on source object</param>
 /// <param name="serviceRequest">Originating serviceRequest</param>
 /// <param name="request">Originating WebRequest</param>
 /// <param name="requestInfo">The request info of the originating request.</param>
 /// <param name="callback">user callback</param>
 /// <param name="state">user state</param>
 /// <param name="requestContentStream">the stream containing the request data.</param>
 internal QueryResult(object source, string method, DataServiceRequest serviceRequest, ODataRequestMessageWrapper request, RequestInfo requestInfo, AsyncCallback callback, object state, ContentStream requestContentStream)
     : this(source, method, serviceRequest, request, requestInfo, callback, state)
 {
     Debug.Assert(null != requestContentStream, "null requestContentStream");
     this.requestContentStream = requestContentStream;
 }
示例#12
0
 private void CreateRequestData(LinkDescriptor binding, ODataRequestMessageWrapper requestMessage)
 {
     this.SerializerInstance.WriteEntityReferenceLink(binding, requestMessage);
 }
示例#13
0
 private bool CreateRequestData(EntityDescriptor entityDescriptor, ODataRequestMessageWrapper requestMessage)
 {
     bool flag = false;
     EntityStates state = entityDescriptor.State;
     if (state != EntityStates.Added)
     {
         if (state == EntityStates.Deleted)
         {
             goto Label_0020;
         }
         if (state != EntityStates.Modified)
         {
             System.Data.Services.Client.Error.ThrowInternalError(InternalError.UnvalidatedEntityState);
             goto Label_0020;
         }
     }
     flag = true;
 Label_0020:
     if (flag)
     {
         this.SerializerInstance.WriteEntry(entityDescriptor, this.RelatedLinks(entityDescriptor), requestMessage);
     }
     return flag;
 }
示例#14
0
        private ODataRequestMessageWrapper CreateNextRequest()
        {
            bool flag = base.streamRequestKind == BaseSaveResult.StreamRequestKind.None;

            if (base.entryIndex < base.ChangedEntries.Count)
            {
                Descriptor descriptor = base.ChangedEntries[base.entryIndex];
                if (descriptor.DescriptorKind == DescriptorKind.Entity)
                {
                    EntityDescriptor descriptor2 = (EntityDescriptor)descriptor;
                    descriptor2.CloseSaveStream();
                    if ((base.streamRequestKind == BaseSaveResult.StreamRequestKind.PutMediaResource) && (EntityStates.Unchanged == descriptor2.State))
                    {
                        descriptor2.ContentGeneratedForSave = true;
                        flag = true;
                    }
                }
                else if (descriptor.DescriptorKind == DescriptorKind.NamedStream)
                {
                    ((StreamDescriptor)descriptor).CloseSaveStream();
                }
            }
            if (flag)
            {
                base.entryIndex++;
            }
            ODataRequestMessageWrapper wrapper = null;

            if (base.entryIndex < base.ChangedEntries.Count)
            {
                Descriptor descriptor3 = base.ChangedEntries[base.entryIndex];
                if (descriptor3.DescriptorKind == DescriptorKind.Entity)
                {
                    EntityDescriptor entityDescriptor = (EntityDescriptor)descriptor3;
                    if (((EntityStates.Unchanged == descriptor3.State) || (EntityStates.Modified == descriptor3.State)) && ((wrapper = this.CheckAndProcessMediaEntryPut(entityDescriptor)) != null))
                    {
                        base.streamRequestKind = BaseSaveResult.StreamRequestKind.PutMediaResource;
                    }
                    else if ((EntityStates.Added == descriptor3.State) && ((wrapper = this.CheckAndProcessMediaEntryPost(entityDescriptor)) != null))
                    {
                        base.streamRequestKind       = BaseSaveResult.StreamRequestKind.PostMediaResource;
                        entityDescriptor.StreamState = EntityStates.Added;
                    }
                    else
                    {
                        base.streamRequestKind = BaseSaveResult.StreamRequestKind.None;
                        wrapper = base.CreateRequest(entityDescriptor);
                    }
                }
                else if (descriptor3.DescriptorKind == DescriptorKind.NamedStream)
                {
                    wrapper = this.CreateNamedStreamRequest((StreamDescriptor)descriptor3);
                }
                else
                {
                    wrapper = base.CreateRequest((LinkDescriptor)descriptor3);
                }
                if (wrapper != null)
                {
                    wrapper.FireSendingRequest2(descriptor3);
                }
            }
            return(wrapper);
        }
示例#15
0
 internal QueryResult(object source, string method, DataServiceRequest serviceRequest, ODataRequestMessageWrapper request, System.Data.Services.Client.RequestInfo requestInfo, AsyncCallback callback, object state) : base(source, method, callback, state)
 {
     this.ServiceRequest = serviceRequest;
     this.Request        = request;
     this.RequestInfo    = requestInfo;
     base.Abortable      = request;
 }
示例#16
0
        internal static Stream GetRequestStream(ODataRequestMessageWrapper request, DataServiceContext context)
        {
            Stream requestStream = request.GetRequestStream();

            return(context.InternalGetRequestWrappingStream(requestStream));
        }
示例#17
0
 internal QueryResult(object source, string method, DataServiceRequest serviceRequest, ODataRequestMessageWrapper request, System.Data.Services.Client.RequestInfo requestInfo, AsyncCallback callback, object state, BaseAsyncResult.ContentStream requestContentStream) : this(source, method, serviceRequest, request, requestInfo, callback, state)
 {
     this.requestContentStream = requestContentStream;
 }
示例#18
0
 internal LoadPropertyResult(object entity, string propertyName, DataServiceContext context, ODataRequestMessageWrapper request, AsyncCallback callback, object state, DataServiceRequest dataServiceRequest, ProjectionPlan plan) : base(context, "LoadProperty", dataServiceRequest, request, new RequestInfo(context), callback, state)
 {
     this.entity = entity;
     this.propertyName = propertyName;
     this.plan = plan;
 }
示例#19
0
 /// <summary>
 /// This method wraps the HttpWebRequest.GetSyncronousResponse method call. The reasons for doing this are to give us a place
 /// to invoke internal test hook callbacks that can validate the response headers, and also so that we can do
 /// debug validation to make sure that the headers have not changed since they were originally configured on the request.
 /// </summary>
 /// <param name="request">ODataRequestMessageWrapper instance</param>
 /// <param name="handleWebException">If set to true, this method will only re-throw the WebException that was caught if
 /// the response in the exception is null. If set to false, this method will always re-throw in case of a WebException.</param>
 /// <returns>
 /// Returns the HttpWebResponse from the wrapped GetSyncronousResponse method.
 /// </returns>
 internal IODataResponseMessage GetSyncronousResponse(ODataRequestMessageWrapper request, bool handleWebException)
 {
     return(this.Context.GetSyncronousResponse(request, handleWebException));
 }
示例#20
0
 protected override ODataRequestMessageWrapper CreateRequestMessage(Uri requestUri, string method)
 {
     return(ODataRequestMessageWrapper.CreateBatchPartRequestMessage(this.batchWriter, method, requestUri, base.RequestInfo));
 }
示例#21
0
 /// <summary>
 /// This method wraps the HttpWebRequest.EndGetResponse method call. The reason for doing this is to give us a place
 /// to invoke internal test hook callbacks that can validate the response headers.
 /// </summary>
 /// <param name="request">HttpWebRequest instance</param>
 /// <param name="asyncResult">Async result obtained from previous call to BeginGetResponse.</param>
 /// <returns>Returns the HttpWebResponse from the wrapped EndGetResponse method.</returns>
 internal IODataResponseMessage EndGetResponse(ODataRequestMessageWrapper request, IAsyncResult asyncResult)
 {
     return(this.Context.EndGetResponse(request, asyncResult));
 }
示例#22
0
 private ODataRequestMessageWrapper CreateBatchRequest()
 {
     Uri requestUrl = Util.CreateUri(base.RequestInfo.BaseUriResolver.GetBaseUriWithSlash(), Util.CreateUri("$batch", UriKind.Relative));
     ODataRequestMessageWrapper requestMessage = new ODataRequestMessageWrapper("POST", requestUrl, base.RequestInfo);
     WebUtil.SetOperationVersionHeaders(requestMessage, Util.DataServiceVersion1, base.RequestInfo.MaxProtocolVersionAsVersion);
     return requestMessage;
 }
示例#23
0
 internal static IAsyncResult InvokeAsync(Func <ODataRequestMessageWrapper, AsyncCallback, object, IAsyncResult> asyncAction, ODataRequestMessageWrapper request, AsyncCallback callback, object state)
 {
     return(PostInvokeAsync(asyncAction(request, GetDataServiceAsyncCallback(callback), state), callback));
 }
示例#24
0
 internal void WriteEntityReferenceLink(LinkDescriptor binding, ODataRequestMessageWrapper requestMessage)
 {
     using (ODataMessageWriter writer = CreateMessageWriter(requestMessage, this.requestInfo))
     {
         Uri resourceUri;
         EntityDescriptor entityDescriptor = this.requestInfo.EntityTracker.GetEntityDescriptor(binding.Target);
         if (entityDescriptor.GetLatestIdentity() != null)
         {
             resourceUri = entityDescriptor.GetResourceUri(this.requestInfo.BaseUriResolver, false);
         }
         else
         {
             resourceUri = Util.CreateUri("$" + entityDescriptor.ChangeOrder.ToString(CultureInfo.InvariantCulture), UriKind.Relative);
         }
         ODataEntityReferenceLink link = new ODataEntityReferenceLink {
             Url = resourceUri
         };
         writer.WriteEntityReferenceLink(link);
     }
 }
示例#25
0
        /// <summary>
        /// Writes the body operation parameters associated with a ServiceAction.
        /// </summary>
        /// <param name="operationParameters">The list of operation parameters to write.</param>
        /// <param name="requestMessage">The OData request message used to write the operation parameters.</param>
        internal void WriteBodyOperationParameters(List <BodyOperationParameter> operationParameters, ODataRequestMessageWrapper requestMessage)
        {
            Debug.Assert(requestMessage != null, "requestMessage != null");
            Debug.Assert(operationParameters != null, "operationParameters != null");
            Debug.Assert(operationParameters.Any(), "operationParameters.Any()");

            using (ODataMessageWriter messageWriter = Serializer.CreateMessageWriter(requestMessage, this.requestInfo, true /*isParameterPayload*/))
            {
                ODataParameterWriter parameterWriter = messageWriter.CreateODataParameterWriter(null);
                parameterWriter.WriteStart();

                foreach (OperationParameter operationParameter in operationParameters)
                {
                    if (operationParameter.Value == null)
                    {
                        parameterWriter.WriteValue(operationParameter.Name, operationParameter.Value);
                    }
                    else
                    {
                        ClientEdmModel model   = this.requestInfo.Model;
                        IEdmType       edmType = model.GetOrCreateEdmType(operationParameter.Value.GetType());
                        Debug.Assert(edmType != null, "edmType != null");

                        switch (edmType.TypeKind)
                        {
                        case EdmTypeKind.Collection:
                        {
                            Collections.IEnumerator enumerator           = ((ICollection)operationParameter.Value).GetEnumerator();
                            ODataCollectionWriter   collectionWriter     = parameterWriter.CreateCollectionWriter(operationParameter.Name);
                            ODataCollectionStart    odataCollectionStart = new ODataCollectionStart();
                            collectionWriter.WriteStart(odataCollectionStart);

                            while (enumerator.MoveNext())
                            {
                                Object collectionItem = enumerator.Current;
                                if (collectionItem == null)
                                {
                                    throw new NotSupportedException(Strings.Serializer_NullCollectionParamterItemValue(operationParameter.Name));
                                }

                                IEdmType edmItemType = model.GetOrCreateEdmType(collectionItem.GetType());
                                Debug.Assert(edmItemType != null, "edmItemType != null");

                                switch (edmItemType.TypeKind)
                                {
                                case EdmTypeKind.Complex:
                                {
                                    Debug.Assert(model.GetClientTypeAnnotation(edmItemType).ElementType != null, "edmItemType.GetClientTypeAnnotation().ElementType != null");
                                    ODataComplexValue complexValue = this.propertyConverter.CreateODataComplexValue(
                                        model.GetClientTypeAnnotation(edmItemType).ElementType,
                                        collectionItem,
                                        null /*propertyName*/,
                                        false /*isCollectionItem*/,
                                        null /*visitedComplexTypeObjects*/);

                                    Debug.Assert(complexValue != null, "complexValue != null");
                                    collectionWriter.WriteItem(complexValue);
                                    break;
                                }

                                case EdmTypeKind.Primitive:
                                {
                                    collectionWriter.WriteItem(collectionItem);
                                    break;
                                }

                                default:

                                    // EdmTypeKind.Entity
                                    // EdmTypeKind.Row
                                    // EdmTypeKind.EntityReference
                                    // EdmTypeKind.Enum.
                                    throw new NotSupportedException(Strings.Serializer_InvalidCollectionParamterItemType(operationParameter.Name, edmItemType.TypeKind));
                                }
                            }

                            collectionWriter.WriteEnd();
                            collectionWriter.Flush();
                            break;
                        }

                        case EdmTypeKind.Complex:
                        {
                            Debug.Assert(model.GetClientTypeAnnotation(edmType).ElementType != null, "model.GetClientTypeAnnotation(edmType).ElementType != null");
                            ODataComplexValue complexValue = this.propertyConverter.CreateODataComplexValue(
                                model.GetClientTypeAnnotation(edmType).ElementType,
                                operationParameter.Value,
                                null /*propertyName*/,
                                false /*isCollectionItemType*/,
                                null /*visitedComplexTypeObjects*/);

                            Debug.Assert(complexValue != null, "complexValue != null");
                            parameterWriter.WriteValue(operationParameter.Name, complexValue);
                            break;
                        }

                        case EdmTypeKind.Primitive:
                            parameterWriter.WriteValue(operationParameter.Name, operationParameter.Value);
                            break;

                        default:
                            // EdmTypeKind.Entity
                            // EdmTypeKind.Row
                            // EdmTypeKind.EntityReference
                            // EdmTypeKind.Enum.
                            throw new NotSupportedException(Strings.Serializer_InvalidParameterType(operationParameter.Name, edmType.TypeKind));
                        }
                    } // else
                }     // foreach

                parameterWriter.WriteEnd();
                parameterWriter.Flush();
            }
        }
示例#26
0
 internal static ODataMessageWriter CreateMessageWriter(ODataRequestMessageWrapper requestMessage, RequestInfo requestInfo)
 {
     ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings {
         CheckCharacters = false,
         Indent = false,
         DisableMessageStreamDisposal = !requestMessage.IsBatchPartRequest
     };
     if (requestInfo.HasWritingEventHandlers)
     {
         writerSettings.EnableWcfDataServicesClientBehavior(new Func<ODataEntry, XmlWriter, XmlWriter>(Serializer.StartEntryXmlCustomizer), new Action<ODataEntry, XmlWriter, XmlWriter>(Serializer.EndEntryXmlCustomizer), requestInfo.DataNamespace, requestInfo.TypeScheme.AbsoluteUri);
     }
     else
     {
         writerSettings.EnableWcfDataServicesClientBehavior(null, null, requestInfo.DataNamespace, requestInfo.TypeScheme.AbsoluteUri);
     }
     return requestMessage.CreateWriter(writerSettings);
 }
示例#27
0
        /// <summary>
        /// Write the entry element.
        /// </summary>
        /// <param name="entityDescriptor">The entity.</param>
        /// <param name="relatedLinks">Collection of links related to the entity.</param>
        /// <param name="requestMessage">The OData request message.</param>
        internal void WriteEntry(EntityDescriptor entityDescriptor, IEnumerable <LinkDescriptor> relatedLinks, ODataRequestMessageWrapper requestMessage)
        {
            ClientEdmModel       model      = this.requestInfo.Model;
            ClientTypeAnnotation entityType = model.GetClientTypeAnnotation(model.GetOrCreateEdmType(entityDescriptor.Entity.GetType()));

            using (ODataMessageWriter messageWriter = Serializer.CreateMessageWriter(requestMessage, this.requestInfo, false /*isParameterPayload*/))
            {
                ODataWriterWrapper entryWriter = ODataWriterWrapper.CreateForEntry(messageWriter, this.requestInfo.Configurations.RequestPipeline);

                // Get the server type name using the type resolver or from the entity descriptor
                string serverTypeName = this.requestInfo.GetServerTypeName(entityDescriptor);

                var entry = CreateODataEntry(entityDescriptor, serverTypeName, entityType, this.requestInfo.Format);

                // Add the annotation required for writing the payload into an XElement
                // for firing WritingEntity events
                if (this.requestInfo.HasWritingEventHandlers)
                {
                    entry.SetAnnotation(new WritingEntityInfo(entityDescriptor.Entity, this.requestInfo));
                }

                if (serverTypeName == null)
                {
                    serverTypeName = this.requestInfo.InferServerTypeNameFromServerModel(entityDescriptor);
                }

                entry.Properties = this.propertyConverter.PopulateProperties(entityDescriptor.Entity, serverTypeName, entityType.PropertiesToSerialize());

                entryWriter.WriteStart(entry, entityDescriptor.Entity);

                if (EntityStates.Added == entityDescriptor.State)
                {
                    this.WriteNavigationLink(entityDescriptor, relatedLinks, entryWriter);
                }

                entryWriter.WriteEnd(entry, entityDescriptor.Entity);
            }
        }
示例#28
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);
            }
        }
示例#29
0
 /// <summary>
 /// Writes an entity reference link.
 /// </summary>
 /// <param name="binding">The link descriptor.</param>
 /// <param name="requestMessage">The request message used for writing the payload.</param>
 /// <param name="isBatch">True if batch, false otherwise.</param>
 internal void WriteEntityReferenceLink(LinkDescriptor binding, ODataRequestMessageWrapper requestMessage, bool isBatch)
示例#30
0
        internal void BeginCreateNextChange()
        {
            HttpWebResponse response;

            this.inMemoryResponseStream = new MemoryStream();
            BaseAsyncResult.PerRequest pereq = null;
            IAsyncResult result = null;

Label_000F:
            response = null;
            ODataRequestMessageWrapper requestMessage = null;

            try
            {
                if (base.perRequest != null)
                {
                    base.SetCompleted();
                    System.Data.Services.Client.Error.ThrowInternalError(InternalError.InvalidBeginNextChange);
                }
                requestMessage = this.CreateNextRequest();
                if (requestMessage == null)
                {
                    base.Abortable = null;
                }
                if ((requestMessage != null) || (base.entryIndex < base.ChangedEntries.Count))
                {
                    if (base.ChangedEntries[base.entryIndex].ContentGeneratedForSave)
                    {
                        goto Label_0191;
                    }
                    base.Abortable = requestMessage;
                    BaseAsyncResult.ContentStream stream = this.CreateNonBatchChangeData(base.entryIndex, requestMessage);
                    base.perRequest = pereq = new BaseAsyncResult.PerRequest();
                    pereq.Request   = requestMessage;
                    BaseAsyncResult.AsyncStateBag state = new BaseAsyncResult.AsyncStateBag(pereq, (DataServiceContext)base.Source);
                    if ((stream == null) || (stream.Stream == null))
                    {
                        result = BaseAsyncResult.InvokeAsync(new Func <ODataRequestMessageWrapper, AsyncCallback, object, IAsyncResult>(WebUtil.BeginGetResponse), requestMessage, new AsyncCallback(this.AsyncEndGetResponse), state);
                    }
                    else
                    {
                        if (stream.IsKnownMemoryStream)
                        {
                            requestMessage.SetContentLengthHeader();
                        }
                        pereq.RequestContentStream = stream;
                        result = BaseAsyncResult.InvokeAsync(new Func <ODataRequestMessageWrapper, AsyncCallback, object, IAsyncResult>(WebUtil.BeginGetRequestStream), requestMessage, new AsyncCallback(this.AsyncEndGetRequestStream), state);
                    }
                    pereq.SetRequestCompletedSynchronously(result.CompletedSynchronously);
                    base.SetCompletedSynchronously(pereq.RequestCompletedSynchronously);
                }
                else
                {
                    base.SetCompleted();
                    if (base.CompletedSynchronously)
                    {
                        this.HandleCompleted(pereq);
                    }
                }
            }
            catch (InvalidOperationException exception)
            {
                WebUtil.GetHttpWebResponse(exception, ref response);
                this.HandleOperationException(exception, response);
                this.HandleCompleted(pereq);
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }
            if (((pereq != null) && pereq.RequestCompleted) && (pereq.RequestCompletedSynchronously && !base.IsCompletedInternally))
            {
                this.FinishCurrentChange(pereq);
            }
Label_0191:
            if (((pereq == null) || (pereq.RequestCompleted && pereq.RequestCompletedSynchronously)) && !base.IsCompletedInternally)
            {
                goto Label_000F;
            }
        }
示例#31
0
 protected BaseAsyncResult.ContentStream CreateNonBatchChangeData(int index, ODataRequestMessageWrapper requestMessage)
 {
     Descriptor descriptor = base.ChangedEntries[index];
     if ((descriptor.DescriptorKind == DescriptorKind.Entity) && (base.streamRequestKind != BaseSaveResult.StreamRequestKind.None))
     {
         if (base.streamRequestKind != BaseSaveResult.StreamRequestKind.None)
         {
             return new BaseAsyncResult.ContentStream(base.mediaResourceRequestStream, false);
         }
     }
     else
     {
         if (descriptor.DescriptorKind == DescriptorKind.NamedStream)
         {
             descriptor.ContentGeneratedForSave = true;
             return new BaseAsyncResult.ContentStream(base.mediaResourceRequestStream, false);
         }
         if (base.CreateChangeData(index, requestMessage))
         {
             return new BaseAsyncResult.ContentStream(requestMessage.CachedRequestStream, true);
         }
     }
     return null;
 }
示例#32
0
 internal GetReadStreamResult(DataServiceContext context, string method, ODataRequestMessageWrapper request, AsyncCallback callback, object state, StreamDescriptor streamDescriptor) : base(context, method, callback, state)
 {
     this.requestMessage   = request;
     base.Abortable        = request;
     this.streamDescriptor = streamDescriptor;
 }
示例#33
0
 private void SetupMediaResourceRequest(ODataRequestMessageWrapper mediaResourceRequest, DataServiceSaveStream saveStream, string etag)
 {
     IEnumerable<string> keys;
     base.mediaResourceRequestStream = saveStream.Stream;
     WebUtil.ApplyHeadersToRequest(saveStream.Args.Headers, mediaResourceRequest, true);
     Dictionary<string, string> headers = saveStream.Args.Headers;
     if (headers.ContainsKey("Accept"))
     {
         keys = new List<string>(headers.Count - 1);
         foreach (string str in headers.Keys)
         {
             if (str != "Accept")
             {
                 ((List<string>) keys).Add(str);
             }
         }
     }
     else
     {
         keys = headers.Keys;
     }
     mediaResourceRequest.AddHeadersToReset(keys);
     if (etag != null)
     {
         mediaResourceRequest.SetHeader("If-Match", etag);
         mediaResourceRequest.AddHeadersToReset("If-Match");
     }
 }
示例#34
0
 internal static HttpWebResponse GetResponse(ODataRequestMessageWrapper request, DataServiceContext context, bool handleWebException)
 {
     return(GetResponseHelper(request, context, null, handleWebException));
 }
示例#35
0
 internal GetReadStreamResult(DataServiceContext context, string method, ODataRequestMessageWrapper request, AsyncCallback callback, object state, StreamDescriptor streamDescriptor) : base(context, method, callback, state)
 {
     this.requestMessage = request;
     base.Abortable = request;
     this.streamDescriptor = streamDescriptor;
 }