/// <summary> /// Instantiates a new Serializer class and calls WriteEntry method on it. /// </summary> /// <param name="dataServiceContext"></param> /// <returns></returns> private static Person SetupSerializerAndCallWriteEntry(DataServiceContext dataServiceContext) { Person person = new Person(); Address address = new Address(); Car car1 = new Car(); person.Cars.Add(car1); person.HomeAddress = address; dataServiceContext.AttachTo("Cars", car1); dataServiceContext.AttachTo("Addresses", address); var requestInfo = new RequestInfo(dataServiceContext); var serializer = new Serializer(requestInfo); var headers = new HeaderCollection(); var clientModel = new ClientEdmModel(ODataProtocolVersion.V4); var entityDescriptor = new EntityDescriptor(clientModel); entityDescriptor.State = EntityStates.Added; entityDescriptor.Entity = person; var requestMessageArgs = new BuildingRequestEventArgs("POST", new Uri("http://www.foo.com/Northwind"), headers, entityDescriptor, HttpStack.Auto); var linkDescriptors = new LinkDescriptor[] { new LinkDescriptor(person, "Cars", car1, clientModel), new LinkDescriptor(person, "HomeAddress", address, clientModel) }; var odataRequestMessageWrapper = ODataRequestMessageWrapper.CreateRequestMessageWrapper(requestMessageArgs, requestInfo); serializer.WriteEntry(entityDescriptor, linkDescriptors, odataRequestMessageWrapper); return person; }
internal BaseSaveResult(DataServiceContext context, string method, DataServiceRequest[] queries, SaveChangesOptions options, AsyncCallback callback, object state) : base(context, method, callback, state) { this.RequestInfo = new RequestInfo(context); this.Options = options; this.SerializerInstance = new Serializer(this.RequestInfo, options); if (null == queries) { #region changed entries this.ChangedEntries = context.EntityTracker.Entities.Cast<Descriptor>() .Union(context.EntityTracker.Links.Cast<Descriptor>()) .Union(context.EntityTracker.Entities.SelectMany(e => e.StreamDescriptors).Cast<Descriptor>()) .Where(o => o.IsModified && o.ChangeOrder != UInt32.MaxValue) .OrderBy(o => o.ChangeOrder) .ToList(); foreach (Descriptor e in this.ChangedEntries) { e.ContentGeneratedForSave = false; e.SaveResultWasProcessed = 0; e.SaveError = null; if (e.DescriptorKind == DescriptorKind.Link) { object target = ((LinkDescriptor)e).Target; if (null != target) { Descriptor f = context.EntityTracker.GetEntityDescriptor(target); if (EntityStates.Unchanged == f.State) { f.ContentGeneratedForSave = false; f.SaveResultWasProcessed = 0; f.SaveError = null; } } } } #endregion } else { this.ChangedEntries = new List<Descriptor>(); } }
/// <summary> /// Gets the string of keys used in URI. /// </summary> /// <param name="context">Wrapping context instance.</param> /// <param name="keys">The dictionary containing key pairs.</param> /// <returns>The string of keys.</returns> public static string GetKeyString(DataServiceContext context, Dictionary<string, object> keys) { var requestInfo = new RequestInfo(context); var serializer = new Serializer(requestInfo); if (keys.Count == 1) { return serializer.ConvertToEscapedUriValue(keys.First().Key, keys.First().Value); } else { StringBuilder stringBuilder = new StringBuilder(); foreach (var keyPair in keys) { stringBuilder.Append(keyPair.Key); stringBuilder.Append(UriHelper.EQUALSSIGN); stringBuilder.Append(serializer.ConvertToEscapedUriValue(keyPair.Key, keyPair.Value)); stringBuilder.Append(UriHelper.COMMA); } stringBuilder.Remove(stringBuilder.Length - 1, 1); return stringBuilder.ToString(); } }
/// <summary> /// Seriliaze the parameter value to string. /// </summary> /// <param name="context">The context.</param> /// <param name="parameter">The parameter.</param> /// <returns>Parameter value string.</returns> internal static string GetParameterValue(DataServiceContext context, OperationParameter parameter) { var requestInfo = new RequestInfo(context); var serializer = new Serializer(requestInfo); UriEntityOperationParameter entityParameter = parameter as UriEntityOperationParameter; return serializer.ConvertToEscapedUriValue(parameter.Name, parameter.Value, entityParameter != null && entityParameter.UseEntityReference); }
/// <summary> /// Gets the string of parameters used in URI. /// </summary> /// <param name="context">Wrapping context instance.</param> /// <param name="parameters">Parameters of function.</param> /// <returns>The string of parameters.</returns> public static string GetParameterString(DataServiceContext context, params OperationParameter[] parameters) { var requestInfo = new RequestInfo(context); var serializer = new Serializer(requestInfo); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(UriHelper.LEFTPAREN); foreach (var key in parameters) { stringBuilder.Append(key.Name); stringBuilder.Append(UriHelper.EQUALSSIGN); stringBuilder.Append(serializer.ConvertToEscapedUriValue(key.Name, key.Value)); stringBuilder.Append(UriHelper.COMMA); } if (parameters.Any()) { stringBuilder.Remove(stringBuilder.Length - 1, 1); } stringBuilder.Append(UriHelper.RIGHTPAREN); return stringBuilder.ToString(); }
public void SerializeEnity_NullableEnumProperty() { MyEntity1 myEntity1 = new MyEntity1() { ID = 2, MyColorValue = null, MyFlagsColorValue = MyFlagsColor.Blue, ComplexValue1Value = new ComplexValue1() { MyColorValue = MyColor.Green, MyFlagsColorValue = MyFlagsColor.Red }, MyFlagsColorCollection1 = new List<MyFlagsColor>() { MyFlagsColor.Blue, MyFlagsColor.Red, MyFlagsColor.Red }, MyColorCollection = new List<MyColor?> { MyColor.Green, null } }; DataServiceContext dataServiceContext = new DataServiceContext(new Uri("http://www.odata.org/service.svc")); dataServiceContext.EnableAtom = true; dataServiceContext.Format.UseAtom(); dataServiceContext.AttachTo("MyEntitySet1", myEntity1); var requestInfo = new RequestInfo(dataServiceContext); var serializer = new Serializer(requestInfo); var headers = new HeaderCollection(); var clientModel = new ClientEdmModel(ODataProtocolVersion.V4); var entityDescriptor = new EntityDescriptor(clientModel); entityDescriptor.State = EntityStates.Added; entityDescriptor.Entity = myEntity1; var requestMessageArgs = new BuildingRequestEventArgs("POST", new Uri("http://www.foo.com/Northwind"), headers, entityDescriptor, HttpStack.Auto); var linkDescriptors = new LinkDescriptor[] { }; var odataRequestMessageWrapper = ODataRequestMessageWrapper.CreateRequestMessageWrapper(requestMessageArgs, requestInfo); serializer.WriteEntry(entityDescriptor, linkDescriptors, odataRequestMessageWrapper); // read result: MemoryStream stream = (MemoryStream)(odataRequestMessageWrapper.CachedRequestStream.Stream); stream.Position = 0; string payload = (new StreamReader(stream)).ReadToEnd(); payload = Regex.Replace(payload, "<updated>[^<]*</updated>", ""); payload.Should().Be( "{\"ComplexValue1Value\":{\"MyColorValue\":\"Green\",\"MyFlagsColorValue\":\"Red\",\"StringValue\":null},\"ID\":2,\"MyColorCollection\":[\"Green\",null],\"MyColorValue\":null,\"MyFlagsColorCollection1\":[\"Blue\",\"Red\",\"Red\"],\"MyFlagsColorValue\":\"Blue\"}"); }
public void SerializeEnity_EnumProperty() { MyEntity1 myEntity1 = new MyEntity1() { ID = 2, MyColorValue = MyColor.Yellow, MyFlagsColorValue = MyFlagsColor.Blue, ComplexValue1Value = new ComplexValue1() { MyColorValue = MyColor.Green, MyFlagsColorValue = MyFlagsColor.Red }, MyFlagsColorCollection1 = new List<MyFlagsColor>() { MyFlagsColor.Blue, MyFlagsColor.Red, MyFlagsColor.Red }, MyColorCollection = new List<MyColor?>() }; DataServiceContext dataServiceContext = new DataServiceContext(new Uri("http://www.odata.org/service.svc")); dataServiceContext.EnableAtom = true; dataServiceContext.Format.UseAtom(); dataServiceContext.AttachTo("MyEntitySet1", myEntity1); var requestInfo = new RequestInfo(dataServiceContext); var serializer = new Serializer(requestInfo); var headers = new HeaderCollection(); headers.SetHeader("Content-Type", "application/atom+xml;odata.metadata=minimal"); var clientModel = new ClientEdmModel(ODataProtocolVersion.V4); var entityDescriptor = new EntityDescriptor(clientModel); entityDescriptor.State = EntityStates.Added; entityDescriptor.Entity = myEntity1; var requestMessageArgs = new BuildingRequestEventArgs("POST", new Uri("http://www.foo.com/Northwind"), headers, entityDescriptor, HttpStack.Auto); var linkDescriptors = new LinkDescriptor[] { }; var odataRequestMessageWrapper = ODataRequestMessageWrapper.CreateRequestMessageWrapper(requestMessageArgs, requestInfo); serializer.WriteEntry(entityDescriptor, linkDescriptors, odataRequestMessageWrapper); // read result: MemoryStream stream = (MemoryStream)(odataRequestMessageWrapper.CachedRequestStream.Stream); stream.Position = 0; string payload = (new StreamReader(stream)).ReadToEnd(); payload = Regex.Replace(payload, "<updated>[^<]*</updated>", ""); payload.Should().Be( "<?xml version=\"1.0\" encoding=\"utf-8\"?><entry xmlns=\"http://www.w3.org/2005/Atom\" " + "xmlns:d=\"http://docs.oasis-open.org/odata/ns/data\" xmlns:m=\"http://docs.oasis-open.org/odata/ns/metadata\" " + "xmlns:georss=\"http://www.georss.org/georss\" xmlns:gml=\"http://www.opengis.net/gml\">" + "<id />" + "<title />" + //"<updated>2013-11-11T19:29:54Z</updated>" + "<author><name /></author>" + "<content type=\"application/xml\">" + "<m:properties>" + "<d:ComplexValue1Value>" + "<d:MyColorValue m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests_MyColor\">Green</d:MyColorValue>" + "<d:MyFlagsColorValue m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests_MyFlagsColor\">Red</d:MyFlagsColorValue>" + "<d:StringValue m:null=\"true\" />" + "</d:ComplexValue1Value>" + "<d:ID m:type=\"Int64\">2</d:ID>" + "<d:MyColorCollection />" + "<d:MyColorValue m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests_MyColor\">Yellow</d:MyColorValue>" + "<d:MyFlagsColorCollection1>" + "<m:element m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests+MyFlagsColor\">Blue</m:element>" + "<m:element m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests+MyFlagsColor\">Red</m:element>" + "<m:element m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests+MyFlagsColor\">Red</m:element>" + "</d:MyFlagsColorCollection1>" + "<d:MyFlagsColorValue m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests_MyFlagsColor\">Blue</d:MyFlagsColorValue>" + "</m:properties>" + "</content>" + "</entry>"); }
public void SerializeEnity_TwoNavigationLinksInJsonFormat() { var person = new Person { ID = 100, Name = "Bing", }; var car1 = new Car { ID = 1001 }; var car2 = new Car { ID = 1002 }; DataServiceContext dataServiceContext = new DataServiceContext(new Uri("http://www.odata.org/service.svc")); dataServiceContext.AttachTo("Persons", person); dataServiceContext.AttachTo("Cars", car1); dataServiceContext.AttachTo("Cars", car2); dataServiceContext.AddLink(person, "Cars", car1); dataServiceContext.AddLink(person, "Cars", car2); var requestInfo = new RequestInfo(dataServiceContext); var serializer = new Serializer(requestInfo); var headers = new HeaderCollection(); var clientModel = new ClientEdmModel(ODataProtocolVersion.V4); var entityDescriptor = new EntityDescriptor(clientModel); entityDescriptor.State = EntityStates.Added; entityDescriptor.Entity = person; entityDescriptor.EditLink = new Uri("http://www.foo.com/custom"); var requestMessageArgs = new BuildingRequestEventArgs("POST", new Uri("http://www.foo.com/Northwind"), headers, entityDescriptor, HttpStack.Auto); var linkDescriptors = new LinkDescriptor[] { new LinkDescriptor(person, "Cars", car1, clientModel), new LinkDescriptor(person, "Cars", car2, clientModel)}; var odataRequestMessageWrapper = ODataRequestMessageWrapper.CreateRequestMessageWrapper(requestMessageArgs, requestInfo); serializer.WriteEntry(entityDescriptor, linkDescriptors, odataRequestMessageWrapper); // read result: MemoryStream stream = (MemoryStream)(odataRequestMessageWrapper.CachedRequestStream.Stream); stream.Position = 0; string payload = (new StreamReader(stream)).ReadToEnd(); payload.Should().Be( "{\"ID\":100,\"Name\":\"Bing\",\"[email protected]\":[\"http://www.odata.org/service.svc/Cars(1001)\",\"http://www.odata.org/service.svc/Cars(1002)\"]}"); }
/// <summary> /// Generate the batch request for all changes to save. /// </summary> /// <returns>Returns the instance of ODataRequestMessage containing all the headers and payload for the batch request.</returns> private ODataRequestMessageWrapper GenerateBatchRequest() { if (this.ChangedEntries.Count == 0 && this.Queries == null) { this.SetCompleted(); return(null); } ODataRequestMessageWrapper batchRequestMessage = this.CreateBatchRequest(); // we need to fire request after the headers have been written, but before we write the payload batchRequestMessage.FireSendingRequest2(null); using (ODataMessageWriter messageWriter = Serializer.CreateMessageWriter(batchRequestMessage, this.RequestInfo, false /*isParameterPayload*/)) { this.batchWriter = messageWriter.CreateODataBatchWriter(); this.batchWriter.WriteStartBatch(); if (this.Queries != null) { foreach (DataServiceRequest query in this.Queries) { QueryComponents queryComponents = query.QueryComponents(this.RequestInfo.Model); Uri requestUri = this.RequestInfo.BaseUriResolver.GetOrCreateAbsoluteUri(queryComponents.Uri); Debug.Assert(requestUri != null, "request uri is null"); Debug.Assert(requestUri.IsAbsoluteUri, "request uri is not absolute uri"); HeaderCollection headers = new HeaderCollection(); headers.SetRequestVersion(queryComponents.Version, this.RequestInfo.MaxProtocolVersionAsVersion); this.RequestInfo.Format.SetRequestAcceptHeaderForQuery(headers, queryComponents); ODataRequestMessageWrapper batchOperationRequestMessage = this.CreateRequestMessage(XmlConstants.HttpMethodGet, requestUri, headers, this.RequestInfo.HttpStack, null /*descriptor*/, null /*contentId*/); batchOperationRequestMessage.FireSendingEventHandlers(null /*descriptor*/); } } else if (0 < this.ChangedEntries.Count) { if (Util.IsBatchWithSingleChangeset(this.Options)) { this.batchWriter.WriteStartChangeset(); } var model = this.RequestInfo.Model; for (int i = 0; i < this.ChangedEntries.Count; ++i) { if (Util.IsBatchWithIndependentOperations(this.Options)) { this.batchWriter.WriteStartChangeset(); } Descriptor descriptor = this.ChangedEntries[i]; if (descriptor.ContentGeneratedForSave) { continue; } EntityDescriptor entityDescriptor = descriptor as EntityDescriptor; if (descriptor.DescriptorKind == DescriptorKind.Entity) { if (entityDescriptor.State == EntityStates.Added) { // We don't support adding MLE/MR in batch mode ClientTypeAnnotation type = model.GetClientTypeAnnotation(model.GetOrCreateEdmType(entityDescriptor.Entity.GetType())); if (type.IsMediaLinkEntry || entityDescriptor.IsMediaLinkEntry) { throw Error.NotSupported(Strings.Context_BatchNotSupportedForMediaLink); } } else if (entityDescriptor.State == EntityStates.Unchanged || entityDescriptor.State == EntityStates.Modified) { // We don't support PUT for the MR in batch mode // It's OK to PUT the MLE alone inside a batch mode though if (entityDescriptor.SaveStream != null) { throw Error.NotSupported(Strings.Context_BatchNotSupportedForMediaLink); } } } else if (descriptor.DescriptorKind == DescriptorKind.NamedStream) { // Similar to MR, we do not support adding named streams in batch mode. throw Error.NotSupported(Strings.Context_BatchNotSupportedForNamedStreams); } ODataRequestMessageWrapper operationRequestMessage; if (descriptor.DescriptorKind == DescriptorKind.Entity) { operationRequestMessage = this.CreateRequest(entityDescriptor); } else { operationRequestMessage = this.CreateRequest((LinkDescriptor)descriptor); } // we need to fire request after the headers have been written, but before we write the payload operationRequestMessage.FireSendingRequest2(descriptor); this.CreateChangeData(i, operationRequestMessage); if (Util.IsBatchWithIndependentOperations(this.Options)) { this.batchWriter.WriteEndChangeset(); } } if (Util.IsBatchWithSingleChangeset(this.Options)) { this.batchWriter.WriteEndChangeset(); } } this.batchWriter.WriteEndBatch(); this.batchWriter.Flush(); } Debug.Assert(this.ChangedEntries.All(o => o.ContentGeneratedForSave), "didn't generated content for all entities/links"); return(batchRequestMessage); }