private static ODataCollectionValue ReadResourceSet(ODataReader reader)
        {
            var items = new List <ODataResource>();

            while (reader.Read())
            {
                if (reader.State == ODataReaderState.ResourceEnd)
                {
                    items.Add((ODataResource)reader.Item);
                }
            }

            return(new ODataCollectionValue()
            {
                Items = items
            });
        }
        public static void Deserialize(this ITableEntity entity, byte[] value)
        {
            MemoryStream ms = new MemoryStream(value);

            using (ODataMessageReader messageReader = new ODataMessageReader(new Message(ms), new ODataMessageReaderSettings()
            {
                MessageQuotas = new ODataMessageQuotas()
                {
                    MaxReceivedMessageSize = 20 * 1024 * 1024
                }
            }))
            {
                ODataReader reader = messageReader.CreateODataEntryReader();
                reader.Read();
                TableOperationHttpWebRequestFactory.ReadAndUpdateTableEntity(entity, (ODataEntry)reader.Item, null);
            }
        }
 public void VerifyCanReadResponseSyncTest()
 {
     using (ODataMessageReader messageReader = new ODataMessageReader(
                this.CreateResponseMessage(),
                new ODataMessageReaderSettings(),
                TestUtils.GetServiceModel(TestDemoService.ServiceBaseUri)))
     {
         ODataReader reader = messageReader.CreateODataEntryReader();
         while (reader.Read())
         {
             if (reader.State == ODataReaderState.EntryEnd)
             {
                 ODataEntry entry = (ODataEntry)reader.Item;
                 Assert.AreEqual("DataServiceProviderDemo.Product", entry.TypeName);
             }
         }
     }
 }
        private ODataResponse ReadResponse(ODataReader odataReader, IODataResponseMessageAsync responseMessage)
        {
            ResponseNode rootNode  = null;
            var          nodeStack = new Stack <ResponseNode>();

            while (odataReader.Read())
            {
                if (odataReader.State == ODataReaderState.Completed)
                {
                    break;
                }

                switch (odataReader.State)
                {
                case ODataReaderState.ResourceSetStart:
                case ODataReaderState.DeltaResourceSetStart:
                    StartFeed(nodeStack, CreateAnnotations(odataReader.Item as ODataResourceSetBase));
                    break;

                case ODataReaderState.ResourceSetEnd:
                case ODataReaderState.DeltaResourceSetEnd:
                    EndFeed(nodeStack, CreateAnnotations(odataReader.Item as ODataResourceSetBase), ref rootNode);
                    break;

                case ODataReaderState.ResourceStart:
                    StartEntry(nodeStack);
                    break;

                case ODataReaderState.ResourceEnd:
                    EndEntry(nodeStack, ref rootNode, odataReader.Item);
                    break;

                case ODataReaderState.NestedResourceInfoStart:
                    StartNavigationLink(nodeStack, (odataReader.Item as ODataNestedResourceInfo).Name);
                    break;

                case ODataReaderState.NestedResourceInfoEnd:
                    EndNavigationLink(nodeStack);
                    break;
                }
            }

            return(ODataResponse.FromNode(TypeCache, rootNode, responseMessage.Headers));
        }
Example #5
0
        private ODataResponse ReadResponse(ODataReader odataReader, bool includeResourceTypeInEntryProperties)
        {
            ResponseNode rootNode  = null;
            var          nodeStack = new Stack <ResponseNode>();

            while (odataReader.Read())
            {
                if (odataReader.State == ODataReaderState.Completed)
                {
                    break;
                }

                switch (odataReader.State)
                {
                case ODataReaderState.FeedStart:
                    StartFeed(nodeStack, CreateFeedAnnotaions(odataReader.Item as ODataFeed));
                    break;

                case ODataReaderState.FeedEnd:
                    EndFeed(nodeStack, CreateFeedAnnotaions(odataReader.Item as ODataFeed), ref rootNode);
                    break;

                case ODataReaderState.EntryStart:
                    StartEntry(nodeStack);
                    break;

                case ODataReaderState.EntryEnd:
                    EndEntry(nodeStack, ref rootNode, odataReader.Item, includeResourceTypeInEntryProperties);
                    break;

                case ODataReaderState.NavigationLinkStart:
                    StartNavigationLink(nodeStack, (odataReader.Item as ODataNavigationLink).Name);
                    break;

                case ODataReaderState.NavigationLinkEnd:
                    EndNavigationLink(nodeStack);
                    break;
                }
            }

            return(rootNode.Feed != null
                ? ODataResponse.FromFeed(rootNode.Feed, rootNode.FeedAnnotations)
                : ODataResponse.FromEntry(rootNode.Entry));
        }
Example #6
0
        /// <summary>
        /// Reads a <see cref="ODataResource"/> or <see cref="ODataResourceSet"/> object.
        /// </summary>
        /// <param name="reader">The OData reader to read from.</param>
        /// <returns>The read resource or resource set.</returns>
        public static ODataItemWrapper ReadResourceOrResourceSet(this ODataReader reader)
        {
            if (reader == null)
            {
                throw Error.ArgumentNull(nameof(reader));
            }

            ODataItemWrapper         topLevelItem = null;
            Stack <ODataItemWrapper> itemsStack   = new Stack <ODataItemWrapper>();

            while (reader.Read())
            {
                ReadODataItem(reader, itemsStack, ref topLevelItem);
            }

            Contract.Assert(reader.State == ODataReaderState.Completed, "We should have consumed all of the input by now.");
            Contract.Assert(topLevelItem != null, "A top level resource or resource set should have been read by now.");
            return(topLevelItem);
        }
        public static void Deserialize(this ITableEntity entity, byte[] value)
        {
            MemoryStream ms = new MemoryStream(value);

            using (ODataMessageReader messageReader = new ODataMessageReader(new Message(ms), new ODataMessageReaderSettings()
            {
                MessageQuotas = new ODataMessageQuotas()
                {
                    MaxReceivedMessageSize = 20 * 1024 * 1024
                }
            }))
            {
                ODataReader reader = messageReader.CreateODataEntryReader();
                var         readAndUpdateTableEntity = typeof(TableConstants).Assembly.GetType("Microsoft.WindowsAzure.Storage.Table.Protocol.TableOperationHttpResponseParsers")
                                                       .GetMethod("ReadAndUpdateTableEntity", BindingFlags.NonPublic | BindingFlags.Static);
                reader.Read();
                readAndUpdateTableEntity.Invoke(null, new object[] { entity, reader.Item, 31, null });
            }
        }
Example #8
0
 private void ReadFeedTestAndMeasure(string templateFile, int entryCount, bool isFullValidation)
 {
     foreach (var iteration in Benchmark.Iterations)
     {
         using (var stream = new MemoryStream(PayloadGenerator.GenerateFeed(templateFile, entryCount)))
         {
             using (iteration.StartMeasurement())
             {
                 using (var messageReader = ODataMessageHelper.CreateMessageReader(stream, Model, ODataMessageKind.Response, isFullValidation))
                 {
                     ODataReader feedReader = messageReader.CreateODataResourceSetReader(TestEntitySet, TestEntityType);
                     while (feedReader.Read())
                     {
                     }
                 }
             }
         }
     }
 }
        private ODataResponse ReadResponse(ODataReader odataReader)
        {
            ResponseNode rootNode  = null;
            var          nodeStack = new Stack <ResponseNode>();

            while (odataReader.Read())
            {
                if (odataReader.State == ODataReaderState.Completed)
                {
                    break;
                }

                switch (odataReader.State)
                {
                case ODataReaderState.FeedStart:
                    StartFeed(nodeStack, CreateFeedDetails(odataReader.Item as ODataFeed));
                    break;

                case ODataReaderState.FeedEnd:
                    EndFeed(nodeStack, CreateFeedDetails(odataReader.Item as ODataFeed), ref rootNode);
                    break;

                case ODataReaderState.EntryStart:
                    StartEntry(nodeStack);
                    break;

                case ODataReaderState.EntryEnd:
                    EndEntry(nodeStack, ref rootNode, odataReader.Item);
                    break;

                case ODataReaderState.NavigationLinkStart:
                    StartNavigationLink(nodeStack, (odataReader.Item as ODataNavigationLink).Name);
                    break;

                case ODataReaderState.NavigationLinkEnd:
                    EndNavigationLink(nodeStack);
                    break;
                }
            }

            return(ODataResponse.FromNode(rootNode));
        }
