예제 #1
0
 internal BatchSaveResult(DataServiceContext context, string method, DataServiceRequest[] queries, SaveChangesOptions options, AsyncCallback callback, object state) : base(context, method, queries, options, callback, state)
 {
     this.Queries          = queries;
     this.streamCopyBuffer = new byte[0xfa0];
 }
예제 #2
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;
 }
        /// <summary>
        /// Processes the result for successfull request and produces the actual result of the request.
        /// </summary>
        /// <typeparam name="TElement">Element type of the result.</typeparam>
        /// <param name="context">The data service context.</param>
        /// <param name="plan">The plan to use for the projection, if available in precompiled form.</param>
        /// <returns>A instance of QueryResponseResult created on top of of the request.</returns>
        internal QueryOperationResponse <TElement> ProcessResult <TElement>(DataServiceContext context, ProjectionPlan plan)
        {
            MaterializeAtom materializeAtom = DataServiceRequest.Materialize(context, this.ServiceRequest.QueryComponents, plan, this.ContentType, this.GetResponseStream());

            return(this.GetResponse <TElement>(materializeAtom));
        }
예제 #4
0
 private NonEntityProjectionAnalyzer(PathBox pb, Type type, DataServiceContext context)
 {
     this.box     = pb;
     this.type    = type;
     this.context = context;
 }
예제 #5
0
        private MaterializeAtom ReadPropertyFromAtom(EntityDescriptor box, ClientPropertyAnnotation property)
        {
            MaterializeAtom    atom2;
            DataServiceContext source = (DataServiceContext)base.Source;
            bool applyingChanges      = source.ApplyingChanges;

            try
            {
                source.ApplyingChanges = true;
                bool   flag2           = EntityStates.Deleted == box.State;
                bool   instanceCreated = false;
                object instance        = null;
                if (property.IsEntityCollection)
                {
                    instance = this.GetCollectionInstance(property, out instanceCreated);
                }
                Type  type    = property.IsEntityCollection ? property.EntityCollectionItemType : property.NullablePropertyType;
                IList results = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(new Type[] { type }));
                DataServiceQueryContinuation continuation = null;
                using (MaterializeAtom atom = base.GetMaterializer(this.plan))
                {
                    bool flag4 = property.EdmProperty.PropertyKind == EdmPropertyKind.Navigation;
                    int  num   = 0;
                    foreach (object obj3 in atom)
                    {
                        if (property.IsEntityCollection)
                        {
                            property.SetValue(instance, obj3, this.propertyName, true);
                            results.Add(obj3);
                        }
                        else if (property.IsPrimitiveOrComplexCollection)
                        {
                            object obj4 = property.GetValue(this.entity);
                            if (obj4 == null)
                            {
                                obj4 = Activator.CreateInstance(obj3.GetType());
                                property.SetValue(this.entity, obj4, this.propertyName, false);
                            }
                            else
                            {
                                property.ClearBackingICollectionInstance(obj4);
                            }
                            foreach (object obj5 in (IEnumerable)obj3)
                            {
                                property.AddValueToBackingICollectionInstance(obj4, obj5);
                            }
                            results.Add(obj4);
                        }
                        else
                        {
                            property.SetValue(this.entity, obj3, this.propertyName, false);
                            results.Add(obj3);
                        }
                        num++;
                        if (((obj3 != null) && (MergeOption.NoTracking != atom.MergeOptionValue)) && flag4)
                        {
                            if (flag2)
                            {
                                source.DeleteLink(this.entity, this.propertyName, obj3);
                            }
                            else
                            {
                                source.AttachLink(this.entity, this.propertyName, obj3, atom.MergeOptionValue);
                            }
                        }
                    }
                    continuation = atom.GetContinuation(null);
                    Util.SetNextLinkForCollection(property.IsEntityCollection ? instance : this.entity, continuation);
                }
                if (instanceCreated)
                {
                    property.SetValue(this.entity, instance, this.propertyName, false);
                }
                atom2 = MaterializeAtom.CreateWrapper(source, results, continuation);
            }
            finally
            {
                source.ApplyingChanges = applyingChanges;
            }
            return(atom2);
        }
