public void GenerateDynamicPropertyContainerWithNonConflictingName() { // Edmx with declared property named DynamicProperties var edmx = @"<?xml version=""1.0"" standalone=""yes"" ?> <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=""Vehicle""> <Key> <PropertyRef Name=""Id"" /> </Key> <Property Name=""Id"" Type=""Edm.Int32"" Nullable=""false"" /> <Property Name=""DynamicProperties"" Type=""Edm.String"" /> </EntityType> <EntityType Name=""Car"" BaseType=""NS.Vehicle"" OpenType=""true""> <Property Name=""Model"" Type=""Edm.String"" /> <Property Name=""DynamicProperties2"" Type=""Edm.String"" /> </EntityType> </Schema> <Schema xmlns=""http://docs.oasis-open.org/odata/ns/edm"" Namespace=""NS""> <EntityContainer Name=""Container""/> </Schema> </edmx:DataServices> </edmx:Edmx> "; var languageOptionTargets = new Dictionary <ODataT4CodeGenerator.LanguageOption, string> { { ODataT4CodeGenerator.LanguageOption.CSharp, "[global::Microsoft.OData.Client.ContainerProperty]publicvirtualglobal::System.Collections.Generic.IDictionary<string,object>DynamicProperties3" }, { ODataT4CodeGenerator.LanguageOption.VB, "<Global.Microsoft.OData.Client.ContainerProperty>_PublicOverridablePropertyDynamicProperties3()AsGlobal.System.Collections.Generic.IDictionary(OfString,Object)" } }; foreach (var languageOption in new[] { ODataT4CodeGenerator.LanguageOption.CSharp, ODataT4CodeGenerator.LanguageOption.VB }) { var containerPropertyAttributeSnippet = languageOptionTargets[languageOption]; var t4CodeGenerator = new ODataT4CodeGenerator { Edmx = edmx, GetReferencedModelReaderFunc = null, NamespacePrefix = null, TargetLanguage = languageOption, EnableNamingAlias = false, IgnoreUnexpectedElementsAndAttributes = false, GenerateMultipleFiles = false, ExcludedSchemaTypes = null, EmitContainerPropertyAttribute = true }; var generatedCode = t4CodeGenerator.TransformText(); var normalizedGeneratedCode = GeneratedCodeHelpers.NormalizeGeneratedCode(generatedCode); Assert.IsTrue(normalizedGeneratedCode.IndexOf(containerPropertyAttributeSnippet, StringComparison.Ordinal) > 0); } }
private async Task AddGeneratedCSharpCodeAsync() { ODataT4CodeGenerator t4CodeGenerator = CodeGeneratorFactory.Create(); t4CodeGenerator.MetadataDocumentUri = MetadataUri; t4CodeGenerator.UseDataServiceCollection = this.ServiceConfiguration.UseDataServiceCollection; t4CodeGenerator.TargetLanguage = ODataT4CodeGenerator.LanguageOption.CSharp; t4CodeGenerator.IgnoreUnexpectedElementsAndAttributes = this.ServiceConfiguration.IgnoreUnexpectedElementsAndAttributes; t4CodeGenerator.EnableNamingAlias = this.ServiceConfiguration.EnableNamingAlias; t4CodeGenerator.NamespacePrefix = this.ServiceConfiguration.NamespacePrefix; t4CodeGenerator.MakeTypesInternal = ServiceConfiguration.MakeTypesInternal; string tempFile = Path.GetTempFileName(); using (StreamWriter writer = File.CreateText(tempFile)) { await writer.WriteAsync(t4CodeGenerator.TransformText()); await writer.FlushAsync(); if (t4CodeGenerator.Errors != null && t4CodeGenerator.Errors.Count > 0) { foreach (var err in t4CodeGenerator.Errors) { await this.Context.Logger.WriteMessageAsync(LoggerMessageCategory.Warning, err.ToString()); } } } string outputFile = Path.Combine(GetReferenceFileFolder(), this.GeneratedFileNamePrefix + ".cs"); await this.Context.HandlerHelper.AddFileAsync(tempFile, outputFile, new AddFileOptions { OpenOnComplete = this.ServiceConfiguration.OpenGeneratedFilesInIDE }); }
// ReSharper disable once RedundantAssignment public override List <ExplorerItem> GetSchemaAndBuildAssembly(IConnectionInfo connectionInfo, AssemblyName assemblyToBuild, ref string nameSpace, ref string typeName) { var properties = connectionInfo.GetConnectionProperties(); var codeGenerator = new ODataT4CodeGenerator { MetadataDocumentUri = properties.Uri, NamespacePrefix = nameSpace, TargetLanguage = ODataT4CodeGenerator.LanguageOption.CSharp, UseDataServiceCollection = false, EnableNamingAlias = false, IgnoreUnexpectedElementsAndAttributes = true, Properties = properties, }; var code = codeGenerator.TransformText(); BuildAssembly(code, assemblyToBuild); var model = properties.GetModel(); typeName = GetContainerName(model); var schema = model.GetSchema(); return(schema); }
public void GenerateDynamicPropertyContainer() { var edmx = @"<?xml version=""1.0"" standalone=""yes"" ?> <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""> <ComplexType Name=""Address"" OpenType=""True""> <Property Name=""Street"" Type=""Edm.String"" Nullable=""false"" /> <Property Name=""City"" Type=""Edm.String"" Nullable=""false"" /> </ComplexType> </Schema> <Schema xmlns=""http://docs.oasis-open.org/odata/ns/edm"" Namespace=""NS""> <EntityContainer Name=""Container""/> </Schema> </edmx:DataServices> </edmx:Edmx> "; var languageOptionTargets = new Dictionary <ODataT4CodeGenerator.LanguageOption, Tuple <string, string> > { { ODataT4CodeGenerator.LanguageOption.CSharp, new Tuple <string, string>("DynamicPropertyContainerTest.cs", "[global::Microsoft.OData.Client.ContainerProperty]publicvirtualglobal::System.Collections.Generic.IDictionary<string,object>DynamicProperties") }, { ODataT4CodeGenerator.LanguageOption.VB, new Tuple <string, string>("DynamicPropertyContainerTest.vb", "<Global.Microsoft.OData.Client.ContainerProperty>_PublicOverridablePropertyDynamicProperties()AsGlobal.System.Collections.Generic.IDictionary(OfString,Object)") } }; foreach (var languageOption in new[] { ODataT4CodeGenerator.LanguageOption.CSharp, ODataT4CodeGenerator.LanguageOption.VB }) { var expectedCodeFileName = languageOptionTargets[languageOption].Item1; var containerPropertyAttributeSnippet = languageOptionTargets[languageOption].Item2; var t4CodeGenerator = new ODataT4CodeGenerator { Edmx = edmx, GetReferencedModelReaderFunc = null, NamespacePrefix = null, TargetLanguage = languageOption, EnableNamingAlias = false, IgnoreUnexpectedElementsAndAttributes = false, GenerateMultipleFiles = false, ExcludedSchemaTypes = null, EmitContainerPropertyAttribute = true }; var generatedCode = t4CodeGenerator.TransformText(); var expectedCode = ODataT4CodeGeneratorTestDescriptors.GetFileContent(expectedCodeFileName); var normalizedGeneratedCode = GeneratedCodeHelpers.NormalizeGeneratedCode(generatedCode); var normalizedExpectedCode = GeneratedCodeHelpers.NormalizeGeneratedCode(expectedCode); Assert.AreEqual(normalizedGeneratedCode, normalizedExpectedCode); Assert.IsTrue(normalizedGeneratedCode.IndexOf(containerPropertyAttributeSnippet, StringComparison.Ordinal) > 0); } }
private static string CodeGenWithT4Template(string edmx, string namespacePrefix, bool isCSharp, bool useDataServiceCollection, bool enableNamingAlias = false, bool ignoreUnexpectedElementsAndAttributes = false, Func <Uri, WebProxy, IList <string>, XmlReader> getReferencedModelReaderFunc = null, bool appendDSCSuffix = false, string MetadataFilePath = null, bool generateMultipleFiles = false, IEnumerable <string> excludedSchemaTypes = default(List <string>)) { if (useDataServiceCollection && appendDSCSuffix) // hack now { var pattern = "<Schema (.*)Namespace=\"(.*?)\""; MatchCollection matches = Regex.Matches(edmx, pattern); foreach (Match match in matches) { edmx = edmx.Replace(match.Groups[2].Value + ".", match.Groups[2].Value + ".DSC."); } edmx = Regex.Replace(edmx, pattern, "<Schema $1Namespace=\"$2.DSC\"", RegexOptions.Multiline); } var t4CodeGenerator = new ODataT4CodeGenerator { Edmx = edmx, GetReferencedModelReaderFunc = getReferencedModelReaderFunc, NamespacePrefix = namespacePrefix, TargetLanguage = isCSharp ? ODataT4CodeGenerator.LanguageOption.CSharp : ODataT4CodeGenerator.LanguageOption.VB, EnableNamingAlias = enableNamingAlias, IgnoreUnexpectedElementsAndAttributes = ignoreUnexpectedElementsAndAttributes, GenerateMultipleFiles = generateMultipleFiles, ExcludedSchemaTypes = excludedSchemaTypes }; if (!String.IsNullOrEmpty(MetadataFilePath)) { t4CodeGenerator.MetadataFilePath = MetadataFilePath; t4CodeGenerator.MetadataFileRelativePath = MetadataFilePath; } if (useDataServiceCollection) { t4CodeGenerator.UseDataServiceCollection = true; } string code = t4CodeGenerator.TransformText(); if (CompileGeneratedCode && !generateMultipleFiles) { // Comment next line to not to verify that the generated code can be compiled successfully GeneratedCodeShouldCompile(code, isCSharp); } return(code); }
private string Generate(string edmx, string referenceName, ODataT4CodeGenerator.LanguageOption languageOption, bool useDataServiceCollection) { ODataT4CodeGenerator t4CodeGenerator = new ODataT4CodeGenerator { Edmx = edmx, NamespacePrefix = referenceName, TargetLanguage = languageOption, UseDataServiceCollection = useDataServiceCollection, }; return(t4CodeGenerator.TransformText()); }
public void TestTypeDefinitionsParamsConvertedToUnderlyingType() { string edmx = LoadReferenceContent("TypeDefinitions.xml"); string expected = LoadReferenceContent("TypeDefinitionsParamsConvertedToUnderlyingType.cs"); var generator = new ODataT4CodeGenerator() { Edmx = edmx, TargetLanguage = ODataT4CodeGenerator.LanguageOption.CSharp }; var output = generator.TransformText(); VerifyGeneratedCode(expected, output); }
public void TestEntitiesComplexTypesEnumsFunctions() { string edmx = LoadReferenceContent("EntitiesEnumsFunctions.xml"); string expected = LoadReferenceContent("EntitiesEnumsFunctions.cs"); var generator = new ODataT4CodeGenerator() { Edmx = edmx, TargetLanguage = ODataT4CodeGenerator.LanguageOption.CSharp }; var output = generator.TransformText(); VerifyGeneratedCode(expected, output); }
public void TestEntitiesComplexTypesEnumFunctionsWithInternalTypes() { string edmx = GeneratedCodeHelpers.LoadReferenceContent("EntitiesEnumsFunctions.xml"); string expected = GeneratedCodeHelpers.LoadReferenceContent("EntitiesEnumsFunctionsWithInternalTypes.cs"); var generator = new ODataT4CodeGenerator() { Edmx = edmx, TargetLanguage = ODataT4CodeGenerator.LanguageOption.CSharp, MakeTypesInternal = true }; var output = generator.TransformText(); GeneratedCodeHelpers.VerifyGeneratedCode(expected, output); }
private async Task AddGeneratedCSharpCodeAsync() { ODataT4CodeGenerator t4CodeGenerator = CodeGeneratorFactory.Create(); t4CodeGenerator.MetadataDocumentUri = MetadataUri; t4CodeGenerator.UseDataServiceCollection = this.ServiceConfiguration.UseDataServiceCollection; t4CodeGenerator.TargetLanguage = ODataT4CodeGenerator.LanguageOption.CSharp; t4CodeGenerator.IgnoreUnexpectedElementsAndAttributes = this.ServiceConfiguration.IgnoreUnexpectedElementsAndAttributes; t4CodeGenerator.EnableNamingAlias = this.ServiceConfiguration.EnableNamingAlias; t4CodeGenerator.NamespacePrefix = this.ServiceConfiguration.NamespacePrefix; t4CodeGenerator.MakeTypesInternal = ServiceConfiguration.MakeTypesInternal; t4CodeGenerator.GenerateMultipleFiles = ServiceConfiguration.GenerateMultipleFiles; var headers = new List <string>(); if (this.ServiceConfiguration.CustomHttpHeaders != null) { string[] headerElements = this.ServiceConfiguration.CustomHttpHeaders.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); foreach (var headerElement in headerElements) { // Trim header for empty spaces var header = headerElement.Trim(); headers.Add(header); } } t4CodeGenerator.CustomHttpHeaders = headers; string tempFile = Path.GetTempFileName(); using (StreamWriter writer = File.CreateText(tempFile)) { await writer.WriteAsync(t4CodeGenerator.TransformText()); await writer.FlushAsync(); if (t4CodeGenerator.Errors != null && t4CodeGenerator.Errors.Count > 0) { foreach (var err in t4CodeGenerator.Errors) { await this.Context.Logger.WriteMessageAsync(LoggerMessageCategory.Warning, err.ToString()); } } } string referenceFolder = GetReferenceFileFolder(); string outputFile = Path.Combine(referenceFolder, this.GeneratedFileNamePrefix + ".cs"); await this.Context.HandlerHelper.AddFileAsync(tempFile, outputFile, new AddFileOptions { OpenOnComplete = this.ServiceConfiguration.OpenGeneratedFilesInIDE }); t4CodeGenerator.MultipleFilesManager?.GenerateFiles(ServiceConfiguration.GenerateMultipleFiles, this.Context.HandlerHelper, referenceFolder, true, this.ServiceConfiguration.OpenGeneratedFilesInIDE); }
public void TestExcludedOperationImportsNotIncludeInGeneratedCode() { string edmx = LoadReferenceContent("EntitiesEnumsFunctions.xml"); string expected = LoadReferenceContent("EntitiesEnumsFunctionsDSCExcludeOperationImports.cs"); var generator = new ODataT4CodeGenerator() { Edmx = edmx, UseDataServiceCollection = true, ExcludedOperationImports = new string[] { "GetPersonWithMostFriends", "ResetDataSource" }, TargetLanguage = ODataT4CodeGenerator.LanguageOption.CSharp }; var output = generator.TransformText(); VerifyGeneratedCode(expected, output); }
private async Task AddGeneratedCodeAsync() { await this.Context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Generating Client Proxy for OData V4..."); this.ServiceConfiguration.ExcludedOperationImportsNames += GetExcludedOperationImportsNames(); var t4CodeGenerator = new ODataT4CodeGenerator { MetadataDocumentUri = MetadataUri, UseDataServiceCollection = this.ServiceConfiguration.UseDataServiceCollection, UseAsyncDataServiceCollection = this.ServiceConfiguration.UseAsyncDataServiceCollection, TargetLanguage = this.ServiceConfiguration.LanguageOption == LanguageOption.GenerateCSharpCode ? ODataT4CodeGenerator.LanguageOption.CSharp : ODataT4CodeGenerator.LanguageOption.VB, IgnoreUnexpectedElementsAndAttributes = this.ServiceConfiguration.IgnoreUnexpectedElementsAndAttributes, EnableNamingAlias = this.ServiceConfiguration.EnableNamingAlias, NamespacePrefix = this.ServiceConfiguration.NamespacePrefix, ExcludedOperationImportsNames = this.ServiceConfiguration?.ExcludedOperationImportsNames, GenerateDynamicPropertiesCollection = this.ServiceConfiguration.GenerateDynamicPropertiesCollection, DynamicPropertiesCollectionName = this.ServiceConfiguration?.DynamicPropertiesCollectionName, MakeTypesInternal = ServiceConfiguration.MakeTypesInternal }; var tempFile = Path.GetTempFileName(); using (var writer = File.CreateText(tempFile)) { var proxyClassText = t4CodeGenerator.TransformText(); await writer.WriteAsync(proxyClassText); await writer.FlushAsync(); if (t4CodeGenerator.Errors != null && t4CodeGenerator.Errors.Count > 0) { foreach (var err in t4CodeGenerator.Errors) { await this.Context.Logger.WriteMessageAsync(LoggerMessageCategory.Warning, err.ToString()); } } } await Microsoft.VisualStudio.Shell.ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var outputFile = Path.Combine(this.ReferenceFileFolder, $"{this.GeneratedFileNamePrefix}{(this.ServiceConfiguration.LanguageOption == LanguageOption.GenerateCSharpCode ? ".cs" : ".vb")}"); await this.Context.HandlerHelper.AddFileAsync(tempFile, outputFile, new AddFileOptions { OpenOnComplete = this.Instance.ServiceConfig.OpenGeneratedFilesOnComplete }); await this.Context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Client Proxy for OData V4 was generated."); }
public string GenerateCode(string namespacePrefix, string metadataDocumentUri, bool useDataServiceCollection = true, bool ignoreUnexpectedElementsAndAttributes = false, bool enableNamingAlias = false) { ODataT4CodeGenerator t4CodeGenerator = new ODataT4CodeGenerator { NamespacePrefix = namespacePrefix, MetadataDocumentUri = metadataDocumentUri, UseDataServiceCollection = useDataServiceCollection, TargetLanguage = ODataT4CodeGenerator.LanguageOption.CSharp, IgnoreUnexpectedElementsAndAttributes = ignoreUnexpectedElementsAndAttributes, EnableNamingAlias = enableNamingAlias }; return(t4CodeGenerator.TransformText()); }
private async Task AddGeneratedCSharpCode() { await this.Context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Generating Client Proxy for OData V4..."); var t4CodeGenerator = new ODataT4CodeGenerator { MetadataDocumentUri = MetadataUri, UseDataServiceCollection = this.ServiceConfiguration.UseDataServiceCollection, TargetLanguage = ODataT4CodeGenerator.LanguageOption.CSharp, IgnoreUnexpectedElementsAndAttributes = this.ServiceConfiguration.IgnoreUnexpectedElementsAndAttributes, EnableNamingAlias = this.ServiceConfiguration.EnableNamingAlias, NamespacePrefix = this.ServiceConfiguration.NamespacePrefix }; var tempFile = Path.GetTempFileName(); using (var writer = File.CreateText(tempFile)) { var proxyClassText = t4CodeGenerator.TransformText(); await writer.WriteAsync(proxyClassText); await writer.FlushAsync(); if (t4CodeGenerator.Errors != null && t4CodeGenerator.Errors.Count > 0) { foreach (var err in t4CodeGenerator.Errors) { await this.Context.Logger.WriteMessageAsync(LoggerMessageCategory.Warning, err.ToString()); } } } var outputFile = Path.Combine(GetReferenceFileFolder(), this.GeneratedFileNamePrefix + ".cs"); await this.Context.HandlerHelper.AddFileAsync(tempFile, outputFile, new AddFileOptions { OpenOnComplete = this.Instance.ServiceConfig.OpenGeneratedFilesOnComplete }); await this.Context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Client Proxy for OData V4 was generated."); }
private async Task AddGeneratedCodeAsync() { await Context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Generating Client Proxy for OData V4...").ConfigureAwait(true); ODataT4CodeGenerator t4CodeGenerator = CodeGeneratorFactory.Create(); t4CodeGenerator.MetadataDocumentUri = MetadataUri; t4CodeGenerator.UseDataServiceCollection = this.ServiceConfiguration.UseDataServiceCollection; t4CodeGenerator.TargetLanguage = this.TargetProjectLanguage == LanguageOption.GenerateCSharpCode ? ODataT4CodeGenerator.LanguageOption.CSharp : ODataT4CodeGenerator.LanguageOption.VB; t4CodeGenerator.IgnoreUnexpectedElementsAndAttributes = this.ServiceConfiguration.IgnoreUnexpectedElementsAndAttributes; t4CodeGenerator.EnableNamingAlias = this.ServiceConfiguration.EnableNamingAlias; t4CodeGenerator.NamespacePrefix = this.ServiceConfiguration.NamespacePrefix; t4CodeGenerator.MakeTypesInternal = ServiceConfiguration.MakeTypesInternal; t4CodeGenerator.GenerateMultipleFiles = ServiceConfiguration.GenerateMultipleFiles; t4CodeGenerator.ExcludedOperationImports = ServiceConfiguration.ExcludedOperationImports; t4CodeGenerator.ExcludedBoundOperations = ServiceConfiguration.ExcludedBoundOperations; t4CodeGenerator.ExcludedSchemaTypes = ServiceConfiguration.ExcludedSchemaTypes; var headers = new List <string>(); if (this.ServiceConfiguration.CustomHttpHeaders != null) { var headerElements = this.ServiceConfiguration.CustomHttpHeaders.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); foreach (var headerElement in headerElements) { // Trim header for empty spaces var header = headerElement.Trim(); headers.Add(header); } } t4CodeGenerator.CustomHttpHeaders = headers; t4CodeGenerator.IncludeWebProxy = ServiceConfiguration.IncludeWebProxy; t4CodeGenerator.WebProxyHost = ServiceConfiguration.WebProxyHost; t4CodeGenerator.IncludeWebProxyNetworkCredentials = ServiceConfiguration.IncludeWebProxyNetworkCredentials; t4CodeGenerator.WebProxyNetworkCredentialsUsername = ServiceConfiguration.WebProxyNetworkCredentialsUsername; t4CodeGenerator.WebProxyNetworkCredentialsPassword = ServiceConfiguration.WebProxyNetworkCredentialsPassword; t4CodeGenerator.WebProxyNetworkCredentialsDomain = ServiceConfiguration.WebProxyNetworkCredentialsDomain; var tempFile = Path.GetTempFileName(); var referenceFolder = GetReferenceFileFolder(); // Csdl file name is this format [ServiceName]Csdl.xml var csdlFileName = string.Concat(ServiceConfiguration.ServiceName, Common.Constants.CsdlFileNameSuffix); var metadataFile = Path.Combine(referenceFolder, csdlFileName); await Context.HandlerHelper.AddFileAsync(tempFile, metadataFile, new AddFileOptions() { SuppressOverwritePrompt = true }).ConfigureAwait(true); // Hack! // Tests were failing since the test project cannot access ProjectItems // dte == null when running test cases var dte = VisualStudio.Shell.Package.GetGlobalService(typeof(DTE)) as DTE; if (dte != null) { var projectItem = this.GetCsdlFileProjectItem(csdlFileName); projectItem.Properties.Item("BuildAction").Value = prjBuildAction.prjBuildActionEmbeddedResource; t4CodeGenerator.EmitContainerPropertyAttribute = EmitContainerPropertyAttribute(); } t4CodeGenerator.MetadataFilePath = metadataFile; t4CodeGenerator.MetadataFileRelativePath = csdlFileName; using (StreamWriter writer = File.CreateText(tempFile)) { await writer.WriteAsync(t4CodeGenerator.TransformText()).ConfigureAwait(true); await writer.FlushAsync().ConfigureAwait(true); if (t4CodeGenerator.Errors != null && t4CodeGenerator.Errors.Count > 0) { foreach (var err in t4CodeGenerator.Errors) { await Context.Logger.WriteMessageAsync(LoggerMessageCategory.Warning, err.ToString()).ConfigureAwait(false); } } } var outputFile = Path.Combine(referenceFolder, $"{this.GeneratedFileNamePrefix}{(this.TargetProjectLanguage == LanguageOption.GenerateCSharpCode ? ".cs" : ".vb")}"); await Context.HandlerHelper.AddFileAsync(tempFile, outputFile, new AddFileOptions { OpenOnComplete = ServiceConfiguration.OpenGeneratedFilesInIDE }).ConfigureAwait(true); t4CodeGenerator.MultipleFilesManager?.GenerateFiles(ServiceConfiguration.GenerateMultipleFiles, this.Context.HandlerHelper, this.Context.Logger, referenceFolder, true, this.ServiceConfiguration.OpenGeneratedFilesInIDE); await Context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Client Proxy for OData V4 was generated.").ConfigureAwait(true); }
private string Generate(string edmx, string referenceName, ODataT4CodeGenerator.LanguageOption languageOption, bool useDataServiceCollection) { ODataT4CodeGenerator t4CodeGenerator = new ODataT4CodeGenerator { Edmx = edmx, NamespacePrefix = referenceName, TargetLanguage = languageOption, UseDataServiceCollection = useDataServiceCollection, }; return t4CodeGenerator.TransformText(); }
private async Task AddGeneratedCSharpCode() { ODataT4CodeGenerator t4CodeGenerator = new ODataT4CodeGenerator(); t4CodeGenerator.MetadataDocumentUri = MetadataUri; t4CodeGenerator.UseDataServiceCollection = this.ServiceConfiguration.UseDataServiceCollection; t4CodeGenerator.TargetLanguage = ODataT4CodeGenerator.LanguageOption.CSharp; t4CodeGenerator.IgnoreUnexpectedElementsAndAttributes = this.ServiceConfiguration.IgnoreUnexpectedElementsAndAttributes; t4CodeGenerator.EnableNamingAlias = this.ServiceConfiguration.EnableNamingAlias; t4CodeGenerator.NamespacePrefix = this.ServiceConfiguration.NamespacePrefix; string tempFile = Path.GetTempFileName(); using (StreamWriter writer = File.CreateText(tempFile)) { await writer.WriteAsync(t4CodeGenerator.TransformText()); await writer.FlushAsync(); if (t4CodeGenerator.Errors != null && t4CodeGenerator.Errors.Count > 0) { foreach (var err in t4CodeGenerator.Errors) { await this.Context.Logger.WriteMessageAsync(LoggerMessageCategory.Warning, err.ToString()); } } } string outputFile = Path.Combine(GetReferenceFileFolder(), this.GeneratedFileNamePrefix + ".cs"); await this.Context.HandlerHelper.AddFileAsync(tempFile, outputFile); }
/// <summary> /// Generates proxy classes /// </summary> /// <param name="configuration"></param> public void GenerateClientProxyClasses(GeneratorParams configuration) { _logger.LogInformation(Resources.Generating_Client_Proxy____); if (string.IsNullOrWhiteSpace(configuration.MetadataDocumentUri)) { throw new ArgumentNullException(nameof(configuration.MetadataDocumentUri)); } var version = GetMetadataVersion(configuration); if (version != Constants.EdmxVersion4) { throw new ArgumentException(string.Format(Resources.Wrong_edx_version, version)); } ODataT4CodeGenerator t4CodeGenerator = new ODataT4CodeGenerator(); t4CodeGenerator.MetadataDocumentUri = configuration.MetadataDocumentUri; t4CodeGenerator.UseDataServiceCollection = configuration.UseDataServiceCollection; t4CodeGenerator.TargetLanguage = ODataT4CodeGenerator.LanguageOption.CSharp; t4CodeGenerator.IgnoreUnexpectedElementsAndAttributes = configuration.IgnoreUnexpectedElementsAndAttributes; t4CodeGenerator.EnableNamingAlias = configuration.EnableNamingAlias; t4CodeGenerator.NamespacePrefix = configuration.NamespacePrefix; t4CodeGenerator.MakeTypesInternal = configuration.MakeTypesInternal; t4CodeGenerator.GenerateMultipleFiles = configuration.GenerateMultipleFiles; t4CodeGenerator.ExcludedOperationImports = configuration.ExcludedOperationImports; t4CodeGenerator.ExcludedBoundOperations = configuration.ExcludedBoundOperations; t4CodeGenerator.ExcludedSchemaTypes = configuration.ExcludedSchemaTypes; t4CodeGenerator.CustomHttpHeaders = configuration.CustomHttpHeaders; t4CodeGenerator.IncludeWebProxy = configuration.IncludeWebProxy; t4CodeGenerator.WebProxyHost = configuration.WebProxyHost; t4CodeGenerator.IncludeWebProxyNetworkCredentials = configuration.IncludeWebProxyNetworkCredentials; t4CodeGenerator.WebProxyNetworkCredentialsUsername = configuration.WebProxyNetworkCredentialsUsername; t4CodeGenerator.WebProxyNetworkCredentialsPassword = configuration.WebProxyNetworkCredentialsPassword; t4CodeGenerator.WebProxyNetworkCredentialsDomain = configuration.WebProxyNetworkCredentialsDomain; t4CodeGenerator.CustomContainerName = configuration.CustomContainerName; var tempFile = Path.GetTempFileName(); var referenceFolder = configuration.OutputDirectory; var fileHandler = new FilesHandler(_logger); fileHandler.TokenReplacementValues.Add("#VersionNumber#", Constants.GeneratorVersion); var serviceFilename = Constants.DefaultServiceFilename; if (!string.IsNullOrWhiteSpace(configuration.CustomContainerName)) { serviceFilename = configuration.CustomContainerName; } var csdlFileName = string.Concat(serviceFilename, Constants.CsdlFileNameSuffix); var metadataFile = Path.Combine(referenceFolder, csdlFileName); fileHandler.AddFileAsync(tempFile, metadataFile).ConfigureAwait(true); t4CodeGenerator.EmitContainerPropertyAttribute = false; t4CodeGenerator.MetadataFilePath = metadataFile; t4CodeGenerator.MetadataFileRelativePath = csdlFileName; try { using (StreamWriter writer = File.CreateText(tempFile)) { writer.Write(t4CodeGenerator.TransformText()); writer.Flush(); if (t4CodeGenerator.Errors != null && t4CodeGenerator.Errors.Count > 0) { foreach (var err in t4CodeGenerator.Errors) { _logger?.LogError(err.ToString()); } _logger.LogError(Resources.Client_Proxy_for_OData_V4_was_not_generated_); } } } catch (Exception e) { _logger.LogError(Resources.Generators_error, e); throw; } var outputFile = Path.Combine(referenceFolder, string.IsNullOrWhiteSpace(configuration.CustomContainerName) ? $"{Constants.DefaultServiceFilename}.cs" : $"{configuration.CustomContainerName}.cs"); fileHandler.AddFileAsync(tempFile, outputFile).ConfigureAwait(true); t4CodeGenerator.MultipleFilesManager?.GenerateFiles(true, fileHandler, referenceFolder, true, false); foreach (var pluginCommand in configuration.Plugins) { var plugin = PluginCreator.Create(_logger, configuration, pluginCommand); plugin.Execute(); } _logger?.LogInformation(Resources.Client_Proxy_for_OData_V4_was_generated_); }
private static string CodeGenWithT4Template(string edmx, string namespacePrefix, bool isCSharp, bool useDataServiceCollection, bool enableNamingAlias = false, bool ignoreUnexpectedElementsAndAttributes = false, Func<Uri, XmlReader> getReferencedModelReaderFunc = null, bool appendDSCSuffix = false) { if (useDataServiceCollection && appendDSCSuffix) // hack now { var pattern = "<Schema (.*)Namespace=\"(.*?)\""; MatchCollection matches = Regex.Matches(edmx, pattern); foreach (Match match in matches) { edmx = edmx.Replace(match.Groups[2].Value + ".", match.Groups[2].Value + ".DSC."); } edmx = Regex.Replace(edmx, pattern, "<Schema $1Namespace=\"$2.DSC\"", RegexOptions.Multiline); } ODataT4CodeGenerator t4CodeGenerator = new ODataT4CodeGenerator { Edmx = edmx, GetReferencedModelReaderFunc = getReferencedModelReaderFunc, NamespacePrefix = namespacePrefix, TargetLanguage = isCSharp ? ODataT4CodeGenerator.LanguageOption.CSharp : ODataT4CodeGenerator.LanguageOption.VB, EnableNamingAlias = enableNamingAlias, IgnoreUnexpectedElementsAndAttributes = ignoreUnexpectedElementsAndAttributes }; if (useDataServiceCollection) { t4CodeGenerator.UseDataServiceCollection = true; } string code = t4CodeGenerator.TransformText(); if (CompileGeneratedCode) { // Comment next line to not to verify that the generated code can be compiled successfully GeneratedCodeShouldCompile(code, isCSharp); } return code; }
private async Task AddGeneratedCodeAsync(string metadata, string outputDirectory, LanguageOption languageOption, ServiceConfiguration serviceConfiguration) { await MessageLogger.WriteMessageAsync(LogMessageCategory.Information, "Generating Client Proxy for OData V4..."); ServiceConfigurationV4 servConfiguration = serviceConfiguration as ServiceConfigurationV4; ODataT4CodeGenerator t4CodeGenerator = CodeGeneratorFactory.Create(); t4CodeGenerator.MetadataDocumentUri = metadata; t4CodeGenerator.UseDataServiceCollection = servConfiguration.UseDataServiceCollection; t4CodeGenerator.TargetLanguage = languageOption == LanguageOption.GenerateCSharpCode ? ODataT4CodeGenerator.LanguageOption.CSharp : ODataT4CodeGenerator.LanguageOption.VB; t4CodeGenerator.IgnoreUnexpectedElementsAndAttributes = servConfiguration.IgnoreUnexpectedElementsAndAttributes; t4CodeGenerator.EnableNamingAlias = servConfiguration.EnableNamingAlias; t4CodeGenerator.NamespacePrefix = servConfiguration.NamespacePrefix; t4CodeGenerator.MakeTypesInternal = servConfiguration.MakeTypesInternal; t4CodeGenerator.GenerateMultipleFiles = servConfiguration.GenerateMultipleFiles; t4CodeGenerator.ExcludedOperationImports = servConfiguration.ExcludedOperationImports; t4CodeGenerator.ExcludedBoundOperations = servConfiguration.ExcludedBoundOperations; t4CodeGenerator.ExcludedSchemaTypes = servConfiguration.ExcludedSchemaTypes; var headers = new List <string>(); if (servConfiguration.CustomHttpHeaders != null) { var headerElements = servConfiguration.CustomHttpHeaders.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); foreach (var headerElement in headerElements) { // Trim header for empty spaces var header = headerElement.Trim(); headers.Add(header); } } t4CodeGenerator.CustomHttpHeaders = headers; t4CodeGenerator.IncludeWebProxy = servConfiguration.IncludeWebProxy; t4CodeGenerator.WebProxyHost = servConfiguration.WebProxyHost; t4CodeGenerator.IncludeWebProxyNetworkCredentials = servConfiguration.IncludeWebProxyNetworkCredentials; t4CodeGenerator.WebProxyNetworkCredentialsUsername = servConfiguration.WebProxyNetworkCredentialsUsername; t4CodeGenerator.WebProxyNetworkCredentialsPassword = servConfiguration.WebProxyNetworkCredentialsPassword; t4CodeGenerator.WebProxyNetworkCredentialsDomain = servConfiguration.WebProxyNetworkCredentialsDomain; var tempFile = Path.GetTempFileName(); var referenceFolder = outputDirectory; // Csdl file name is this format [ServiceName]Csdl.xml var csdlFileName = string.Concat(servConfiguration.ServiceName, Common.Constants.CsdlFileNameSuffix); var metadataFile = Path.Combine(referenceFolder, csdlFileName); await FileHandler.AddFileAsync(tempFile, metadataFile, new ODataFileOptions { SuppressOverwritePrompt = true }); FileHandler.SetFileAsEmbeddedResource(csdlFileName); t4CodeGenerator.EmitContainerPropertyAttribute = FileHandler.EmitContainerPropertyAttribute(); t4CodeGenerator.MetadataFilePath = metadataFile; t4CodeGenerator.MetadataFileRelativePath = csdlFileName; using (StreamWriter writer = File.CreateText(tempFile)) { await writer.WriteAsync(t4CodeGenerator.TransformText()); await writer.FlushAsync(); if (t4CodeGenerator.Errors != null && t4CodeGenerator.Errors.Count > 0) { foreach (var err in t4CodeGenerator.Errors) { await MessageLogger.WriteMessageAsync(LogMessageCategory.Warning, err.ToString()).ConfigureAwait(false); } } } var outputFile = Path.Combine(referenceFolder, $"{this.GeneratedFileNamePrefix(servConfiguration.GeneratedFileNamePrefix)}{(languageOption == LanguageOption.GenerateCSharpCode ? ".cs" : ".vb")}"); await FileHandler.AddFileAsync(tempFile, outputFile, new ODataFileOptions { SuppressOverwritePrompt = true }); t4CodeGenerator.MultipleFilesManager?.GenerateFiles(servConfiguration.GenerateMultipleFiles, FileHandler, MessageLogger, referenceFolder, true, servConfiguration.OpenGeneratedFilesInIDE); await MessageLogger.WriteMessageAsync(LogMessageCategory.Information, "Client Proxy for OData V4 was generated."); }