Example #10
0
        private void ClientReadBatchResponse(string batchContentType, byte[] responsePayload)
        {
            Debug.Assert(!string.IsNullOrEmpty(batchContentType), "!string.IsNullOrEmpty(batchContentType)");

            IODataResponseMessage responseMessage = new InMemoryMessage()
            {
                Stream = new MemoryStream(responsePayload)
            };

            responseMessage.SetHeader("Content-Type", batchContentType);
            using (var messageReader = new ODataMessageReader(responseMessage, new ODataMessageReaderSettings(), this.userModel))
            {
                var batchReader = messageReader.CreateODataBatchReader();
                while (batchReader.Read())
                {
                    switch (batchReader.State)
                    {
                    case ODataBatchReaderState.Operation:
                        ODataBatchOperationResponseMessage operationMessage = batchReader.CreateOperationResponseMessage();
                        if (operationMessage.StatusCode == 200)
                        {
                            using (ODataMessageReader innerMessageReader = new ODataMessageReader(
                                       operationMessage, new ODataMessageReaderSettings(), this.userModel))
                            {
                                ODataReader reader = innerMessageReader.CreateODataResourceReader();

                                while (reader.Read())
                                {
                                }
                            }
                        }
                        break;

                    default:
                        break;
                    }
                }
            }
        }
Example #11
0
        public static object ReadEntityOrEntityCollection(ODataReader reader, bool forFeed)
        {
            MethodInfo addMethod = null;

            // Store the last entry of the top-level feed or the top-level entry;
            ODataResource entry = null;

            // Store entries at each level
            Stack <ODataItem> items = new Stack <ODataItem>();

            // Store the objects with its parent for current level.
            // Example:
            //    CompleCollection: [ complex1, complex2 ]
            //    objects contains [{CompleCollection, complex1Obj}, {CompleCollection, complex2Obj}] when NestedResourceInfoEnd for CompleCollection
            Stack <KeyValuePair <ODataItem, object> > objects = new Stack <KeyValuePair <ODataItem, object> >();

            // Store the SetValue action for complex property.
            Stack <KeyValuePair <ODataItem, Action <object> > > actions = new Stack <KeyValuePair <ODataItem, Action <object> > >();

            while (reader.Read())
            {
                switch (reader.State)
                {
                case ODataReaderState.ResourceStart:
                case ODataReaderState.NestedResourceInfoStart:
                {
                    items.Push(reader.Item);
                    break;
                }

                case ODataReaderState.NestedResourceInfoEnd:
                {
                    items.Pop();
                    // Create current complex property value.
                    var currentProperty = reader.Item as ODataNestedResourceInfo;
                    var parent          = items.Peek() as ODataResource;
                    var parentType      = EdmClrTypeUtils.GetInstanceType(parent.TypeName);
                    var propertyInfo    = parentType.GetProperty(currentProperty.Name);
                    if (propertyInfo != null)
                    {
                        var propertyType = propertyInfo.PropertyType;
                        if (propertyType.IsGenericType)
                        {
                            Type listType = typeof(List <>).MakeGenericType(propertyType.GetGenericArguments()[0]);
                            addMethod = listType.GetMethod("Add");
                            var currentList = Activator.CreateInstance(listType);
                            while (objects.Count > 0 && objects.Peek().Key == currentProperty)
                            {
                                addMethod.Invoke(currentList, new[] { objects.Pop().Value });
                            }

                            // Keep the order of all the items
                            MethodInfo reverseMethod = listType.GetMethod("Reverse", new Type[0]);
                            reverseMethod.Invoke(currentList, new object[0]);
                            actions.Push(new KeyValuePair <ODataItem, Action <object> >(parent, obj => propertyInfo.SetValue(obj, currentList)));
                        }
                        else
                        {
                            var propertyValue = objects.Pop().Value;
                            actions.Push(new KeyValuePair <ODataItem, Action <object> >(parent, obj => propertyInfo.SetValue(obj, propertyValue)));
                        }
                    }

                    break;
                }

                case ODataReaderState.ResourceEnd:
                {
                    // Create object for current resource.
                    entry = reader.Item as ODataResource;
                    object item = ODataObjectModelConverter.ConvertPropertyValue(entry);
                    while (actions.Count > 0 && actions.Peek().Key == entry)
                    {
                        actions.Pop().Value.Invoke(item);
                    }

                    items.Pop();
                    var parent = items.Count > 0 ? items.Peek() : null;
                    objects.Push(new KeyValuePair <ODataItem, object>(parent, item));
                    break;
                }

                default:
                    break;
                }
            }
            if (forFeed)
            {
                // create the list. This would require the first type is not derived type.
                List <object> topLeveObjects = new List <object>();
                while (objects.Count > 0)
                {
                    topLeveObjects.Add(objects.Pop().Value);
                }

                Type type = null;
                // Need to fix this if all items in the collection are null;
                if (entry == null || string.IsNullOrEmpty(entry.TypeName))
                {
                    for (int i = 0; i < topLeveObjects.Count; i++)
                    {
                        if (topLeveObjects[i] != null)
                        {
                            type = topLeveObjects[i].GetType();
                            break;
                        }
                    }
                }
                else
                {
                    type = EdmClrTypeUtils.GetInstanceType(entry.TypeName);
                }

                Type listType = typeof(List <>).MakeGenericType(type);
                addMethod = listType.GetMethod("Add");
                var list = Activator.CreateInstance(listType);
                for (int i = topLeveObjects.Count - 1; i >= 0; i--)
                {
                    addMethod.Invoke(list, new[] { topLeveObjects[i] });
                }

                return(list);
            }
            else
            {
                return(objects.Pop().Value);
            }
        }