예제 #6
0
 internal void ExecuteQuery(DataServiceContext context)
 {
     try
     {
         if ((this.requestContentStream != null) && (this.requestContentStream.Stream != null))
         {
             if (this.requestContentStream.IsKnownMemoryStream)
             {
                 this.Request.SetContentLengthHeader();
             }
             using (Stream stream = WebUtil.GetRequestStream(this.Request, context))
             {
                 int    num;
                 byte[] buffer = new byte[0x10000];
                 do
                 {
                     num = this.requestContentStream.Stream.Read(buffer, 0, buffer.Length);
                     if (num > 0)
                     {
                         stream.Write(buffer, 0, num);
                     }
                 }while (num > 0);
             }
         }
         HttpWebResponse response = null;
         response = WebUtil.GetResponse(this.Request, context, true);
         this.SetHttpWebResponse(Util.NullCheck <HttpWebResponse>(response, InternalError.InvalidGetResponse));
         if (HttpStatusCode.NoContent != this.StatusCode)
         {
             using (Stream stream2 = WebUtil.GetResponseStream(this.httpWebResponse, context))
             {
                 if (stream2 != null)
                 {
                     Stream asyncResponseStreamCopy = this.GetAsyncResponseStreamCopy();
                     this.outputResponseStream = asyncResponseStreamCopy;
                     byte[] asyncResponseStreamCopyBuffer = this.GetAsyncResponseStreamCopyBuffer();
                     long   num2 = WebUtil.CopyStream(stream2, asyncResponseStreamCopy, ref asyncResponseStreamCopyBuffer);
                     if (this.responseStreamOwner)
                     {
                         if (0L == num2)
                         {
                             this.outputResponseStream = null;
                         }
                         else if (asyncResponseStreamCopy.Position < asyncResponseStreamCopy.Length)
                         {
                             ((MemoryStream)asyncResponseStreamCopy).SetLength(asyncResponseStreamCopy.Position);
                         }
                     }
                     this.PutAsyncResponseStreamCopyBuffer(asyncResponseStreamCopyBuffer);
                 }
             }
         }
     }
     catch (Exception exception)
     {
         base.HandleFailure(exception);
         throw;
     }
     finally
     {
         base.SetCompleted();
         this.CompletedRequest();
     }
     if (base.Failure != null)
     {
         throw base.Failure;
     }
 }
예제 #7
0
        /// <summary>
        /// Analyzes a lambda expression to check whether it can be satisfied with
        /// $select and client-side materialization.
        /// </summary>
        /// <param name="le">Lambda expression.</param>
        /// <param name="re">Resource expression in scope.</param>
        /// <param name="matchMembers">Whether member accesses are matched as top-level projections.</param>
        /// <param name="context">Context of expression to analyze.</param>
        /// <returns>true if the lambda is a client-side projection; false otherwise.</returns>
        internal static bool Analyze(LambdaExpression le, ResourceExpression re, bool matchMembers, DataServiceContext context)
        {
            Debug.Assert(le != null, "le != null");

            if (le.Body.NodeType == ExpressionType.Constant)
            {
                if (ClientTypeUtil.TypeOrElementTypeIsEntity(le.Body.Type))
                {
                    throw new NotSupportedException(Strings.ALinq_CannotCreateConstantEntity);
                }

                re.Projection = new ProjectionQueryOptionExpression(le.Body.Type, le, new List <string>());
                return(true);
            }

            if (le.Body.NodeType == ExpressionType.MemberInit || le.Body.NodeType == ExpressionType.New)
            {
                AnalyzeResourceExpression(le, re, context);
                return(true);
            }

            if (matchMembers)
            {
                // Members can be projected standalone or type-casted.
                Expression withoutConverts = SkipConverts(le.Body);
                if (withoutConverts.NodeType == ExpressionType.MemberAccess)
                {
                    AnalyzeResourceExpression(le, re, context);
                    return(true);
                }
            }

            return(false);
        }
