void VerifyResult(string[] inputText, string expectedResult, EdmxTarget target, Action <IEdmModel> visitModel) { IEdmModel model; IEnumerable <EdmError> errors; List <XmlReader> readers = new List <XmlReader>(); foreach (string s in inputText) { readers.Add(XmlReader.Create(new StringReader(s))); } bool parsed = CsdlReader.TryParse(readers, out model, out errors); Assert.IsTrue(parsed, "Model Parsed"); Assert.IsTrue(errors.Count() == 0, "No Errors"); if (visitModel != null) { visitModel(model); } StringWriter sw = new StringWriter(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.Encoding = System.Text.Encoding.UTF8; XmlWriter xw = XmlWriter.Create(sw, settings); EdmxWriter.TryWriteEdmx(model, xw, target, out errors); xw.Flush(); xw.Close(); string outputText = sw.ToString(); Assert.AreEqual(expectedResult, outputText, "Expected Result = Output"); }
public void FindVocabularyAnnotationInParallel() { int annotationCount = 30; var edmModel = new EdmParModel().Model as EdmModel; var container = edmModel.EntityContainer; for (int i = 0; i < annotationCount; i++) { EdmTerm term = new EdmTerm("NS", "Test" + i, EdmPrimitiveTypeKind.String); EdmVocabularyAnnotation annotation = new EdmAnnotation( container, term, new EdmStringConstant("desc" + i)); edmModel.AddVocabularyAnnotation(annotation); } IEdmModel loadedEdmModel = null; using (var ms = new MemoryStream()) { var xw = XmlWriter.Create(ms, new XmlWriterSettings { Indent = true }); IEnumerable <EdmError> errors; var res = EdmxWriter.TryWriteEdmx(edmModel, xw, EdmxTarget.OData, out errors); xw.Flush(); ms.Flush(); ms.Seek(0, SeekOrigin.Begin); using (var sr = new StreamReader(ms)) { var metadata = sr.ReadToEnd(); loadedEdmModel = EdmxReader.Parse(XmlReader.Create(new MemoryStream(Encoding.UTF8.GetBytes(metadata)))); } } container = loadedEdmModel.EntityContainer; int errorCount = 0; int totalAnnotationCount = 0; int taskCount = 100; Parallel.ForEach( Enumerable.Range(0, taskCount), index => { try { var count = loadedEdmModel.FindVocabularyAnnotations(container).ToList().Count(); Interlocked.Add(ref totalAnnotationCount, count); } catch (Exception ew) { Console.WriteLine(ew); Interlocked.Increment(ref errorCount); } }); Assert.AreEqual(0, errorCount); Assert.AreEqual(taskCount * annotationCount, totalAnnotationCount); }
private static void ShowModel(IEdmModel model) { IEnumerable <EdmError> errors; var writer = XmlWriter.Create(Console.Out, new XmlWriterSettings { Indent = true }); EdmxWriter.TryWriteEdmx(model, writer, EdmxTarget.OData, out errors); writer.Flush(); Console.WriteLine(); foreach (var edmError in errors) { Console.WriteLine(edmError); } /* * model.Validate(out errors); * foreach (var edmError in errors) * { * Console.WriteLine(edmError); * } */ }
/// <summary> /// Returns the payload to be used for this test case and the specified test configuration. /// </summary> /// <param name="testConfiguration">The test configuration to use.</param> /// <returns>The payload to use for testing.</returns> private byte[] GetPayload(ReaderTestConfiguration testConfiguration) { if (testConfiguration.Format != null && testConfiguration.Format != ODataFormat.Metadata) { // NOTE: metadata reading is not supported in other formats; return an empty payload for error tests return(new byte[0]); } TestStream testStream = new TestStream(new MemoryStream(), ignoreDispose: true); if (this.PayloadEdmModel != null) { using (XmlWriter xmlWriter = XmlWriter.Create(testStream)) { IEnumerable <EdmError> errors; if (!EdmxWriter.TryWriteEdmx(this.PayloadEdmModel, xmlWriter, EdmxTarget.OData, out errors)) { var errorBuilder = new StringBuilder(); foreach (var error in errors) { errorBuilder.AppendLine(error.ToString()); } throw new Exception("TryWriteEdmx Error:" + errorBuilder); } } } byte[] payload = new byte[testStream.Length]; testStream.Seek(0, SeekOrigin.Begin); testStream.Read(payload, 0, (int)testStream.Length); return(payload); }
/// <summary> /// Writes the metadata document as the message body. /// </summary> /// <remarks>It is the responsibility of this method to flush the output before the method returns.</remarks> internal override void WriteMetadataDocument() { DebugUtils.CheckNoExternalCallers(); this.AssertSynchronous(); // Save the in-memory OData annotations to the model (i.e., turn them into serializable ones) this.Model.SaveODataAnnotations(); IEnumerable <EdmError> errors; if (!EdmxWriter.TryWriteEdmx(this.Model, this.xmlWriter, EdmxTarget.OData, out errors)) { Debug.Assert(errors != null, "errors != null"); StringBuilder builder = new StringBuilder(); foreach (EdmError error in errors) { builder.AppendLine(error.ToString()); } throw new ODataException(Strings.ODataMetadataOutputContext_ErrorWritingMetadata(builder.ToString())); } this.Flush(); }
private void WriteMetadata(TextWriter writer, IEdmModel model) { using (var xmlWriter = XmlWriter.Create(writer)) { IEnumerable <EdmError> errors; EdmxWriter.TryWriteEdmx(model, xmlWriter, EdmxTarget.OData, out errors); } }
private static void ReferentialConstraintDemo() { EdmModel model = new EdmModel(); var customer = new EdmEntityType("ns", "Customer"); model.AddElement(customer); var customerId = customer.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32, false); customer.AddKeys(customerId); var address = new EdmComplexType("ns", "Address"); model.AddElement(address); var code = address.AddStructuralProperty("gid", EdmPrimitiveTypeKind.Guid); customer.AddStructuralProperty("addr", new EdmComplexTypeReference(address, true)); var order = new EdmEntityType("ns", "Order"); model.AddElement(order); var oId = order.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32, false); order.AddKeys(oId); var orderCustomerId = order.AddStructuralProperty("CustomerId", EdmPrimitiveTypeKind.Int32, false); var nav = new EdmNavigationPropertyInfo() { Name = "NavCustomer", Target = customer, TargetMultiplicity = EdmMultiplicity.One, DependentProperties = new[] { orderCustomerId }, PrincipalProperties = new[] { customerId } }; order.AddUnidirectionalNavigation(nav); IEnumerable <EdmError> errors; var writer = XmlWriter.Create(Console.Out, new XmlWriterSettings { Indent = true }); EdmxWriter.TryWriteEdmx(model, writer, EdmxTarget.OData, out errors); writer.Flush(); foreach (var edmError in errors) { Console.WriteLine(edmError); } model.Validate(out errors); foreach (var edmError in errors) { Console.WriteLine(edmError); } }
public CsdlParModel() { #region parse Model StringBuilder builder = new StringBuilder(); TextWriter tw = null; try { tw = new StringWriter(builder); using (var xw = XmlWriter.Create(tw)) { IEnumerable <EdmError> errors; EdmxWriter.TryWriteEdmx(BaseModel, xw, EdmxTarget.OData, out errors); } } catch (Exception) { if (tw != null) { tw.Dispose(); } } TextReader tr = null; try { tr = new StringReader(builder.ToString()); using (var xr = XmlReader.Create(tr)) { Model = EdmxReader.Parse(xr); } } catch (Exception) { if (tr != null) { tr.Dispose(); } } Debug.Assert(Model != null); #endregion Person = Model.FindEntityType("NS.Person"); Debug.Assert(Person != null); PersonSet = Model.FindDeclaredEntitySet("PersonSet"); Debug.Assert(PersonSet != null); PersonNavPetCon = Person.GetNavigationProperty("NavPetCon"); Debug.Assert(PersonNavPetCon != null); PersonNavPetUnknown = Person.GetNavigationProperty("NavPetUnknown"); Debug.Assert(PersonNavPetUnknown != null); }
public static void Dump(this IEdmModel model) { var sb = new StringBuilder(); using (var writer = XmlWriter.Create(sb, new XmlWriterSettings { Indent = true })) { IEnumerable <EdmError> errors; EdmxWriter.TryWriteEdmx(model, writer, EdmxTarget.OData, out errors); } Debug.WriteLine(sb.ToString()); }
public void CheckEdmxUnsupportedVersion() { const string edmx = @"<?xml version=""1.0"" encoding=""utf-16""?> <edmx:Edmx Version=""4.0"" xmlns:edmx=""http://docs.oasis-open.org/odata/ns/edmx""> <edmx:Runtime> <edmx:ConceptualModels> <Schema Namespace=""NS1"" xmlns=""http://docs.oasis-open.org/odata/ns/edm""> <EntityType Name=""Customer""> <Key> <PropertyRef Name=""CustomerID"" /> </Key> <Property Name=""CustomerID"" Type=""Edm.String"" Nullable=""false"" /> </EntityType> <EntityContainer Name=""C1""> <EntitySet Name=""Customers"" EntityType=""NS1.Customer"" /> </EntityContainer> </Schema> </edmx:ConceptualModels> </edmx:Runtime> </edmx:Edmx>"; IEdmModel model; IEnumerable <EdmError> errors; bool parsed = EdmxReader.TryParse(XmlReader.Create(new StringReader(edmx)), out model, out errors); Assert.IsTrue(parsed, "Model Parsed"); Assert.IsTrue(errors.Count() == 0, "No Errors"); Assert.AreEqual(EdmConstants.EdmVersion4, model.GetEdmVersion(), "Model version check 1"); Assert.AreEqual(CsdlConstants.EdmxVersionLatest, model.GetEdmxVersion(), "EDMX version check 1"); StringWriter sw = new StringWriter(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.Encoding = System.Text.Encoding.UTF8; using (XmlWriter xw = XmlWriter.Create(sw, settings)) { model.SetEdmxVersion(new Version(1, 123)); try { EdmxWriter.TryWriteEdmx(model, xw, EdmxTarget.OData, out errors); } catch (Exception e) { Assert.IsTrue(e is InvalidOperationException, "e is InvalidOperationException"); } } }
public static string GetCSDL(IEdmModel model) { StringWriter writer = new StringWriter(); var xwriter = XmlWriter.Create(writer); IEnumerable <EdmError> errors; if (EdmxWriter.TryWriteEdmx(model, xwriter, EdmxTarget.OData, out errors)) { xwriter.Flush(); return(writer.ToString()); } else { throw new Exception(errors.First().ErrorMessage); } }
internal override void WriteMetadataDocument() { IEnumerable <EdmError> enumerable; base.Model.SaveODataAnnotations(); if (!EdmxWriter.TryWriteEdmx(base.Model, this.xmlWriter, EdmxTarget.OData, out enumerable)) { StringBuilder builder = new StringBuilder(); foreach (EdmError error in enumerable) { builder.AppendLine(error.ToString()); } throw new ODataException(Microsoft.Data.OData.Strings.ODataMetadataOutputContext_ErrorWritingMetadata(builder.ToString())); } this.Flush(); }
public void WriterShouldContinueToWork() { var builder = new StringBuilder(); using (var writer = XmlWriter.Create(builder)) { IEnumerable <EdmError> errors; EdmxWriter.TryWriteEdmx(this.representativeModel, writer, EdmxTarget.OData, out errors).Should().BeTrue(); errors.Should().BeEmpty(); writer.Flush(); } string actual = builder.ToString(); var actualXml = XElement.Parse(actual); var actualNormalized = actualXml.ToString(); actualNormalized.Should().Be(RepresentativeEdmxDocument); }
public void VerifyRepresentativeModelWrittenOutCorrectly() { var builder = new StringBuilder(); using (var writer = XmlWriter.Create(builder)) { IEnumerable <EdmError> errors; EdmxWriter.TryWriteEdmx(this.TestModel.RepresentativeModel, writer, EdmxTarget.OData, out errors).Should().BeTrue(); errors.Should().BeEmpty(); writer.Flush(); } string actual = builder.ToString(); var actualXml = XElement.Parse(actual); var actualNormalized = actualXml.ToString(); actualNormalized.Should().Be(DefaultTestModel.RepresentativeEdmxDocument); }
private string DumpEdm(IEdmModel edmModel) { StringWriter sw = new StringWriter(); using (XmlWriter xmlWriter = XmlWriter.Create(sw, new XmlWriterSettings() { Indent = true })) { IEnumerable <EdmError> edmErrors; bool success = EdmxWriter.TryWriteEdmx(edmModel, xmlWriter, EdmxTarget.OData, out edmErrors); Assert.True(success); } string edmXml = sw.ToString(); _testOutput.WriteLine(edmXml); return(edmXml); }
public void TestNullArgChecks() { const string inputText = @"<?xml version=""1.0"" encoding=""utf-16""?> <edmx:Edmx Version=""4.0"" xmlns:edmx=""http://docs.oasis-open.org/odata/ns/edmx""> <edmx:DataServices xmlns:m=""http://docs.oasis-open.org/odata/ns/metadata""> <Schema Namespace=""NS1"" xmlns=""http://docs.oasis-open.org/odata/ns/edm""> <EntityType Name=""Customer""> <Key> <PropertyRef Name=""CustomerID"" /> </Key> <Property Name=""CustomerID"" Type=""Edm.String"" Nullable=""false"" /> </EntityType> <EntityContainer Name=""C1""> <EntitySet Name=""Customers"" EntityType=""NS1.Customer"" /> </EntityContainer> </Schema> </edmx:DataServices> </edmx:Edmx>"; IEdmModel model; IEnumerable <EdmError> errors; EdmxReader.TryParse(XmlReader.Create(new StringReader(inputText)), out model, out errors); try { EdmxWriter.TryWriteEdmx(null, XmlWriter.Create(new StringWriter()), EdmxTarget.EntityFramework, out errors); } catch (Exception e) { Assert.IsTrue(e is ArgumentNullException, "e is ArgumentNullException"); } try { EdmxWriter.TryWriteEdmx(model, null, EdmxTarget.EntityFramework, out errors); } catch (Exception e) { Assert.IsTrue(e is ArgumentNullException, "e is ArgumentNullException"); } }
/// <summary> /// Writes the metadata document as the message body. /// </summary> /// <remarks>It is the responsibility of this method to flush the output before the method returns.</remarks> internal override void WriteMetadataDocument() { this.AssertSynchronous(); IEnumerable <EdmError> errors; if (!EdmxWriter.TryWriteEdmx(this.Model, this.xmlWriter, EdmxTarget.OData, out errors)) { Debug.Assert(errors != null, "errors != null"); StringBuilder builder = new StringBuilder(); foreach (EdmError error in errors) { builder.AppendLine(error.ToString()); } throw new ODataException(Strings.ODataMetadataOutputContext_ErrorWritingMetadata(builder.ToString())); } this.Flush(); }
private string GetEdmx(IEdmModel model, EdmxTarget target) { string edmx = string.Empty; using (StringWriter sw = new StringWriter()) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = System.Text.Encoding.UTF8; using (XmlWriter xw = XmlWriter.Create(sw, settings)) { IEnumerable <EdmError> errors; EdmxWriter.TryWriteEdmx(model, xw, target, out errors); xw.Flush(); } edmx = sw.ToString(); } return(edmx); }
void VerifyResult(string inputText, string expectedResult, EdmxTarget target) { IEdmModel model; IEnumerable <EdmError> errors; bool parsed = CsdlReader.TryParse(new XmlReader[] { XmlReader.Create(new StringReader(inputText)) }, out model, out errors); Assert.IsTrue(parsed, "Model Parsed"); Assert.IsTrue(errors.Count() == 0, "No Errors"); StringWriter sw = new StringWriter(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.Encoding = System.Text.Encoding.UTF8; XmlWriter xw = XmlWriter.Create(sw, settings); EdmxWriter.TryWriteEdmx(model, xw, target, out errors); xw.Flush(); xw.Close(); string outputText = sw.ToString(); Assert.AreEqual(expectedResult, outputText, "Expected Result = Output"); }
/// <summary> /// Generates the OData $metadata document. /// </summary> /// <param name="modelMetadata"><c>true</c> to expose the model metadata; <c>false</c> to use the web API odata model (the default for Web API odata).</param> /// <param name="includeClrInfo">Currently has not effect</param> /// <returns>The <see cref="IEdmModel"/> representing $metadata.</returns> public HttpResponseMessage GetMetadata(bool modelMetadata = true, bool includeClrInfo = false) { var request = Request; var response = new HttpResponseMessage(HttpStatusCode.OK) { RequestMessage = request }; response.Headers.Add("DataServiceVersion", "3.0"); // Write the Metadata EDMX to a var edmModel = GetModel(modelMetadata); IEnumerable <EdmError> writeErrors; if (includeClrInfo == false) { edmModel.RemoveClrTypeAnnotations(); } //response.Content = new PushStreamContent((stream, httpContent, transportContext) => // { // using (XmlWriter xmlWriter = XmlWriter.Create(stream)) // { // EdmxWriter.TryWriteEdmx(edmModel, xmlWriter, EdmxTarget.OData, out writeErrors); // } // if (writeErrors.Any()) // { // var traceWriter = Configuration.Services.GetTraceWriter(); // traceWriter.Error(request, // typeof(EntityRepositoryMetadataController).FullName, // "EDMX write errors:\r\n" + string.Join("\r\n", writeErrors)); // } // }, "application/xml"); var memStream = new MemoryStream(4096); Encoding xmlEncoding; using (XmlWriter xmlWriter = XmlWriter.Create(memStream, new XmlWriterSettings() { Indent = true })) { EdmxWriter.TryWriteEdmx(edmModel, xmlWriter, EdmxTarget.OData, out writeErrors); xmlEncoding = xmlWriter.Settings.Encoding; } if (writeErrors.Any()) { var traceWriter = Configuration.Services.GetTraceWriter(); traceWriter.Error(request, typeof(EntityRepositoryMetadataController).FullName, "EDMX write errors:\r\n" + string.Join("\r\n", writeErrors)); } memStream.Seek(0, SeekOrigin.Begin); response.Content = new StreamContent(memStream); response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml"); response.Content.Headers.ContentType.CharSet = xmlEncoding.WebName; return(response); }