Example #12
0
        public static void TestReadResource()
        {
            string requestData = @"{
  ""@odata.type"": ""#NS.Customer"",
  ""*****@*****.**"": ""Cloud"",
  ""DisplayName"": ""Group Display Name"",
  ""*****@*****.**"": ""Cloud"",
  ""AssignedLabels"": [
    {
      ""City"": ""City1"",
      ""Street"": ""Street1""
    }
  ]
}";
            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("Content-Type", "application/json;odata.metadata=minima;odata.streaming=true");
            headers.Add("Accept", "application/json");

            ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings
            {
                BaseUri = new Uri("http://localhost"),
                ShouldIncludeAnnotation = s => true
            };

            //ODataResourceWrapper topLevelResource = null;

            ODataItemWrapper topLevel = null, currentItem = null;
            IEdmModel        model     = EdmModelBuilder.GetEdmModel();
            IEdmEntitySet    customers = model.EntityContainer.FindEntitySet("Customers");

            //  ODataResource resource = null;
            using (MemoryStream ms = new MemoryStream(Encoding.GetEncoding("iso-8859-1").GetBytes(requestData)))
            {
                ODataMessageWrapper requestMessage = new ODataMessageWrapper(ms);

                ODataMessageReader messageReader = new ODataMessageReader((IODataRequestMessage)requestMessage, readerSettings, model);

                Stack <ODataItemWrapper> resStack = new Stack <ODataItemWrapper>();
                ODataReader odataReader           = messageReader.CreateODataResourceReader(customers, customers.EntityType());

                while (odataReader.Read())
                {
                    Console.WriteLine(odataReader.State);

                    switch (odataReader.State)
                    {
                    case ODataReaderState.ResourceStart:
                        ODataResourceWrapper newResource = new ODataResourceWrapper();
                        newResource.Resource = odataReader.Item as ODataResource;

                        resStack.TryPeek(out currentItem);
                        if (currentItem == null)
                        {
                            // TopLevel, do nothing
                            Debug.Assert(topLevel == null);
                            topLevel = newResource;
                        }
                        else
                        {
                            currentItem.Append(newResource);
                        }

                        resStack.Push(newResource);
                        break;

                    case ODataReaderState.ResourceSetStart:
                        ODataResourceSet        resourceSet = (ODataResourceSet)odataReader.Item;
                        ODataResourceSetWrapper setWrapper  = new ODataResourceSetWrapper
                        {
                            ResourceSet = resourceSet
                        };

                        resStack.TryPeek(out currentItem);
                        if (currentItem == null)
                        {
                            // TopLevel, do nothing
                            Debug.Assert(topLevel == null);
                            topLevel = setWrapper;
                        }
                        else
                        {
                            currentItem.Append(setWrapper);
                        }

                        resStack.Push(setWrapper);
                        break;

                    case ODataReaderState.NestedResourceInfoStart:
                        resStack.TryPeek(out currentItem);
                        Debug.Assert(currentItem != null);

                        ODataItem item = odataReader.Item;
                        ODataNestedResourceInfoWrapper infoWrapper = new ODataNestedResourceInfoWrapper
                        {
                            NestedInfo = item as ODataNestedResourceInfo
                        };

                        currentItem.Append(infoWrapper);
                        resStack.Push(infoWrapper);
                        break;

                    case ODataReaderState.ResourceEnd:
                        //currWrapper = resStack.Peek();
                        //currWrapper.Resource = (ODataResource)odataReader.Item;
                        resStack.Pop();
                        break;

                    case ODataReaderState.ResourceSetEnd:

                        resStack.Pop();
                        break;

                    case ODataReaderState.NestedResourceInfoEnd:

                        item = odataReader.Item;

                        resStack.Pop();
                        break;
                    }
                }
            }

            if (topLevel == null)
            {
                return;
            }

            ODataResourceWrapper topLevelResource = topLevel as ODataResourceWrapper;

            if (topLevelResource != null)
            {
                foreach (var a in topLevelResource.Resource.Properties)
                {
                    Console.WriteLine(a.Name + ": " + a.Value);
                }

                foreach (var a in topLevelResource.NestedResourceInfos)
                {
                    Console.WriteLine(a.NestedInfo.Name);
                    ODataResourceSetWrapper setWrapper      = a.NestedWrapper as ODataResourceSetWrapper;
                    ODataResourceWrapper    resourceWrapper = a.NestedWrapper as ODataResourceWrapper;
                    if (resourceWrapper != null)
                    {
                        foreach (var prop in resourceWrapper.Resource.Properties)
                        {
                            Console.WriteLine(prop.Name + ": " + prop.Value);
                        }
                    }
                }
            }
        }
        internal static Task <ResultSegment <TElement> > TableQueryPostProcessGeneric <TElement>(Stream responseStream, Func <string, string, DateTimeOffset, IDictionary <string, EntityProperty>, string, TElement> resolver, HttpResponseMessage resp, TableRequestOptions options, OperationContext ctx, string accountName)
        {
            return(Task.Run(() =>
            {
                ResultSegment <TElement> retSeg = new ResultSegment <TElement>(new List <TElement>());
                retSeg.ContinuationToken = ContinuationFromResponse(resp);
                IEnumerable <string> contentType;
                IEnumerable <string> eTag;

                resp.Content.Headers.TryGetValues(Constants.ContentTypeElement, out contentType);
                resp.Headers.TryGetValues(Constants.EtagElement, out eTag);

                string ContentType = contentType != null ? contentType.FirstOrDefault() : null;
                string ETag = eTag != null ? eTag.FirstOrDefault() : null;
                if (ContentType.Contains(Constants.JsonContentTypeHeaderValue) && ContentType.Contains(Constants.NoMetadata))
                {
                    ReadQueryResponseUsingJsonParser(retSeg, responseStream, ETag, resolver, options.PropertyResolver, typeof(TElement), null);
                }
                else
                {
                    ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings();
                    readerSettings.MessageQuotas = new ODataMessageQuotas()
                    {
                        MaxPartsPerBatch = TableConstants.TableServiceMaxResults, MaxReceivedMessageSize = TableConstants.TableServiceMaxPayload
                    };

                    using (ODataMessageReader responseReader = new ODataMessageReader(new HttpResponseAdapterMessage(resp, responseStream), readerSettings, new TableStorageModel(accountName)))
                    {
                        // create a reader
                        ODataReader reader = responseReader.CreateODataFeedReader();

                        // Start => FeedStart
                        if (reader.State == ODataReaderState.Start)
                        {
                            reader.Read();
                        }

                        // Feedstart
                        if (reader.State == ODataReaderState.FeedStart)
                        {
                            reader.Read();
                        }

                        while (reader.State == ODataReaderState.EntryStart)
                        {
                            // EntryStart => EntryEnd
                            reader.Read();

                            ODataEntry entry = (ODataEntry)reader.Item;

                            retSeg.Results.Add(ReadAndResolve(entry, resolver));

                            // Entry End => ?
                            reader.Read();
                        }

                        DrainODataReader(reader);
                    }
                }

                return retSeg;
            }));
        }
        private string WriteAndVerifyRequestMessage(StreamRequestMessage requestMessageWithoutModel,
                                                    ODataWriter odataWriter, bool hasModel, string mimeType)
        {
            var order = new ODataEntry()
            {
                Id       = new Uri(this.ServiceUri + "Order(-10)"),
                TypeName = NameSpace + "Order"
            };

            var orderP1 = new ODataProperty {
                Name = "OrderId", Value = -10
            };
            var orderp2 = new ODataProperty {
                Name = "CustomerId", Value = 8212
            };
            var orderp3 = new ODataProperty {
                Name = "Concurrency", Value = null
            };

            order.Properties = new[] { orderP1, orderp2, orderp3 };
            if (!hasModel)
            {
                order.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo()
                {
                    NavigationSourceName = "Order", NavigationSourceEntityTypeName = NameSpace + "Order"
                });
                orderP1.SetSerializationInfo(new ODataPropertySerializationInfo()
                {
                    PropertyKind = ODataPropertyKind.Key
                });
            }

            odataWriter.WriteStart(order);
            odataWriter.WriteEnd();

            Stream stream = requestMessageWithoutModel.GetStream();

            if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
            {
                stream.Seek(0, SeekOrigin.Begin);
                var settings = new ODataMessageReaderSettings()
                {
                    BaseUri = this.ServiceUri
                };
                ODataMessageReader messageReader = new ODataMessageReader(requestMessageWithoutModel, settings,
                                                                          WritePayloadHelper.Model);
                ODataReader reader            = messageReader.CreateODataEntryReader(WritePayloadHelper.OrderSet, WritePayloadHelper.OrderType);
                bool        verifyEntryCalled = false;
                while (reader.Read())
                {
                    if (reader.State == ODataReaderState.EntryEnd)
                    {
                        ODataEntry entry = reader.Item as ODataEntry;
                        Assert.IsTrue(entry.Id.ToString().Contains("Order(-10)"), "entry.Id");
                        Assert.AreEqual(3, entry.Properties.Count(), "entry.Properties.Count");
                        verifyEntryCalled = true;
                    }
                }

                Assert.AreEqual(ODataReaderState.Completed, reader.State);
                Assert.IsTrue(verifyEntryCalled, "verifyEntryCalled");
            }

            return(WritePayloadHelper.ReadStreamContent(stream));
        }
Example #15
0
        public IEnumerable <JObject> ReadOpenType(Stream response, Type baseEntityType)
        {
            IODataRequestMessage responseMessage = new OeInMemoryMessage(response, null);
            var settings = new ODataMessageReaderSettings()
            {
                Validations = ValidationKinds.None, EnableMessageStreamDisposal = false
            };
            var messageReader = new ODataMessageReader(responseMessage, settings, _edmModel);

            IEdmEntitySet entitySet = _edmModel.EntityContainer.EntitySets().Single(e => e.Type.AsElementType().FullTypeName() == baseEntityType.FullName);
            ODataReader   reader    = messageReader.CreateODataResourceSetReader(entitySet, entitySet.EntityType());

            StackItem stackItem;
            var       stack = new Stack <StackItem>();

            while (reader.Read())
            {
                switch (reader.State)
                {
                case ODataReaderState.ResourceSetStart:
                    stack.Push(new StackItem((ODataResourceSet)reader.Item));
                    break;

                case ODataReaderState.ResourceSetEnd:
                    stackItem = stack.Pop();
                    if (stack.Count == 0)
                    {
                        if (stackItem.Value != null)
                        {
                            foreach (StackItem entry in (IList)stackItem.Value)
                            {
                                yield return((JObject)CreateOpenTypeEntity(entry));
                            }
                        }
                    }
                    else
                    {
                        var entries = (IList)CreateOpenTypeEntity(stackItem);
                        stack.Peek().AddEntry(entries);
                    }
                    break;

                case ODataReaderState.ResourceStart:
                    stack.Push(new StackItem((ODataResource)reader.Item));
                    break;

                case ODataReaderState.ResourceEnd:
                    stackItem = stack.Pop();
                    if (stack.Count == 0)
                    {
                        yield return((JObject)CreateOpenTypeEntity(stackItem));
                    }
                    else
                    {
                        stack.Peek().AddEntry(stackItem);
                    }
                    break;

                case ODataReaderState.NestedResourceInfoStart:
                    stack.Push(new StackItem((ODataNestedResourceInfo)reader.Item));
                    break;

                case ODataReaderState.NestedResourceInfoEnd:
                    StackItem item = stack.Pop();
                    stack.Peek().AddLink((ODataNestedResourceInfo)item.Item, item.Value);
                    break;
                }
            }
        }