예제 #8
0
파일: UriHelper.cs 프로젝트: tapika/swupd
        /// <summary>
        /// Appends a type segment to the <see cref="StringBuilder"/> which is building up a URI from a query.
        /// </summary>
        /// <param name="stringBuilder">The string builder.</param>
        /// <param name="type">The type for the segment.</param>
        /// <param name="dataServiceContext">The data service context.</param>
        /// <param name="inPath">Whether or not the type segment is being appended within the path (as opposed to within a $filter or $orderby expression).</param>
        /// <param name="version">The current version.</param>
        internal static void AppendTypeSegment(StringBuilder stringBuilder, Type type, DataServiceContext dataServiceContext, bool inPath, ref Version version)
        {
            // The '$' segment is used to escape known metadata segments in the key-as-segments mode to avoid ambiguity.
            // Because keys are not allowed inside filter or orderby expressions, we do not need to add it in those cases.
            if (inPath && dataServiceContext.UrlConventions == DataServiceUrlConventions.KeyAsSegment)
            {
                stringBuilder.Append('$');
                stringBuilder.Append(FORWARDSLASH);
            }

            string typeName = GetEntityTypeNameForUriAndValidateMaxProtocolVersion(type, dataServiceContext, ref version);

            stringBuilder.Append(typeName);
        }
예제 #9
0
        /// <summary>
        /// Analyzes the specified <paramref name="lambda"/> for selection and updates
        /// <paramref name="resource"/>.
        /// </summary>
        /// <param name="lambda">Lambda expression to analyze.</param>
        /// <param name="resource">Resource expression to update.</param>
        /// <param name="context">Context of expression to analyze.</param>
        private static void AnalyzeResourceExpression(LambdaExpression lambda, ResourceExpression resource, DataServiceContext context)
        {
            PathBox pb = new PathBox();

            ProjectionAnalyzer.Analyze(lambda, pb, context);
            resource.Projection  = new ProjectionQueryOptionExpression(lambda.Body.Type, lambda, pb.ProjectionPaths.ToList());
            resource.ExpandPaths = pb.ExpandPaths.Union(resource.ExpandPaths, StringComparer.Ordinal).ToList();
            resource.RaiseUriVersion(pb.UriVersion);
        }
예제 #10
0
 internal AsyncStateBag(System.Data.Services.Client.BaseAsyncResult.PerRequest pereq, DataServiceContext context)
 {
     this.PerRequest = pereq;
     this.Context    = context;
 }
예제 #11
0
파일: UriHelper.cs 프로젝트: tapika/swupd
        /// <summary>Gets the type name to be used in the URI for the given <paramref name="type"/>.</summary>
        /// <param name="type">Type to get name for.</param>
        /// <param name="context">Data context used to generate type names for types.</param>
        /// <param name="uriVersion">Data service version for the uri</param>
        /// <returns>The name for the <paramref name="type"/>, suitable for including in a URI.</returns>
        internal static string GetEntityTypeNameForUriAndValidateMaxProtocolVersion(Type type, DataServiceContext context, ref Version uriVersion)
        {
            Debug.Assert(type != null, "type != null");
            Debug.Assert(context != null, "context != null");

            if (context.MaxProtocolVersionAsVersion < Util.DataServiceVersion3)
            {
                throw new NotSupportedException(Strings.ALinq_TypeAsNotSupportedForMaxDataServiceVersionLessThan3);
            }

            if (!ClientTypeUtil.TypeOrElementTypeIsEntity(type))
            {
                throw new NotSupportedException(Strings.ALinq_TypeAsArgumentNotEntityType(type.FullName));
            }

            // Raise the uriVersion each time we write the type segment on the uri.
            WebUtil.RaiseVersion(ref uriVersion, Util.DataServiceVersion3);
            return(context.ResolveNameFromType(type) ?? type.FullName);
        }
