/// <summary> /// Creates an OpenAPI document from a CSDL document. /// </summary> /// <param name="uri">The file path of the CSDL document location.</param> /// <param name="styleOptions">Optional parameter that defines the style /// options to be used in formatting the OpenAPI document.</param> /// <returns></returns> public static OpenApiDocument CreateOpenApiDocument(string uri, OpenApiStyleOptions styleOptions = null) { if (string.IsNullOrEmpty(uri)) { return(null); } using StreamReader streamReader = new StreamReader(uri); Stream csdl = streamReader.BaseStream; var edmModel = CsdlReader.Parse(XElement.Load(csdl).CreateReader()); var settings = new OpenApiConvertSettings() { EnableKeyAsSegment = true, EnableOperationId = true, PrefixEntityTypeNameBeforeKey = true, TagDepth = 2, EnablePagination = styleOptions != null && styleOptions.EnablePagination, EnableDiscriminatorValue = styleOptions != null && styleOptions.EnableDiscriminatorValue, EnableDerivedTypesReferencesForRequestBody = styleOptions != null && styleOptions.EnableDerivedTypesReferencesForRequestBody, EnableDerivedTypesReferencesForResponses = styleOptions != null && styleOptions.EnableDerivedTypesReferencesForResponses, ShowRootPath = styleOptions != null && styleOptions.ShowRootPath }; OpenApiDocument document = edmModel.ConvertToOpenApi(settings); document = FixReferences(document); return(document); }
public Container(global::System.Uri serviceRoot) : base(serviceRoot, ODataProtocolVersion.V4) { this.Format.LoadServiceModel = () => CsdlReader.Parse(XmlReader.Create(new StringReader(Edmx))); this.Format.UseJson(); this.Products = base.CreateQuery <Product>("Products"); }
public async Task CanRenameTypesAndNamespacesInRegularModelBuilder() { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, BaseAddress + "/explicit/$metadata"); HttpResponseMessage response = await Client.SendAsync(request); IEdmModel model = CsdlReader.Parse(XmlReader.Create(await response.Content.ReadAsStreamAsync())); //Can rename an entity + namespace IEdmEntityType customer = model.FindDeclaredType("ModelAliasing.Customer") as IEdmEntityType; Assert.NotNull(customer); //Explicit configuration on the model builder overrides any configuration on the DataContract attribute. IEdmEntityType orders = model.FindDeclaredType("AliasedNamespace.Order") as IEdmEntityType; Assert.NotNull(orders); //Can rename a derived entity name + namespace IEdmEntityType expressOrder = model.FindDeclaredType("Purchasing.ExpressOrder") as IEdmEntityType; Assert.NotNull(expressOrder); //DataContract doesn't rename the entity or the namespace IEdmEntityType freeDeliveryOrder = model.FindDeclaredType("Purchasing.FreeOrder") as IEdmEntityType; Assert.NotNull(freeDeliveryOrder); //DataContract doesn't rename the entity or the namespace IEdmEntityType ordersLines = model.FindDeclaredType("Billing.OrderLine") as IEdmEntityType; Assert.Null(ordersLines); //Can change the name and the namespaces for complex types IEdmComplexType region = model.FindDeclaredType("Location.PoliticalRegion") as IEdmComplexType; Assert.NotNull(region); IEdmComplexType address = model.FindDeclaredType("Location.Direction") as IEdmComplexType; Assert.NotNull(address); }
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 EdmVocabularyAnnotation( 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 = CsdlWriter.TryWriteCsdl(edmModel, xw, CsdlTarget.OData, out errors); xw.Flush(); ms.Flush(); ms.Seek(0, SeekOrigin.Begin); using (var sr = new StreamReader(ms)) { var metadata = sr.ReadToEnd(); loadedEdmModel = CsdlReader.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); }
public async Task Test_NavigationBidingUrlIsAsExpected() { var ctx = new DataServiceContext(new Uri("http://localhost")); ctx.Format.LoadServiceModel = () => CsdlReader.Parse(XmlReader.Create(new StringReader(EDMX))); ctx.Format.UseJson(); ctx.Configurations.ResponsePipeline.OnMessageReaderSettingsCreated((settingsArgs) => { settingsArgs.Settings.Validations = ValidationKinds.None; }); ctx.Configurations.RequestPipeline.OnMessageCreating = args => new CustomizedRequestMessage( args, RESPONSE, new Dictionary <string, string>() { { "Content-Type", "application/json;charset=utf-8" }, }); var query = ctx.CreateQuery <Level3>("Level3"); var values = await query.ExecuteAsync(); values = values.ToList(); var first = values.FirstOrDefault(); Assert.NotNull(first?.Id); Assert.NotNull(ctx.Entities); var firstEntityDescriptor = ctx.Entities.FirstOrDefault(); Assert.Equal(EXPECTED_URL, firstEntityDescriptor?.Identity?.AbsoluteUri); }
/// <summary> /// Converts CSDL to OpenAPI /// </summary> /// <param name="csdl">The CSDL stream.</param> /// <returns>An OpenAPI document.</returns> public static async Task <OpenApiDocument> ConvertCsdlToOpenApiAsync(Stream csdl) { using var reader = new StreamReader(csdl); var csdlTxt = await reader.ReadToEndAsync(); var edmModel = CsdlReader.Parse(XElement.Parse(csdlTxt).CreateReader()); var settings = new OpenApiConvertSettings() { EnableKeyAsSegment = true, EnableOperationId = true, PrefixEntityTypeNameBeforeKey = true, TagDepth = 2, EnablePagination = true, EnableDiscriminatorValue = false, EnableDerivedTypesReferencesForRequestBody = false, EnableDerivedTypesReferencesForResponses = false, ShowRootPath = true, ShowLinks = true }; OpenApiDocument document = edmModel.ConvertToOpenApi(settings); document = FixReferences(document); return(document); }
public DefaultTestModel() { this.RepresentativeModel = CsdlReader.Parse(XElement.Parse(RepresentativeEdmxDocument).CreateReader()); this.EntityContainer = this.RepresentativeModel.EntityContainer; Assert.NotNull(this.EntityContainer); Assert.Equal("Container", this.EntityContainer.Name); this.AddAction = (IEdmAction)this.RepresentativeModel.FindDeclaredOperations("Test.Add").Single(); this.OtherAction = (IEdmAction)this.RepresentativeModel.FindDeclaredOperations("Test.Other").Single(); this.RemoveBadCarAction = (IEdmAction)this.RepresentativeModel.FindDeclaredOperations("Test.RemoveBadCar").Single(); this.Get1Function = (IEdmFunction)this.RepresentativeModel.FindDeclaredOperations("Test.Get1").Single(); this.Get2Function = (IEdmFunction)this.RepresentativeModel.FindDeclaredOperations("Test.Get2").Single(); var operations = this.RepresentativeModel.FindDeclaredOperations("Test.Get3").ToList(); this.Get3FunctionOneParam = (IEdmFunction)operations[0]; this.Get3FunctionNoParams = (IEdmFunction)operations[1]; this.Get1FunctionImport = (IEdmFunctionImport)this.EntityContainer.FindOperationImports("Get1").Single(); this.Get2FunctionImport = (IEdmFunctionImport)this.EntityContainer.FindOperationImports("Get2").Single(); var get3Imports = this.EntityContainer.FindOperationImports("Get3").ToList(); this.Get3FunctionImportWithOneParam = (IEdmFunctionImport)get3Imports[0]; this.Get3FunctionImportWithNoParams = (IEdmFunctionImport)get3Imports[1]; this.PersonType = this.RepresentativeModel.FindDeclaredType("Test.Person") as IEdmEntityType; Assert.NotNull(this.PersonType); this.CarType = this.RepresentativeModel.FindDeclaredType("Test.Car") as IEdmEntityType; Assert.NotNull(this.CarType); }
private IEdmModel GetAlternativeEdmModel() { const string edmx = @"<edmx:Edmx Version=""4.0"" xmlns:edmx=""http://docs.oasis-open.org/odata/ns/edmx""> <edmx:DataServices> <Schema Namespace=""Microsoft.AspNet.OData.Test"" xmlns=""http://docs.oasis-open.org/odata/ns/edm""> <EntityType Name=""Account""> <Key> <PropertyRef Name=""AccountId"" /> </Key> <Property Name=""AccountId"" Type=""Edm.Guid"" Nullable=""false"" /> <Property Name=""Name"" Type=""Edm.String"" /> <Property Name=""AccountType"" Type=""Microsoft.AspNet.OData.Test.AccountType"" Nullable=""false"" /> </EntityType> <EnumType Name=""AccountType""> <Member Name=""Corporate"" Value=""0"" /> <Member Name=""Personal"" Value=""1"" /> <Member Name=""Unknown"" Value=""2"" /> </EnumType> </Schema> <Schema Namespace=""Default"" xmlns=""http://docs.oasis-open.org/odata/ns/edm""> <EntityContainer Name=""AccountService""> <EntitySet Name=""Accounts"" EntityType=""Microsoft.AspNet.OData.Test.Account"" /> </EntityContainer> </Schema> </edmx:DataServices> </edmx:Edmx>"; XmlReader reader = XmlReader.Create(new System.IO.StringReader(edmx)); return(CsdlReader.Parse(reader)); }
public async Task ProvideOverloadToSupplyEntitySetConfiguration() { IEdmModel model = null; Stream stream = await Client.GetStreamAsync(BaseAddress + "/odata/$metadata"); using (XmlReader reader = XmlReader.Create(stream)) { model = CsdlReader.Parse(reader); } IEdmAction collection = model.FindDeclaredOperations("Default.GetProductsByCategory").SingleOrDefault() as IEdmAction; IEdmEntityType expectedReturnType = model.FindDeclaredType(typeof(ActionProduct).FullName) as IEdmEntityType; Assert.NotNull(expectedReturnType); Assert.NotNull(collection); Assert.True(collection.IsBound); Assert.NotNull(collection.ReturnType.AsCollection()); Assert.NotNull(collection.ReturnType.AsCollection().ElementType().AsEntity()); Assert.Equal(expectedReturnType, collection.ReturnType.AsCollection().ElementType().AsEntity().EntityDefinition()); IEdmAction single = model.FindDeclaredOperations("Default.GetSpecialProduct").SingleOrDefault() as IEdmAction; Assert.NotNull(single); Assert.True(single.IsBound); Assert.NotNull(single.ReturnType.AsEntity()); Assert.Equal(expectedReturnType, single.ReturnType.AsEntity().EntityDefinition()); }
public void CanRenamePropertiesInRegularModelBuilder() { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, BaseAddress + "/explicit/$metadata"); HttpResponseMessage response = Client.SendAsync(request).Result; IEdmModel model = CsdlReader.Parse(XmlReader.Create(response.Content.ReadAsStreamAsync().Result)); // Can change the name of regular, complex and navigation properties. IEdmEntityType customer = model.FindDeclaredType("ModelAliasing.Customer") as IEdmEntityType; Assert.NotNull(customer); Assert.NotNull(customer.FindProperty("FinancialAddress")); Assert.NotNull(customer.FindProperty("ClientName")); Assert.NotNull(customer.FindProperty("Purchases")); // Can change the name of properties on complex objects IEdmComplexType address = model.FindDeclaredType("Location.Direction") as IEdmComplexType; Assert.NotNull(address); Assert.NotNull(address.FindProperty("Reign")); //Can change the name of properties on derived entities. IEdmEntityType expressOrder = model.FindDeclaredType("Purchasing.ExpressOrder") as IEdmEntityType; Assert.NotNull(expressOrder); //Can change the name of properties on derived entities when added explicitly. Assert.NotNull(expressOrder.FindProperty("Fee")); //Data contract attribute doesn't change the name of the property. Assert.Null(expressOrder.FindProperty("DeliveryDate")); Assert.Null(expressOrder.FindProperty("GuanteedDeliveryDate")); // Data contract attribute doesn't change the names of the properties IEdmEntityType ordersLines = model.FindDeclaredType("WebStack.QA.Test.OData.ModelAliasing.ModelAliasingMetadataOrderLine") as IEdmEntityType; Assert.NotNull(ordersLines); Assert.Null(ordersLines.FindProperty("Product")); Assert.NotNull(ordersLines.FindProperty("Item")); // Data contract attribute doesn't override any explicit configuration on the model builder Assert.NotNull(ordersLines.FindProperty("Cost")); }
public OasisRelationshipChangesAcceptanceTests() { this.representativeModel = CsdlReader.Parse(XElement.Parse(RepresentativeEdmxDocument).CreateReader()); var container = this.representativeModel.EntityContainer; this.entitySet1 = container.FindEntitySet("EntitySet1"); this.entitySet2 = container.FindEntitySet("EntitySet2"); this.entityType = this.representativeModel.FindType("Test.EntityType") as IEdmEntityType; this.entitySet1.Should().NotBeNull(); this.entitySet2.Should().NotBeNull(); this.entityType.Should().NotBeNull(); this.navigation1 = this.entityType.FindProperty("navigation") as IEdmNavigationProperty; this.navigation2 = this.entityType.FindProperty("NAVIGATION") as IEdmNavigationProperty; nonKeyPrincipalNavigation = this.entityType.FindProperty("NonKeyPrincipalNavigation") as IEdmNavigationProperty; var derivedType = this.representativeModel.FindType("Test.DerivedEntityType") as IEdmEntityType; derivedType.Should().NotBeNull(); this.derivedNavigation = derivedType.FindProperty("DerivedNavigation") as IEdmNavigationProperty; this.navigation1.Should().NotBeNull(); this.navigation2.Should().NotBeNull(); this.derivedNavigation.Should().NotBeNull(); }
/// <summary> /// Load the IEdmModel for both V1 and Beta /// </summary> /// <param name="customMetadataPath">Full file path to the metadata</param> private void LoadGraphMetadata(string customMetadataPath) { ServiceRootV1 = new Uri("https://graph.microsoft.com/v1.0"); ServiceRootBeta = new Uri("https://graph.microsoft.com/beta"); // use clean metadata IedmModelV1 = new Lazy <IEdmModel>(() => CsdlReader.Parse(XmlReader.Create("https://raw.githubusercontent.com/microsoftgraph/msgraph-metadata/master/clean_v10_metadata/cleanMetadataWithDescriptionsv1.0.xml"))); IedmModelBeta = new Lazy <IEdmModel>(() => CsdlReader.Parse(XmlReader.Create("https://raw.githubusercontent.com/microsoftgraph/msgraph-metadata/master/clean_beta_metadata/cleanMetadataWithDescriptionsbeta.xml"))); if (customMetadataPath == null) { return; } if (!File.Exists(customMetadataPath)) { throw new FileNotFoundException("Metadata file is not found in the specified path!", nameof(customMetadataPath)); } CustomEdmModel = new Lazy <IEdmModel>(() => { using (var reader = File.OpenText(customMetadataPath)) { return(CsdlReader.Parse(XmlReader.Create(reader))); } }); }
private IEdmModel LoadAndTransformRsdlModel(string rsdlPath) { var model = parser.Parse(File.ReadAllText(rsdlPath), System.IO.Path.GetFileNameWithoutExtension(rsdlPath)); var referencedModels = new Dictionary <string, RdmDataModel>(); var transformer = new ModelTransformer(NullLogger.Instance); if (transformer.TryTransform(model, referencedModels, out var result)) { // to work arround the problem of comparing generated models with the ones loaded from a file // we will save and load this in-memory model. using (var xml = XmlWriter.Create(rsdlPath + ".actual.csdl.xml")) { CsdlWriter.TryWriteCsdl(result, xml, CsdlTarget.OData, out var errors); } using (var reader = XmlReader.Create(rsdlPath + ".actual.csdl.xml")) { var loaded = CsdlReader.Parse(reader); return(loaded); } } else { throw new System.Exception("failed to transform model"); } }
public void ValidateNavigationPropertyBindingPathTypeCast() { var csdl = "<?xml version=\"1.0\" encoding=\"utf-16\"?>" + "<edmx:Edmx Version=\"4.0\" xmlns:edmx=\"http://docs.oasis-open.org/odata/ns/edmx\">" + "<edmx:DataServices>" + "<Schema Namespace=\"NS\" xmlns=\"http://docs.oasis-open.org/odata/ns/edm\">" + "<EntityType Name=\"EntityA\">" + "<Key><PropertyRef Name=\"ID\" /></Key>" + "<Property Name=\"ID\" Type=\"Edm.Int32\" Nullable=\"false\" />" + "<Property Name=\"Complex\" Type=\"NS.ComplexA\" Nullable=\"false\" />" + "</EntityType>" + "<EntityType Name=\"EntityB\">" + "<Key><PropertyRef Name=\"ID\" /></Key>" + "<Property Name=\"ID\" Type=\"Edm.Int32\" Nullable=\"false\" />" + "</EntityType>" + "<ComplexType Name=\"ComplexA\" />" + "<ComplexType Name=\"ComplexB\">" + "<NavigationProperty Name=\"ComplexBNav\" Type=\"NS.EntityB\" Nullable=\"false\" />" + "</ComplexType>" + "<EntityContainer Name=\"Container\">" + "<EntitySet Name=\"Set1\" EntityType=\"NS.EntityA\">" + "<NavigationPropertyBinding Path=\"Complex/NS.ComplexB/ComplexBNav\" Target=\"Set2\" />" + "</EntitySet>" + "<EntitySet Name=\"Set2\" EntityType=\"NS.EntityB\" />" + "</EntityContainer>" + "</Schema>" + "</edmx:DataServices>" + "</edmx:Edmx>"; var model = CsdlReader.Parse(XElement.Parse(csdl).CreateReader()); var set1 = model.FindDeclaredNavigationSource("Set1"); Assert.True(set1.NavigationPropertyBindings.First().NavigationProperty is UnresolvedNavigationPropertyPath); }
private static IEdmModel GetModel() { var model2 = CsdlReader.Parse(XmlReader.Create("https://localhost:44350/odata/$metadata")); var model = new EdmModel(); model.AddReferencedModel(model2); var reference = new EdmReference(new Uri("https://localhost:44350/odata/$metadata")); reference.AddInclude(new EdmInclude("Model2", "SampleService2.Models")); model.SetEdmReferences(new List <IEdmReference> { reference }); var container = new EdmEntityContainer("NS1", "Default"); var order = model2.FindDeclaredType("SampleService2.Models.Order") as IEdmEntityType; model2.SetAnnotationValue <ClrTypeAnnotation>(order, new ClrTypeAnnotation(typeof(Order))); container.AddEntitySet("Orders", order); model.AddElement(container); var product = new EdmEntityType("NS1", "Product"); product.AddKeys(product.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32)); product.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String); model.AddElement(product); return(model); }
public async Task CanRenamePropertiesInConventionModelBuilder() { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, BaseAddress + "/convention/$metadata"); HttpResponseMessage response = await Client.SendAsync(request); IEdmModel model = CsdlReader.Parse(XmlReader.Create(await response.Content.ReadAsStreamAsync())); // Can change the name of regular, complex and navigation properties. IEdmEntityType customer = model.FindDeclaredType("ModelAliasing.Customer") as IEdmEntityType; Assert.NotNull(customer); Assert.NotNull(customer.FindProperty("FinancialAddress")); Assert.NotNull(customer.FindProperty("ClientName")); Assert.NotNull(customer.FindProperty("Purchases")); // Can change the name of properties on complex objects IEdmComplexType address = model.FindDeclaredType("Location.Direction") as IEdmComplexType; Assert.NotNull(address); Assert.NotNull(address.FindProperty("Reign")); //Can change the name of properties on derived entities. IEdmEntityType expressOrder = model.FindDeclaredType("Purchasing.ExpressOrder") as IEdmEntityType; Assert.NotNull(expressOrder); //Can change the name of properties on derived entities when added explicitly. Assert.NotNull(expressOrder.FindProperty("Fee")); //Can change the name of properties on derived entities using data contract attribute. Assert.NotNull(expressOrder.FindProperty("DeliveryDate")); // Can change the name of the properties using DataContract attribute IEdmEntityType ordersLines = model.FindDeclaredType("Billing.OrderLine") as IEdmEntityType; Assert.NotNull(ordersLines); Assert.NotNull(ordersLines.FindProperty("Product")); // Data contract attribute override any explicit configuration on the model builder Assert.NotNull(ordersLines.FindProperty("Cost")); }
private void Parse(XmlReader xmlReader, List <ITransferObject> list) { IEdmModel model = CsdlReader.Parse(xmlReader); Dictionary <IEdmType, TypeTransferObject> mapping = this.ReadModels(model, list); this.ReadServices(model, mapping, list); }
// This test asserts that single quotes inside strings are escaped public void GenerateSnippetsWithSingleQuotesInsideString() { //Arrange LanguageExpressions expressions = new JavascriptExpressions(); const string actionResultParts = "{\r\n" + " \"values\": [\r\n" + " {\r\n" + " \"@odata.type\": \"microsoft.graph.aadUserConversationMember\",\r\n" + " \"roles\":[],\r\n" + " \"[email protected]\": \"https://graph.microsoft.com/beta/users('18a80140-b0fb-4489-b360-2f6efaf225a0')\"\r\n" + " },\r\n" + " {\r\n" + " \"@odata.type\": \"microsoft.graph.aadUserConversationMember\",\r\n" + " \"roles\":[\"owner\"],\r\n" + " \"[email protected]\": \"https://graph.microsoft.com/beta/users('86503198-b81b-43fe-81ee-ad45b8848ac9')\"\r\n" + " }\r\n" + " ]\r\n" + "}"; var requestPayload = new HttpRequestMessage(HttpMethod.Post, "https://graph.microsoft.com/beta/teams/e4183b04-c9a2-417c-bde4-70e3ee46a6dc/members/add") { Content = new StringContent(actionResultParts) }; var betaServiceRootUrl = "https://graph.microsoft.com/beta"; var betaEdmModel = CsdlReader.Parse(XmlReader.Create(CommonGeneratorShould.CleanBetaMetadata)); var snippetModel = new SnippetModel(requestPayload, betaServiceRootUrl, betaEdmModel); //Act by generating the code snippet var result = JavaScriptGenerator.GenerateCodeSnippet(snippetModel, expressions); //Assert code snippet string matches expectation const string expectedSnippet = "const actionResultPart = {\r\n" + " values: [\r\n" + " {\r\n" + " '@odata.type': 'microsoft.graph.aadUserConversationMember',\r\n" + " roles: [],\r\n" + " '*****@*****.**': 'https://graph.microsoft.com/beta/users(\\'18a80140-b0fb-4489-b360-2f6efaf225a0\\')'\r\n" + " },\r\n" + " {\r\n" + " '@odata.type': 'microsoft.graph.aadUserConversationMember',\r\n" + " roles: ['owner'],\r\n" + " '*****@*****.**': 'https://graph.microsoft.com/beta/users(\\'86503198-b81b-43fe-81ee-ad45b8848ac9\\')'\r\n" + " }\r\n" + " ]\r\n" + "};\r\n" + "\r\n" + "await client.api('/teams/e4183b04-c9a2-417c-bde4-70e3ee46a6dc/members/add')\r\n" + "\t.version('beta')\r\n" + "\t.post(actionResultPart);"; //Assert the snippet generated is as expected Assert.Equal(AuthProviderPrefix + expectedSnippet, result); }
public static async Task <IEdmModel> GetEdmModel(string url) { string content = await _client.GetStringAsync(url); IEdmModel model = CsdlReader.Parse(XElement.Parse(content).CreateReader()); return(model); }
/// <summary> /// Load the IEdmModel for both V1 and Beta /// </summary> private void LoadGraphMetadata() { ServiceRootV1 = new Uri("https://graph.microsoft.com/v1.0"); ServiceRootBeta = new Uri("https://graph.microsoft.com/beta"); IedmModelV1 = new Lazy <IEdmModel>(() => CsdlReader.Parse(XmlReader.Create(ServiceRootV1 + "/$metadata"))); IedmModelBeta = new Lazy <IEdmModel>(() => CsdlReader.Parse(XmlReader.Create(ServiceRootBeta + "/$metadata"))); }
public static IEdmModel GetEdmModel() { string csdlFilePath = @"c:\projects\odata-openapi\ODataV4Metadata.xml"; string csdl = System.IO.File.ReadAllText(csdlFilePath); IEdmModel model = CsdlReader.Parse(XElement.Parse(csdl).CreateReader()); return(model); }
//WASM support public static async Task <IEdmModel> GetServiceModelAsync(HttpClient httpClient) { using (var stream = await httpClient.GetStreamAsync("$metadata")) using (var reader = XmlReader.Create(stream)) { return(EdmModel = CsdlReader.Parse(reader)); } }
/// <summary> /// Get the Edm model. /// </summary> protected override IEdmModel GetEdmModel() { Uri requestUri = new (Input.OriginalString + "/$metadata"); string csdl = GetModelDocumentAsync(requestUri).GetAwaiter().GetResult(); return(CsdlReader.Parse(XElement.Parse(csdl).CreateReader())); }
public IEdmModel GetModel() { var stringReader = new StringReader(_metadataString); var reader = XmlReader.Create(stringReader); var model = CsdlReader.Parse(reader); return(model); }
/// <summary> /// Formulates the requested Graph snippets and returns it as string /// </summary> /// <returns></returns> public string GenerateCsharpSnippet() { //get all the HttpRequestMessage to our RequestPayloadModel RequestPayloadModel requestPayloadModel; // TODO // Assign all properties from the above model all their respective // values /*** Sample Data for Test Purposes **/ requestPayloadModel = new RequestPayloadModel() { Uri = new Uri(@"https://graph.microsoft.com/v1.0/me/messages?$select=subject,IsRead,sender,toRecipients&$filter=IsRead eq false&$skip=10"), Headers = new List <string>() { "Content-Type: application/json" }, Body = string.Empty, HttpMethod = HttpMethod.Get }; Uri serviceRootV1 = new Uri(serviceRoot); Uri fullUriV1 = requestPayloadModel.Uri; IEdmModel iedmModel = CsdlReader.Parse(XmlReader.Create(serviceRootV1 + "/$metadata")); /*** End of sample data for test purposes **/ ODataUriParser parser = new ODataUriParser(iedmModel, serviceRootV1, fullUriV1); ODataUri odatauri = parser.ParseUri(); StringBuilder snippet = new StringBuilder(); //Fomulate all resources path snippet = GenerateResourcesPath(odatauri); /********************************/ /**Formulate the Query options**/ /*******************************/ if (odatauri.Filter != null) { snippet.Append(FilterExpression(odatauri).ToString()); } if (odatauri.SelectAndExpand != null) { snippet.Append(SelectExpression(odatauri).ToString()); } if (odatauri.Search != null) { snippet.Append(SearchExpression(odatauri).ToString()); } snippet.Append(".GetAsync();"); return(snippet.ToString()); }
public void KeyAsSegmentEndToEndSmokeTestInJsonLight() { RunEndToEndSmokeTestWithClient(ctx => { ctx.ResolveName = t => t.FullName; ctx.ResolveType = n => n.Contains("Customer") ? typeof(Customer) : null; ctx.Format.UseJson(CsdlReader.Parse(XmlReader.Create(ctx.GetMetadataUri().AbsoluteUri))); }); }
/// <summary> /// Load the IEdmModel for both V1 and Beta /// </summary> private void LoadGraphMetadata() { ServiceRootV1 = new Uri("https://graph.microsoft.com/v1.0"); ServiceRootBeta = new Uri("https://graph.microsoft.com/beta"); // use clean metadata IedmModelV1 = new Lazy <IEdmModel>(() => CsdlReader.Parse(XmlReader.Create("https://raw.githubusercontent.com/microsoftgraph/msgraph-metadata/master/clean_v10_metadata/cleanMetadataWithDescriptionsv1.0.xml"))); IedmModelBeta = new Lazy <IEdmModel>(() => CsdlReader.Parse(XmlReader.Create("https://raw.githubusercontent.com/microsoftgraph/msgraph-metadata/master/clean_beta_metadata/cleanMetadataWithDescriptionsbeta.xml"))); }
public UserDefinedServiceContainer(Uri serviceRoot) : base(serviceRoot) { XmlReader reader = XmlReader.Create(new StringReader(edmModelString)); edmModel = CsdlReader.Parse(reader); this.Format.LoadServiceModel = () => edmModel; this.Format.UseJson(); }
public void ParsingvalidXmlWithNavigationPropertyInComplex() { string complexWithNav = "<?xml version=\"1.0\" encoding=\"utf-16\"?><edmx:Edmx Version=\"4.0\" xmlns:edmx=\"http://docs.oasis-open.org/odata/ns/edmx\">" + "<edmx:DataServices>" + "<Schema Namespace=\"DefaultNs\" xmlns=\"http://docs.oasis-open.org/odata/ns/edm\">" + "<EntityType Name=\"Person\">" + "<Key><PropertyRef Name=\"UserName\" /></Key>" + "<Property Name=\"UserName\" Type=\"Edm.String\" Nullable=\"false\" />" + "<Property Name=\"HomeAddress\" Type=\"DefaultNs.Address\" Nullable=\"false\" />" + "<Property Name=\"WorkAddress\" Type=\"DefaultNs.Address\" Nullable=\"false\" />" + "<Property Name=\"Addresses\" Type=\"Collection(DefaultNs.Address)\" Nullable=\"false\" />" + "</EntityType>" + "<EntityType Name=\"City\">" + "<Key><PropertyRef Name=\"Name\" /></Key>" + "<Property Name=\"Name\" Type=\"Edm.String\" Nullable=\"false\" />" + "</EntityType>" + "<EntityType Name=\"CountryOrRegion\">" + "<Key><PropertyRef Name=\"Name\" /></Key>" + "<Property Name=\"Name\" Type=\"Edm.String\" Nullable=\"false\" />" + "</EntityType>" + "<ComplexType Name=\"Address\">" + "<Property Name=\"Id\" Type=\"Edm.Int32\" Nullable=\"false\" />" + "<NavigationProperty Name=\"City\" Type=\"DefaultNs.City\" Nullable=\"false\" />" + "</ComplexType>" + "<ComplexType Name=\"WorkAddress\" BaseType=\"DefaultNs.Address\">" + "<NavigationProperty Name=\"CountryOrRegion\" Type=\"DefaultNs.CountryOrRegion\" Nullable=\"false\" /><" + "/ComplexType>" + "<EntityContainer Name=\"Container\">" + "<EntitySet Name=\"People\" EntityType=\"DefaultNs.Person\">" + "<NavigationPropertyBinding Path=\"HomeAddress/City\" Target=\"Cities\" />" + "<NavigationPropertyBinding Path=\"Addresses/City\" Target=\"Cities\" />" + "<NavigationPropertyBinding Path=\"WorkAddress/DefaultNs.WorkAddress/CountryOrRegion\" Target=\"CountriesOrRegions\" />" + "</EntitySet>" + "<EntitySet Name=\"Cities\" EntityType=\"DefaultNs.City\" />" + "<EntitySet Name=\"CountriesOrRegions\" EntityType=\"DefaultNs.CountryOrRegion\" />" + "</EntityContainer></Schema>" + "</edmx:DataServices>" + "</edmx:Edmx>"; var model = CsdlReader.Parse(XElement.Parse(complexWithNav).CreateReader()); var people = model.EntityContainer.FindEntitySet("People"); var address = model.FindType("DefaultNs.Address") as IEdmStructuredType; var workAddress = model.FindType("DefaultNs.WorkAddress") as IEdmStructuredType; var city = address.FindProperty("City") as IEdmNavigationProperty; var countryOrRegion = workAddress.FindProperty("CountryOrRegion") as IEdmNavigationProperty; var cities = model.EntityContainer.FindEntitySet("Cities"); var countriesOrRegions = model.EntityContainer.FindEntitySet("CountriesOrRegions"); var navigationTarget = people.FindNavigationTarget(city, new EdmPathExpression("HomeAddress/City")); Assert.Equal(navigationTarget, cities); navigationTarget = people.FindNavigationTarget(city, new EdmPathExpression("Addresses/City")); Assert.Equal(navigationTarget, cities); navigationTarget = people.FindNavigationTarget(countryOrRegion, new EdmPathExpression("WorkAddress/DefaultNs.WorkAddress/CountryOrRegion")); Assert.Equal(navigationTarget, countriesOrRegions); }
public static IEdmModel GetModel() { if (instance == null) { var xmlReader = XmlReader.Create(DbContextConstants.CsdlFile); instance = CsdlReader.Parse(xmlReader); } return(instance); }