Example #16
0
        private string WriteAndVerifyRequestMessage(ODataMessageWriterSettings settings, string mimeType, bool hasModel)
        {
            // create an order entry to POST
            var order = new ODataEntry()
            {
                TypeName = NameSpace + "Order"
            };

            var orderP1 = new ODataProperty {
                Name = "OrderId", Value = -10
            };
            var orderp2 = new ODataProperty {
                Name = "CustomerId", Value = 8212
            };
            var orderp3 = new ODataProperty {
                Name = "Concurrency", Value = null
            };

            order.Properties = new[] { orderP1, orderp2, orderp3 };
            if (!hasModel)
            {
                order.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo()
                {
                    NavigationSourceName = "Order", NavigationSourceEntityTypeName = NameSpace + "Order"
                });
                orderP1.SetSerializationInfo(new ODataPropertySerializationInfo()
                {
                    PropertyKind = ODataPropertyKind.Key
                });
            }

            Dictionary <string, object> expectedOrderObject = WritePayloadHelper.ComputeExpectedFullMetadataEntryObject(WritePayloadHelper.OrderType, "Order(-10)", order, hasModel);

            // write the request message and read using ODL reader
            var requestMessage = new StreamRequestMessage(new MemoryStream(), new Uri(this.ServiceUri + "Order"), "POST");

            requestMessage.SetHeader("Content-Type", mimeType);
            string result = string.Empty;

            using (var messageWriter = this.CreateODataMessageWriter(requestMessage, settings, hasModel))
            {
                var odataWriter = this.CreateODataEntryWriter(messageWriter, WritePayloadHelper.OrderSet, WritePayloadHelper.OrderType, hasModel);
                odataWriter.WriteStart(order);
                odataWriter.WriteEnd();

                Stream stream = requestMessage.GetStream();
                result = WritePayloadHelper.ReadStreamContent(stream);
                if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    var readerSetting = new ODataMessageReaderSettings()
                    {
                        BaseUri = this.ServiceUri
                    };
                    ODataMessageReader messageReader = new ODataMessageReader(requestMessage, readerSetting, WritePayloadHelper.Model);
                    ODataReader        reader        = messageReader.CreateODataEntryReader(WritePayloadHelper.OrderSet, WritePayloadHelper.OrderType);
                    bool verifyEntryCalled           = false;
                    while (reader.Read())
                    {
                        if (reader.State == ODataReaderState.EntryEnd)
                        {
                            ODataEntry entry = reader.Item as ODataEntry;
                            Assert.AreEqual(3, entry.Properties.Count(), "entry.Properties.Count");
                            verifyEntryCalled = true;
                        }
                    }

                    Assert.AreEqual(ODataReaderState.Completed, reader.State);
                    Assert.IsTrue(verifyEntryCalled, "verifyEntryCalled");
                }
            }

            // For Json light, verify the resulting metadata is as expected
            if (mimeType != MimeTypes.ApplicationAtomXml)
            {
                JavaScriptSerializer        jScriptSerializer = new JavaScriptSerializer();
                Dictionary <string, object> resultObject      = jScriptSerializer.DeserializeObject(result) as Dictionary <string, object>;

                // AutoComputePayloadMetadataInJson has no effect on request message metadata
                Assert.AreEqual(this.ServiceUri + "$metadata#Order/$entity", resultObject.Single(e => e.Key == JsonLightConstants.ODataContextAnnotationName).Value);
                resultObject.Remove(JsonLightConstants.ODataContextAnnotationName);

                foreach (var pair in resultObject)
                {
                    Assert.IsFalse(pair.Key.Contains("odata.") || pair.Key.StartsWith("#"));
                }
            }

            return(result);
        }
Example #17
0
        private void ReadAndOutputEntryOrFeed(ODataReader reader)
        {
            while (reader.Read())
            {
                switch (reader.State)
                {
                case ODataReaderState.FeedStart:
                {
                    ODataFeed feed = (ODataFeed)reader.Item;
                    this.writer.WriteLine("ODataFeed:");
                    this.writer.Indent++;
                }

                break;

                case ODataReaderState.FeedEnd:
                {
                    ODataFeed feed = (ODataFeed)reader.Item;
                    if (feed.Count != null)
                    {
                        this.writer.WriteLine("Count: " + feed.Count.ToString());
                    }
                    if (feed.NextPageLink != null)
                    {
                        this.writer.WriteLine("NextPageLink: " + feed.NextPageLink.AbsoluteUri);
                    }

                    this.writer.Indent--;
                }

                break;

                case ODataReaderState.EntryStart:
                {
                    ODataEntry entry = (ODataEntry)reader.Item;
                    this.writer.WriteLine("ODataEntry:");
                    this.writer.Indent++;
                }

                break;

                case ODataReaderState.EntryEnd:
                {
                    ODataEntry entry = (ODataEntry)reader.Item;
                    this.writer.WriteLine("TypeName: " + (entry.TypeName ?? "<null>"));
                    this.writer.WriteLine("Id: " + (entry.Id ?? "<null>"));
                    if (entry.ReadLink != null)
                    {
                        this.writer.WriteLine("ReadLink: " + entry.ReadLink.AbsoluteUri);
                    }

                    if (entry.EditLink != null)
                    {
                        this.writer.WriteLine("EditLink: " + entry.EditLink.AbsoluteUri);
                    }

                    if (entry.MediaResource != null)
                    {
                        this.writer.Write("MediaResource: ");
                        this.WriteValue(entry.MediaResource);
                    }

                    this.WriteProperties(entry.Properties);

                    this.writer.Indent--;
                }

                break;

                case ODataReaderState.NavigationLinkStart:
                {
                    ODataNavigationLink navigationLink = (ODataNavigationLink)reader.Item;
                    this.writer.WriteLine(navigationLink.Name + ": ODataNavigationLink: ");
                    this.writer.Indent++;
                }

                break;

                case ODataReaderState.NavigationLinkEnd:
                {
                    ODataNavigationLink navigationLink = (ODataNavigationLink)reader.Item;
                    this.writer.WriteLine("Url: " + (navigationLink.Url == null ? "<null>" : navigationLink.Url.AbsoluteUri));
                    this.writer.Indent--;
                }

                break;
                }
            }
        }
Example #18
0
        protected IEnumerable Read(Stream response, Db.OeEntitySetAdapter entitySetMetaAdatpter)
        {
            ResourceSet = null;
            NavigationProperties.Clear();
            NavigationInfoEntities.Clear();

            IODataResponseMessage responseMessage = new Infrastructure.OeInMemoryMessage(response, null, _serviceProvider);
            var settings = new ODataMessageReaderSettings()
            {
                EnableMessageStreamDisposal = false, Validations = ValidationKinds.None
            };

            using (var messageReader = new ODataMessageReader(responseMessage, settings, EdmModel))
            {
                IEdmEntitySet entitySet = OeEdmClrHelper.GetEntitySet(EdmModel, entitySetMetaAdatpter.EntitySetName);
                ODataReader   reader    = messageReader.CreateODataResourceSetReader(entitySet, entitySet.EntityType());

                var stack = new Stack <StackItem>();
                while (reader.Read())
                {
                    switch (reader.State)
                    {
                    case ODataReaderState.ResourceSetStart:
                        if (stack.Count == 0)
                        {
                            ResourceSet = (ODataResourceSetBase)reader.Item;
                        }
                        else
                        {
                            stack.Peek().ResourceSet = (ODataResourceSetBase)reader.Item;
                        }
                        break;

                    case ODataReaderState.ResourceStart:
                        stack.Push(new StackItem((ODataResource)reader.Item));
                        break;

                    case ODataReaderState.ResourceEnd:
                        StackItem stackItem = stack.Pop();

                        if (reader.Item != null)
                        {
                            if (stack.Count == 0)
                            {
                                yield return(CreateRootEntity((ODataResource)stackItem.Item, stackItem.NavigationProperties, entitySetMetaAdatpter.EntityType));
                            }
                            else
                            {
                                stack.Peek().AddEntry(CreateEntity((ODataResource)stackItem.Item, stackItem.NavigationProperties));
                            }
                        }
                        break;

                    case ODataReaderState.NestedResourceInfoStart:
                        stack.Push(new StackItem((ODataNestedResourceInfo)reader.Item));
                        break;

                    case ODataReaderState.NestedResourceInfoEnd:
                        StackItem item = stack.Pop();
                        stack.Peek().AddLink((ODataNestedResourceInfo)item.Item, item.Value, item.ResourceSet);
                        break;
                    }
                }
            }
        }