예제 #12
0
 private MaterializeAtom(DataServiceContext context, XmlReader reader, Type type, MergeOption mergeOption)
     : this(context, reader, new QueryComponents(null, Util.DataServiceVersionEmpty, type, null, null), null, mergeOption)
 {
 }
예제 #13
0
 /// <summary>
 /// Creates a new instance of RequestInfo class which is used to build the request to send to the server
 /// </summary>
 /// <param name="context">wrapping context instance.</param>
 /// <param name="isContinuation">Whether this is a continuation request.</param>
 internal RequestInfo(DataServiceContext context, bool isContinuation) : this(context)
 {
     this.IsContinuation = isContinuation;
 }
예제 #14
0
        protected override void AsyncEndGetResponse(IAsyncResult asyncResult)
        {
            BaseAsyncResult.AsyncStateBag asyncState = asyncResult.AsyncState as BaseAsyncResult.AsyncStateBag;
            BaseAsyncResult.PerRequest    request    = (asyncState == null) ? null : asyncState.PerRequest;
            DataServiceContext            context    = (asyncState == null) ? null : asyncState.Context;

            try
            {
                if (base.IsAborted)
                {
                    if (request != null)
                    {
                        request.SetComplete();
                    }
                    base.SetCompleted();
                }
                else
                {
                    this.CompleteCheck(request, InternalError.InvalidEndGetResponseCompleted);
                    request.SetRequestCompletedSynchronously(asyncResult.CompletedSynchronously);
                    base.SetCompletedSynchronously(asyncResult.CompletedSynchronously);
                    HttpWebResponse response = WebUtil.EndGetResponse(Util.NullCheck <ODataRequestMessageWrapper>(request.Request, InternalError.InvalidEndGetResponseRequest), asyncResult, context);
                    request.HttpWebResponse = Util.NullCheck <HttpWebResponse>(response, InternalError.InvalidEndGetResponseResponse);
                    this.SetHttpWebResponse(request.HttpWebResponse);
                    Stream responseStream = null;
                    if (HttpStatusCode.NoContent != response.StatusCode)
                    {
                        responseStream         = WebUtil.GetResponseStream(response, context);
                        request.ResponseStream = responseStream;
                    }
                    if ((responseStream != null) && responseStream.CanRead)
                    {
                        if (this.outputResponseStream == null)
                        {
                            this.outputResponseStream = Util.NullCheck <Stream>(this.GetAsyncResponseStreamCopy(), InternalError.InvalidAsyncResponseStreamCopy);
                        }
                        if (this.asyncStreamCopyBuffer == null)
                        {
                            this.asyncStreamCopyBuffer = Util.NullCheck <byte[]>(this.GetAsyncResponseStreamCopyBuffer(), InternalError.InvalidAsyncResponseStreamCopyBuffer);
                        }
                        this.ReadResponseStream(asyncState);
                    }
                    else
                    {
                        request.SetComplete();
                        base.SetCompleted();
                    }
                }
            }
            catch (Exception exception)
            {
                if (base.HandleFailure(exception))
                {
                    throw;
                }
            }
            finally
            {
                this.HandleCompleted(request);
            }
        }
예제 #15
0
 public DataServiceCollection(DataServiceContext context)
     : this(context, null, TrackingMode.AutoChangeTracking, null, null, null)
 {
 }