Example #19
0
        /// <summary>
        /// Reads an ODataFeed or an ODataItem from the reader.
        /// </summary>
        /// <param name="reader">The OData reader to read from.</param>
        /// <returns>The read feed or entry.</returns>
        public static ODataItemBase ReadEntryOrFeed(ODataReader reader)
        {
            if (reader == null)
            {
                throw Error.ArgumentNull("odataReader");
            }

            ODataItemBase         topLevelItem = null;
            Stack <ODataItemBase> itemsStack   = new Stack <ODataItemBase>();

            while (reader.Read())
            {
                switch (reader.State)
                {
                case ODataReaderState.EntryStart:
                    ODataEntry entry = (ODataEntry)reader.Item;
                    ODataEntryWithNavigationLinks entryWrapper = null;
                    if (entry != null)
                    {
                        entryWrapper = new ODataEntryWithNavigationLinks(entry);
                    }

                    if (itemsStack.Count == 0)
                    {
                        Contract.Assert(entry != null, "The top-level entry can never be null.");
                        topLevelItem = entryWrapper;
                    }
                    else
                    {
                        ODataItemBase        parentItem = itemsStack.Peek();
                        ODataFeedWithEntries parentFeed = parentItem as ODataFeedWithEntries;
                        if (parentFeed != null)
                        {
                            parentFeed.Entries.Add(entryWrapper);
                        }
                        else
                        {
                            ODataNavigationLinkWithItems parentNavigationLink = (ODataNavigationLinkWithItems)parentItem;
                            Contract.Assert(parentNavigationLink.NavigationLink.IsCollection == false, "Only singleton navigation properties can contain entry as their child.");
                            Contract.Assert(parentNavigationLink.NestedItems.Count == 0, "Each navigation property can contain only one entry as its direct child.");
                            parentNavigationLink.NestedItems.Add(entryWrapper);
                        }
                    }
                    itemsStack.Push(entryWrapper);
                    break;

                case ODataReaderState.EntryEnd:
                    Contract.Assert(itemsStack.Count > 0 && (reader.Item == null || itemsStack.Peek().Item == reader.Item), "The entry which is ending should be on the top of the items stack.");
                    itemsStack.Pop();
                    break;

                case ODataReaderState.NavigationLinkStart:
                    ODataNavigationLink navigationLink = (ODataNavigationLink)reader.Item;
                    Contract.Assert(navigationLink != null, "Navigation link should never be null.");

                    ODataNavigationLinkWithItems navigationLinkWrapper = new ODataNavigationLinkWithItems(navigationLink);
                    Contract.Assert(itemsStack.Count > 0, "Navigation link can't appear as top-level item.");
                    {
                        ODataEntryWithNavigationLinks parentEntry = (ODataEntryWithNavigationLinks)itemsStack.Peek();
                        parentEntry.NavigationLinks.Add(navigationLinkWrapper);
                    }

                    itemsStack.Push(navigationLinkWrapper);
                    break;

                case ODataReaderState.NavigationLinkEnd:
                    Contract.Assert(itemsStack.Count > 0 && itemsStack.Peek().Item == reader.Item, "The navigation link which is ending should be on the top of the items stack.");
                    itemsStack.Pop();
                    break;

                case ODataReaderState.FeedStart:
                    ODataFeed feed = (ODataFeed)reader.Item;
                    Contract.Assert(feed != null, "Feed should never be null.");

                    ODataFeedWithEntries feedWrapper = new ODataFeedWithEntries(feed);
                    if (itemsStack.Count > 0)
                    {
                        ODataNavigationLinkWithItems parentNavigationLink = (ODataNavigationLinkWithItems)itemsStack.Peek();
                        Contract.Assert(parentNavigationLink != null, "this has to be an inner feed. inner feeds always have a navigation link.");
                        Contract.Assert(parentNavigationLink.NavigationLink.IsCollection == true, "Only collection navigation properties can contain feed as their child.");
                        parentNavigationLink.NestedItems.Add(feedWrapper);
                    }
                    else
                    {
                        topLevelItem = feedWrapper;
                    }

                    itemsStack.Push(feedWrapper);
                    break;

                case ODataReaderState.FeedEnd:
                    Contract.Assert(itemsStack.Count > 0 && itemsStack.Peek().Item == reader.Item, "The feed which is ending should be on the top of the items stack.");
                    itemsStack.Pop();
                    break;

                case ODataReaderState.EntityReferenceLink:
                    ODataEntityReferenceLink entityReferenceLink = (ODataEntityReferenceLink)reader.Item;
                    Contract.Assert(entityReferenceLink != null, "Entity reference link should never be null.");
                    ODataEntityReferenceLinkBase entityReferenceLinkWrapper = new ODataEntityReferenceLinkBase(entityReferenceLink);

                    Contract.Assert(itemsStack.Count > 0, "Entity reference link should never be reported as top-level item.");
                    {
                        ODataNavigationLinkWithItems parentNavigationLink = (ODataNavigationLinkWithItems)itemsStack.Peek();
                        parentNavigationLink.NestedItems.Add(entityReferenceLinkWrapper);
                    }

                    break;

                default:
                    Contract.Assert(false, "We should never get here, it means the ODataReader reported a wrong state.");
                    break;
                }
            }

            Contract.Assert(reader.State == ODataReaderState.Completed, "We should have consumed all of the input by now.");
            Contract.Assert(topLevelItem != null, "A top level entry or feed should have been read by now.");
            return(topLevelItem);
        }
Example #20
0
        private ODataEntry ReadEntry(ODataReader odataReader, System.Data.Services.SegmentInfo topLevelSegmentInfo)
        {
            ODataEntry        entry = null;
            Stack <ODataItem> stack = new Stack <ODataItem>();

            while (odataReader.Read())
            {
                if (stack.Count >= 100)
                {
                    throw DataServiceException.CreateDeepRecursion(100);
                }
                switch (odataReader.State)
                {
                case ODataReaderState.FeedStart:
                {
                    ODataFeed feed2 = (ODataFeed)odataReader.Item;
                    feed2.SetAnnotation <ODataFeedAnnotation>(new ODataFeedAnnotation());
                    ODataNavigationLink link3 = (ODataNavigationLink)stack.Peek();
                    link3.GetAnnotation <ODataNavigationLinkAnnotation>().Add(feed2);
                    stack.Push(feed2);
                    break;
                }

                case ODataReaderState.FeedEnd:
                    stack.Pop();
                    break;

                case ODataReaderState.EntryStart:
                {
                    ODataEntry           entry2     = (ODataEntry)odataReader.Item;
                    ODataEntryAnnotation annotation = null;
                    if (entry2 != null)
                    {
                        annotation = new ODataEntryAnnotation();
                        entry2.SetAnnotation <ODataEntryAnnotation>(annotation);
                    }
                    if (stack.Count == 0)
                    {
                        entry = entry2;
                        this.CreateEntityResource(topLevelSegmentInfo, entry2, annotation, true);
                    }
                    else
                    {
                        ODataItem item = stack.Peek();
                        ODataFeed feed = item as ODataFeed;
                        if (feed != null)
                        {
                            feed.GetAnnotation <ODataFeedAnnotation>().Add(entry2);
                        }
                        else
                        {
                            ODataNavigationLink link = (ODataNavigationLink)item;
                            link.GetAnnotation <ODataNavigationLinkAnnotation>().Add(entry2);
                        }
                    }
                    stack.Push(entry2);
                    break;
                }

                case ODataReaderState.EntryEnd:
                    stack.Pop();
                    break;

                case ODataReaderState.NavigationLinkStart:
                {
                    ODataNavigationLink link2 = (ODataNavigationLink)odataReader.Item;
                    link2.SetAnnotation <ODataNavigationLinkAnnotation>(new ODataNavigationLinkAnnotation());
                    ODataEntry entry3 = (ODataEntry)stack.Peek();
                    entry3.GetAnnotation <ODataEntryAnnotation>().Add(link2);
                    stack.Push(link2);
                    break;
                }

                case ODataReaderState.NavigationLinkEnd:
                    stack.Pop();
                    break;

                case ODataReaderState.EntityReferenceLink:
                {
                    ODataEntityReferenceLink link4 = (ODataEntityReferenceLink)odataReader.Item;
                    ODataNavigationLink      link5 = (ODataNavigationLink)stack.Peek();
                    link5.GetAnnotation <ODataNavigationLinkAnnotation>().Add(link4);
                    break;
                }
                }
            }
            return(entry);
        }
Example #21
0
        internal static ODataItem ReadEntryOrFeed(ODataReader odataReader, ODataDeserializerContext readContext)
        {
            ODataItem         topLevelItem = null;
            Stack <ODataItem> itemsStack   = new Stack <ODataItem>();

            while (odataReader.Read())
            {
                switch (odataReader.State)
                {
                case ODataReaderState.EntryStart:
                    ODataEntry           entry           = (ODataEntry)odataReader.Item;
                    ODataEntryAnnotation entryAnnotation = null;
                    if (entry != null)
                    {
                        entryAnnotation = new ODataEntryAnnotation();
                        entry.SetAnnotation(entryAnnotation);
                    }

                    if (itemsStack.Count == 0)
                    {
                        Contract.Assert(entry != null, "The top-level entry can never be null.");
                        topLevelItem = entry;
                    }
                    else
                    {
                        ODataItem parentItem = itemsStack.Peek();
                        ODataFeed parentFeed = parentItem as ODataFeed;
                        if (parentFeed != null)
                        {
                            ODataFeedAnnotation parentFeedAnnotation = parentFeed.GetAnnotation <ODataFeedAnnotation>();
                            Contract.Assert(parentFeedAnnotation != null, "Every feed we added to the stack should have the feed annotation on it.");
                            parentFeedAnnotation.Add(entry);
                        }
                        else
                        {
                            ODataNavigationLink           parentNavigationLink           = (ODataNavigationLink)parentItem;
                            ODataNavigationLinkAnnotation parentNavigationLinkAnnotation = parentNavigationLink.GetAnnotation <ODataNavigationLinkAnnotation>();
                            Contract.Assert(parentNavigationLinkAnnotation != null, "Every navigation link we added to the stack should have the navigation link annotation on it.");

                            Contract.Assert(parentNavigationLink.IsCollection == false, "Only singleton navigation properties can contain entry as their child.");
                            Contract.Assert(parentNavigationLinkAnnotation.Count == 0, "Each navigation property can contain only one entry as its direct child.");
                            parentNavigationLinkAnnotation.Add(entry);
                        }
                    }
                    itemsStack.Push(entry);
                    RecurseEnter(readContext);
                    break;

                case ODataReaderState.EntryEnd:
                    Contract.Assert(itemsStack.Count > 0 && itemsStack.Peek() == odataReader.Item, "The entry which is ending should be on the top of the items stack.");
                    itemsStack.Pop();
                    RecurseLeave(readContext);
                    break;

                case ODataReaderState.NavigationLinkStart:
                    ODataNavigationLink navigationLink = (ODataNavigationLink)odataReader.Item;
                    Contract.Assert(navigationLink != null, "Navigation link should never be null.");

                    navigationLink.SetAnnotation(new ODataNavigationLinkAnnotation());
                    Contract.Assert(itemsStack.Count > 0, "Navigation link can't appear as top-level item.");
                    {
                        ODataEntry           parentEntry           = (ODataEntry)itemsStack.Peek();
                        ODataEntryAnnotation parentEntryAnnotation = parentEntry.GetAnnotation <ODataEntryAnnotation>();
                        Contract.Assert(parentEntryAnnotation != null, "Every entry we added to the stack should have the entry annotation on it.");
                        parentEntryAnnotation.Add(navigationLink);
                    }

                    itemsStack.Push(navigationLink);
                    RecurseEnter(readContext);
                    break;

                case ODataReaderState.NavigationLinkEnd:
                    Contract.Assert(itemsStack.Count > 0 && itemsStack.Peek() == odataReader.Item, "The navigation link which is ending should be on the top of the items stack.");
                    itemsStack.Pop();
                    RecurseLeave(readContext);
                    break;

                case ODataReaderState.FeedStart:
                    ODataFeed feed = (ODataFeed)odataReader.Item;
                    Contract.Assert(feed != null, "Feed should never be null.");

                    feed.SetAnnotation(new ODataFeedAnnotation());
                    if (itemsStack.Count > 0)
                    {
                        ODataNavigationLink parentNavigationLink = (ODataNavigationLink)itemsStack.Peek();
                        Contract.Assert(parentNavigationLink != null, "this has to be an inner feed. inner feeds always have a navigation link.");
                        ODataNavigationLinkAnnotation parentNavigationLinkAnnotation = parentNavigationLink.GetAnnotation <ODataNavigationLinkAnnotation>();
                        Contract.Assert(parentNavigationLinkAnnotation != null, "Every navigation link we added to the stack should have the navigation link annotation on it.");

                        Contract.Assert(parentNavigationLink.IsCollection == true, "Only collection navigation properties can contain feed as their child.");
                        parentNavigationLinkAnnotation.Add(feed);
                    }
                    else
                    {
                        topLevelItem = feed;
                    }

                    itemsStack.Push(feed);
                    RecurseEnter(readContext);
                    break;

                case ODataReaderState.FeedEnd:
                    Contract.Assert(itemsStack.Count > 0 && itemsStack.Peek() == odataReader.Item, "The feed which is ending should be on the top of the items stack.");
                    itemsStack.Pop();
                    RecurseLeave(readContext);
                    break;

                case ODataReaderState.EntityReferenceLink:
                    ODataEntityReferenceLink entityReferenceLink = (ODataEntityReferenceLink)odataReader.Item;
                    Contract.Assert(entityReferenceLink != null, "Entity reference link should never be null.");

                    Contract.Assert(itemsStack.Count > 0, "Entity reference link should never be reported as top-level item.");
                    {
                        ODataNavigationLink           parentNavigationLink           = (ODataNavigationLink)itemsStack.Peek();
                        ODataNavigationLinkAnnotation parentNavigationLinkAnnotation = parentNavigationLink.GetAnnotation <ODataNavigationLinkAnnotation>();
                        Contract.Assert(parentNavigationLinkAnnotation != null, "Every navigation link we added to the stack should have the navigation link annotation on it.");

                        parentNavigationLinkAnnotation.Add(entityReferenceLink);
                    }

                    break;

                default:
                    Contract.Assert(false, "We should never get here, it means the ODataReader reported a wrong state.");
                    break;
                }
            }

            Contract.Assert(odataReader.State == ODataReaderState.Completed, "We should have consumed all of the input by now.");
            Contract.Assert(topLevelItem != null, "A top level entry or feed should have been read by now.");
            return(topLevelItem);
        }
        /// <summary>
        /// Reads a <see cref="ODataResource"/> or <see cref="ODataResourceSet"/> object.
        /// </summary>
        /// <param name="reader">The OData reader to read from.</param>
        /// <returns>The read resource or resource set.</returns>
        public static ODataItemBase ReadResourceOrResourceSet(this ODataReader reader)
        {
            if (reader == null)
            {
                throw Error.ArgumentNull("reader");
            }

            ODataItemBase         topLevelItem = null;
            Stack <ODataItemBase> itemsStack   = new Stack <ODataItemBase>();

            while (reader.Read())
            {
                switch (reader.State)
                {
                case ODataReaderState.ResourceStart:
                    ODataResource        resource        = (ODataResource)reader.Item;
                    ODataResourceWrapper resourceWrapper = null;
                    if (resource != null)
                    {
                        resourceWrapper = new ODataResourceWrapper(resource);
                    }

                    if (itemsStack.Count == 0)
                    {
                        Contract.Assert(resource != null, "The top-level resource can never be null.");
                        topLevelItem = resourceWrapper;
                    }
                    else
                    {
                        ODataItemBase           parentItem        = itemsStack.Peek();
                        ODataResourceSetWrapper parentResourceSet = parentItem as ODataResourceSetWrapper;
                        if (parentResourceSet != null)
                        {
                            parentResourceSet.Resources.Add(resourceWrapper);
                        }
                        else
                        {
                            ODataNestedResourceInfoWrapper parentNestedResource = (ODataNestedResourceInfoWrapper)parentItem;
                            Contract.Assert(parentNestedResource.NestedResourceInfo.IsCollection == false, "Only singleton nested properties can contain resource as their child.");
                            Contract.Assert(parentNestedResource.NestedItems.Count == 0, "Each nested property can contain only one resource as its direct child.");
                            parentNestedResource.NestedItems.Add(resourceWrapper);
                        }
                    }

                    itemsStack.Push(resourceWrapper);
                    break;

                case ODataReaderState.ResourceEnd:
                    Contract.Assert(
                        itemsStack.Count > 0 && (reader.Item == null || itemsStack.Peek().Item == reader.Item),
                        "The resource which is ending should be on the top of the items stack.");
                    itemsStack.Pop();
                    break;

                case ODataReaderState.NestedResourceInfoStart:
                    ODataNestedResourceInfo nestedResourceInfo = (ODataNestedResourceInfo)reader.Item;
                    Contract.Assert(nestedResourceInfo != null, "nested resource info should never be null.");

                    ODataNestedResourceInfoWrapper nestedResourceInfoWrapper = new ODataNestedResourceInfoWrapper(nestedResourceInfo);
                    Contract.Assert(itemsStack.Count > 0, "nested resource info can't appear as top-level item.");
                    {
                        ODataResourceWrapper parentResource = (ODataResourceWrapper)itemsStack.Peek();
                        parentResource.NestedResourceInfos.Add(nestedResourceInfoWrapper);
                    }

                    itemsStack.Push(nestedResourceInfoWrapper);
                    break;

                case ODataReaderState.NestedResourceInfoEnd:
                    Contract.Assert(itemsStack.Count > 0 && itemsStack.Peek().Item == reader.Item,
                                    "The nested resource info which is ending should be on the top of the items stack.");
                    itemsStack.Pop();
                    break;

                case ODataReaderState.ResourceSetStart:
                    ODataResourceSet resourceSet = (ODataResourceSet)reader.Item;
                    Contract.Assert(resourceSet != null, "ResourceSet should never be null.");

                    ODataResourceSetWrapper resourceSetWrapper = new ODataResourceSetWrapper(resourceSet);
                    if (itemsStack.Count > 0)
                    {
                        ODataNestedResourceInfoWrapper parentNestedResourceInfo = (ODataNestedResourceInfoWrapper)itemsStack.Peek();
                        Contract.Assert(parentNestedResourceInfo != null, "this has to be an inner resource set. inner resource sets always have a nested resource info.");
                        Contract.Assert(parentNestedResourceInfo.NestedResourceInfo.IsCollection == true, "Only collection nested properties can contain resource set as their child.");
                        parentNestedResourceInfo.NestedItems.Add(resourceSetWrapper);
                    }
                    else
                    {
                        topLevelItem = resourceSetWrapper;
                    }

                    itemsStack.Push(resourceSetWrapper);
                    break;

                case ODataReaderState.ResourceSetEnd:
                    Contract.Assert(itemsStack.Count > 0 && itemsStack.Peek().Item == reader.Item, "The resource set which is ending should be on the top of the items stack.");
                    itemsStack.Pop();
                    break;

                case ODataReaderState.EntityReferenceLink:
                    ODataEntityReferenceLink entityReferenceLink = (ODataEntityReferenceLink)reader.Item;
                    Contract.Assert(entityReferenceLink != null, "Entity reference link should never be null.");
                    ODataEntityReferenceLinkBase entityReferenceLinkWrapper = new ODataEntityReferenceLinkBase(entityReferenceLink);

                    Contract.Assert(itemsStack.Count > 0, "Entity reference link should never be reported as top-level item.");
                    {
                        ODataNestedResourceInfoWrapper parentNavigationLink = (ODataNestedResourceInfoWrapper)itemsStack.Peek();
                        parentNavigationLink.NestedItems.Add(entityReferenceLinkWrapper);
                    }

                    break;

                default:
                    Contract.Assert(false, "We should never get here, it means the ODataReader reported a wrong state.");
                    break;
                }
            }

            Contract.Assert(reader.State == ODataReaderState.Completed, "We should have consumed all of the input by now.");
            Contract.Assert(topLevelItem != null, "A top level resource or resource set should have been read by now.");
            return(topLevelItem);
        }