예제 #16
0
            /// <summary>Analyzes the specified member-init expression.</summary>
            /// <param name="mie">Expression to analyze.</param>
            /// <param name="pb">Path-tracking object to store analysis in.</param>
            /// <param name="context">Context of expression to analyze.</param>
            internal static void Analyze(MemberInitExpression mie, PathBox pb, DataServiceContext context)
            {
                Debug.Assert(mie != null, "mie != null");

                var epa = new EntityProjectionAnalyzer(pb, mie.Type, context);

                MemberAssignmentAnalysis targetEntityPath = null;

                foreach (MemberBinding mb in mie.Bindings)
                {
                    MemberAssignment ma = mb as MemberAssignment;
                    epa.Visit(ma.Expression);
                    if (ma != null)
                    {
                        var analysis = MemberAssignmentAnalysis.Analyze(pb.ParamExpressionInScope, ma.Expression);
                        if (analysis.IncompatibleAssignmentsException != null)
                        {
                            throw analysis.IncompatibleAssignmentsException;
                        }

                        // Note that an "empty" assignment on the binding is not checked/handled,
                        // because the funcletizer would have turned that into a constant
                        // in the tree, the visit earlier in this method would have thrown
                        // an exception at finding a constant in an entity projection.
                        //
                        // We do account however for failing to find a reference off the
                        // parameter entry to detect errors like this: new ET() { Ref = e }
                        // Here it looks like the new ET should be the parent of 'e', but
                        // there is nothing in scope that represents that.
                        //
                        // This also explains while error messages might be a bit misleading
                        // in this case (because they reference a constant when the user
                        // hasn't included any).
                        Type         targetType      = ClientTypeUtil.GetMemberType(ma.Member);
                        Expression[] lastExpressions = analysis.GetExpressionsBeyondTargetEntity();
                        if (lastExpressions.Length == 0)
                        {
                            throw new NotSupportedException(Strings.ALinq_ExpressionNotSupportedInProjectionToEntity(targetType, ma.Expression));
                        }

                        MemberExpression lastExpression = lastExpressions[lastExpressions.Length - 1] as MemberExpression;
                        Debug.Assert(
                            !analysis.MultiplePathsFound,
                            "!analysis.MultiplePathsFound -- the initilizer has been visited, and cannot be empty, and expressions that can combine paths should have thrown exception during initializer analysis");
#if DEBUG
                        Debug.Assert(
                            lastExpression != null,
                            "lastExpression != null -- the initilizer has been visited, and cannot be empty, and the only expressions that are allowed can be formed off the parameter, so this is always correlatd");
#endif

                        analysis.CheckCompatibleAssignments(mie.Type, ref targetEntityPath);

                        // For DataServiceStreamLink, the last expression will be a constant expression. Hence we won't be comparing name checks and entity checks for those type of bindings
                        if (lastExpression != null)
                        {
                            if (lastExpression.Member.Name != ma.Member.Name)
                            {
                                throw new NotSupportedException(Strings.ALinq_PropertyNamesMustMatchInProjections(lastExpression.Member.Name, ma.Member.Name));
                            }

                            // Unless we're initializing an entity, we should not traverse into the parameter in scope.
                            bool targetIsEntity = ClientTypeUtil.TypeOrElementTypeIsEntity(targetType);
                            bool sourceIsEntity = ClientTypeUtil.TypeOrElementTypeIsEntity(lastExpression.Type);
                            if (sourceIsEntity && !targetIsEntity)
                            {
                                throw new NotSupportedException(Strings.ALinq_ExpressionNotSupportedInProjection(targetType, ma.Expression));
                            }
                        }
                    }
                }
            }
예제 #17
0
 internal DataServiceQueryProvider(DataServiceContext context)
 {
     this.Context = context;
 }
예제 #18
0
        internal void AppendPropertyToPath(PropertyInfo pi, Type convertedSourceType, DataServiceContext context)
        {
            bool   flag = ClientTypeUtil.TypeOrElementTypeIsEntity(pi.PropertyType);
            string name = (convertedSourceType == null) ? null : System.Data.Services.Client.UriHelper.GetEntityTypeNameForUriAndValidateMaxProtocolVersion(convertedSourceType, context, ref this.uriVersion);

            if (flag)
            {
                if (convertedSourceType != null)
                {
                    this.AppendToExpandPath(name);
                }
                this.AppendToExpandPath(pi.Name);
            }
            StringBuilder sb = null;

            if (convertedSourceType != null)
            {
                this.AppendToProjectionPath(name, false);
            }
            sb = this.AppendToProjectionPath(pi.Name, false);
            if (flag)
            {
                AddEntireEntityMarker(sb);
            }
        }