Example #23
0
        /// <summary>
        /// Reads an entry from the <paramref name="odataReader"/> and all it's children including expanded entries and feeds.
        /// </summary>
        /// <param name="odataReader">The ODataReader to read from.</param>
        /// <param name="topLevelSegmentInfo">The segment info for the top-level entry to read.</param>
        /// <returns>The <see cref="ODataEntry"/> with annotations which store the navigation links and their expanded values.</returns>
        private ODataEntry ReadEntry(ODataReader odataReader, SegmentInfo topLevelSegmentInfo)
        {
            Debug.Assert(odataReader != null, "odataReader != null");
            Debug.Assert(odataReader.State == ODataReaderState.Start, "The ODataReader must not have been used yet.");
            Debug.Assert(topLevelSegmentInfo != null, "topLevelSegmentInfo != null");

            ODataEntry        topLevelEntry = null;
            Stack <ODataItem> itemsStack    = new Stack <ODataItem>();

            while (odataReader.Read())
            {
                // Don't let the item stack grow larger than we can process later. Also lets us to fail and report the recursion depth limit error before ODL does.
                if (itemsStack.Count >= RecursionLimit)
                {
                    throw DataServiceException.CreateDeepRecursion(RecursionLimit);
                }

                switch (odataReader.State)
                {
                case ODataReaderState.EntryStart:
                    ODataEntry           entry           = (ODataEntry)odataReader.Item;
                    ODataEntryAnnotation entryAnnotation = null;
                    if (entry != null)
                    {
                        entryAnnotation = new ODataEntryAnnotation();
                        entry.SetAnnotation(entryAnnotation);
                    }

                    if (itemsStack.Count == 0)
                    {
                        Debug.Assert(entry != null, "The top-level entry can never be null.");
                        topLevelEntry = entry;

                        // For top-level entry, create the entry resource here.
                        // This is needed since the creation of the resource may fail (especially if this is an update in which case
                        // we evaluate the URL query, which may return no results and thus we would fail with 404)
                        // and we need to report that failure rather then potential other failures caused by the properties in the entry in question.
                        this.CreateEntityResource(topLevelSegmentInfo, entry, entryAnnotation, /*topLevel*/ true);
                    }
                    else
                    {
                        ODataItem parentItem = itemsStack.Peek();
                        ODataFeed parentFeed = parentItem as ODataFeed;
                        if (parentFeed != null)
                        {
                            ODataFeedAnnotation parentFeedAnnotation = parentFeed.GetAnnotation <ODataFeedAnnotation>();
                            Debug.Assert(parentFeedAnnotation != null, "Every feed we added to the stack should have the feed annotation on it.");
                            parentFeedAnnotation.Add(entry);
                        }
                        else
                        {
                            ODataNavigationLink           parentNavigationLink           = (ODataNavigationLink)parentItem;
                            ODataNavigationLinkAnnotation parentNavigationLinkAnnotation = parentNavigationLink.GetAnnotation <ODataNavigationLinkAnnotation>();
                            Debug.Assert(parentNavigationLinkAnnotation != null, "Every navigation link we added to the stack should have the navigation link annotation on it.");

                            Debug.Assert(parentNavigationLink.IsCollection == false, "Only singleton navigation properties can contain entry as their child.");
                            Debug.Assert(parentNavigationLinkAnnotation.Count == 0, "Each navigation property can contain only one entry as its direct child.");
                            parentNavigationLinkAnnotation.Add(entry);
                        }
                    }

                    itemsStack.Push(entry);
                    break;

                case ODataReaderState.EntryEnd:
                    Debug.Assert(itemsStack.Count > 0 && itemsStack.Peek() == odataReader.Item, "The entry which is ending should be on the top of the items stack.");
                    itemsStack.Pop();
                    break;

                case ODataReaderState.NavigationLinkStart:
                    ODataNavigationLink navigationLink = (ODataNavigationLink)odataReader.Item;
                    Debug.Assert(navigationLink != null, "Navigation link should never be null.");

                    navigationLink.SetAnnotation(new ODataNavigationLinkAnnotation());
                    Debug.Assert(itemsStack.Count > 0, "Navigation link can't appear as top-level item.");
                    {
                        ODataEntry           parentEntry           = (ODataEntry)itemsStack.Peek();
                        ODataEntryAnnotation parentEntryAnnotation = parentEntry.GetAnnotation <ODataEntryAnnotation>();
                        Debug.Assert(parentEntryAnnotation != null, "Every entry we added to the stack should have the navigation link annotation on it.");
                        parentEntryAnnotation.Add(navigationLink);
                    }

                    itemsStack.Push(navigationLink);
                    break;

                case ODataReaderState.NavigationLinkEnd:
                    Debug.Assert(itemsStack.Count > 0 && itemsStack.Peek() == odataReader.Item, "The navigation link which is ending should be on the top of the items stack.");
                    itemsStack.Pop();
                    break;

                case ODataReaderState.FeedStart:
                    ODataFeed feed = (ODataFeed)odataReader.Item;
                    Debug.Assert(feed != null, "Feed should never be null.");

                    feed.SetAnnotation(new ODataFeedAnnotation());
                    Debug.Assert(itemsStack.Count > 0, "Since we always start reading entry, we should never get a feed as the top-level item.");
                    {
                        ODataNavigationLink           parentNavigationLink           = (ODataNavigationLink)itemsStack.Peek();
                        ODataNavigationLinkAnnotation parentNavigationLinkAnnotation = parentNavigationLink.GetAnnotation <ODataNavigationLinkAnnotation>();
                        Debug.Assert(parentNavigationLinkAnnotation != null, "Every navigation link we added to the stack should have the navigation link annotation on it.");

                        Debug.Assert(parentNavigationLink.IsCollection == true, "Only collection navigation properties can contain feed as their child.");
                        parentNavigationLinkAnnotation.Add(feed);
                    }

                    itemsStack.Push(feed);
                    break;

                case ODataReaderState.FeedEnd:
                    Debug.Assert(itemsStack.Count > 0 && itemsStack.Peek() == odataReader.Item, "The feed which is ending should be on the top of the items stack.");
                    itemsStack.Pop();
                    break;

                case ODataReaderState.EntityReferenceLink:
                    ODataEntityReferenceLink entityReferenceLink = (ODataEntityReferenceLink)odataReader.Item;
                    Debug.Assert(entityReferenceLink != null, "Entity reference link should never be null.");

                    Debug.Assert(itemsStack.Count > 0, "Entity reference link should never be reported as top-level item.");
                    {
                        ODataNavigationLink           parentNavigationLink           = (ODataNavigationLink)itemsStack.Peek();
                        ODataNavigationLinkAnnotation parentNavigationLinkAnnotation = parentNavigationLink.GetAnnotation <ODataNavigationLinkAnnotation>();
                        Debug.Assert(parentNavigationLinkAnnotation != null, "Every navigation link we added to the stack should have the navigation link annotation on it.");

                        parentNavigationLinkAnnotation.Add(entityReferenceLink);
                    }

                    break;

                default:
                    Debug.Assert(false, "We should never get here, it means the ODataReader reported a wrong state.");
                    break;
                }
            }

            Debug.Assert(odataReader.State == ODataReaderState.Completed, "We should have consumed all of the input by now.");
            Debug.Assert(topLevelEntry != null, "A top level entry should have been read by now.");
            return(topLevelEntry);
        }
Example #24
0
        public void ExecuteBaseballStatsRequest(IEdmModel model, string fileName)
        {
            //we are going to create a GET request to the OData Netflix Catalog
            HTTPClientRequestMessage message = new HTTPClientRequestMessage("http://baseball-stats.info/OData/baseballstats.svc/");

            message.SetHeader("Accept", "application/atom+xml");
            message.SetHeader("DataServiceVersion", ODataUtils.ODataVersionToString(ODataVersion.V2));
            message.SetHeader("MaxDataServiceVersion", ODataUtils.ODataVersionToString(ODataVersion.V2));

            //create a simple text file to write the response to and create a text writer
            string filePath = @".\out\" + fileName + ".txt";

            using (StreamWriter outputWriter = new StreamWriter(filePath))
            {
                //use an indented text writer for readability
                this.writer = new IndentedTextWriter(outputWriter, "  ");

                //issue the request and get the response as an ODataMessage. Create an ODataMessageReader over the response
                //we will use the model when creating the reader as this will tell the library to validate when parsing
                using (ODataMessageReader messageReader = new ODataMessageReader(message.GetResponse(),
                                                                                 new ODataMessageReaderSettings(), model))
                {
                    //create a feed reader
                    ODataReader reader = messageReader.CreateODataFeedReader();
                    while (reader.Read())
                    {
                        switch (reader.State)
                        {
                        case ODataReaderState.FeedStart:
                        {
                            //this is just the beginning of the feed, data will not be parsed yet
                            ODataFeed feed = (ODataFeed)reader.Item;
                            this.writer.WriteLine("ODataFeed:");
                            this.writer.Indent++;
                        }

                        break;

                        case ODataReaderState.FeedEnd:
                        {
                            //this is the end of feed state. The entire message has been read at this point
                            ODataFeed feed = (ODataFeed)reader.Item;
                            if (feed.Count != null)
                            {
                                //if there is an inlinecount value write the value out
                                this.writer.WriteLine("Count: " + feed.Count.ToString());
                            }
                            if (feed.NextPageLink != null)
                            {
                                //if there is a next link write that link as well
                                this.writer.WriteLine("NextPageLink: " + feed.NextPageLink.AbsoluteUri);
                            }

                            this.writer.Indent--;
                        }

                        break;

                        case ODataReaderState.EntryStart:
                        {
                            //this is just the start of the entry.
                            //Properties of the entity will not be parsed yet
                            ODataEntry entry = (ODataEntry)reader.Item;
                            this.writer.WriteLine("ODataEntry:");
                            this.writer.Indent++;
                        }

                        break;

                        case ODataReaderState.EntryEnd:
                        {
                            //at the point the whole entry has been read
                            //and the properties of the entity are available
                            ODataEntry entry = (ODataEntry)reader.Item;
                            this.writer.WriteLine("TypeName: " + (entry.TypeName ?? "<null>"));
                            this.writer.WriteLine("Id: " + (entry.Id ?? "<null>"));
                            if (entry.ReadLink != null)
                            {
                                this.writer.WriteLine("ReadLink: " + entry.ReadLink.AbsoluteUri);
                            }

                            if (entry.EditLink != null)
                            {
                                this.writer.WriteLine("EditLink: " + entry.EditLink.AbsoluteUri);
                            }

                            if (entry.MediaResource != null)
                            {
                                this.writer.Write("MediaResource: ");
                                this.WriteValue(entry.MediaResource);
                            }

                            this.WriteProperties(entry.Properties);

                            this.writer.Indent--;
                        }

                        break;

                        case ODataReaderState.NavigationLinkStart:
                        {
                            //navigation links have their own states.
                            //This could be an expanded link and include an entire expanded entry or feed.
                            ODataNavigationLink navigationLink = (ODataNavigationLink)reader.Item;
                            this.writer.WriteLine(navigationLink.Name + ": ODataNavigationLink: ");
                            this.writer.Indent++;
                        }

                        break;

                        case ODataReaderState.NavigationLinkEnd:
                        {
                            ODataNavigationLink navigationLink = (ODataNavigationLink)reader.Item;
                            this.writer.WriteLine("Url: " +
                                                  (navigationLink.Url == null ? "<null>" : navigationLink.Url.AbsoluteUri));
                            this.writer.Indent--;
                        }

                        break;
                        }
                    }
                }
            }
        }