static void GenerateVBCodeForService(Uri metadataAddress, string outputFile) { MetadataExchangeClient mexClient = new MetadataExchangeClient(metadataAddress, MetadataExchangeClientMode.HttpGet); mexClient.ResolveMetadataReferences = true; MetadataSet metaDocs = mexClient.GetMetadata(); WsdlImporter importer = new WsdlImporter(metaDocs); ServiceContractGenerator generator = new ServiceContractGenerator(); System.Collections.ObjectModel.Collection <ContractDescription> contracts = importer.ImportAllContracts(); foreach (ContractDescription contract in contracts) { generator.GenerateServiceContractType(contract); } if (generator.Errors.Count != 0) { throw new ApplicationException("There were errors during code compilation."); } // Write the code dom. System.CodeDom.Compiler.CodeGeneratorOptions options = new System.CodeDom.Compiler.CodeGeneratorOptions(); options.BracingStyle = "C"; System.CodeDom.Compiler.CodeDomProvider codeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("VB"); System.CodeDom.Compiler.IndentedTextWriter textWriter = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(outputFile)); codeDomProvider.GenerateCodeFromCompileUnit(generator.TargetCompileUnit, textWriter, options); textWriter.Close(); }
static void GenerateVBCodeForService(Uri metadataAddress, string outputFile) { MetadataExchangeClient mexClient = new MetadataExchangeClient(metadataAddress, MetadataExchangeClientMode.HttpGet); mexClient.ResolveMetadataReferences = true; MetadataSet metaDocs = mexClient.GetMetadata(); WsdlImporter importer = new WsdlImporter(metaDocs); ServiceContractGenerator generator = new ServiceContractGenerator(); System.Collections.ObjectModel.Collection<ContractDescription> contracts = importer.ImportAllContracts(); foreach (ContractDescription contract in contracts) { generator.GenerateServiceContractType(contract); } if (generator.Errors.Count != 0) throw new ApplicationException("There were errors during code compilation."); // Write the code dom. System.CodeDom.Compiler.CodeGeneratorOptions options = new System.CodeDom.Compiler.CodeGeneratorOptions(); options.BracingStyle = "C"; System.CodeDom.Compiler.CodeDomProvider codeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("VB"); System.CodeDom.Compiler.IndentedTextWriter textWriter = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(outputFile)); codeDomProvider.GenerateCodeFromCompileUnit(generator.TargetCompileUnit, textWriter, options); textWriter.Close(); }
static void Main() { string outputFile = "c:\\temp\\test"; //<Snippet0> EndpointAddress mexAddress = new EndpointAddress("http://localhost:8000/ServiceModelSamples/service/mex"); //</Snippet0> //<Snippet1> MetadataExchangeClient mexClient = new MetadataExchangeClient(mexAddress); mexClient.ResolveMetadataReferences = true; MetadataSet metaSet = mexClient.GetMetadata(); //</Snippet1> //<Snippet2> WsdlImporter importer = new WsdlImporter(metaSet); System.Collections.ObjectModel.Collection <ContractDescription> contracts = importer.ImportAllContracts(); //</Snippet2> //<Snippet3> ServiceContractGenerator generator = new ServiceContractGenerator(); foreach (ContractDescription contract in contracts) { generator.GenerateServiceContractType(contract); } if (generator.Errors.Count != 0) { throw new Exception("There were errors during code compilation."); } //</Snippet3> // Write the code dom //<Snippet4> System.CodeDom.Compiler.CodeGeneratorOptions options = new System.CodeDom.Compiler.CodeGeneratorOptions(); options.BracingStyle = "C"; System.CodeDom.Compiler.CodeDomProvider codeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("C#"); System.CodeDom.Compiler.IndentedTextWriter textWriter = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(outputFile)); codeDomProvider.GenerateCodeFromCompileUnit(generator.TargetCompileUnit, textWriter, options); textWriter.Close(); //</Snippet4> Console.WriteLine(); Console.WriteLine("Press <ENTER> to terminate client."); Console.ReadLine(); }
static void GenerateCSCodeForService(EndpointAddress metadataAddress, string outputFile) { MetadataExchangeClient mexClient = new MetadataExchangeClient(metadataAddress); mexClient.ResolveMetadataReferences = true; MetadataSet metaDocs = mexClient.GetMetadata(); WsdlImporter importer = new WsdlImporter(metaDocs); ServiceContractGenerator generator = new ServiceContractGenerator(); // Uncomment the following code if you are going to do your work programmatically rather than add // the WsdlDocumentationImporters through a configuration file. /* * // The following code inserts the custom WSDL programmatically adding the custom WsdlImporter without * // removing the other importers already in the collection. * System.Collections.Generic.IEnumerable<IWsdlImportExtension> exts = importer.WsdlExtensions; * System.Collections.Generic.List<IWsdlImportExtension> newExts = new System.Collections.Generic.List<IWsdlImportExtension>(); * foreach (IWsdlImportExtension ext in exts) * newExts.Add(ext); * newExts.Add(new WsdlDocumentationImporter()); * importer = new WsdlImporter(newExts.ToArray(), metaDocs.MetadataSections); */ System.Collections.ObjectModel.Collection <ContractDescription> contracts = importer.ImportAllContracts(); foreach (ContractDescription contract in contracts) { generator.GenerateServiceContractType(contract); } if (generator.Errors.Count != 0) { throw new ApplicationException("There were errors during code compilation."); } // Write the code dom System.CodeDom.Compiler.CodeGeneratorOptions options = new System.CodeDom.Compiler.CodeGeneratorOptions(); options.BracingStyle = "C"; System.CodeDom.Compiler.CodeDomProvider codeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("C#"); System.CodeDom.Compiler.IndentedTextWriter textWriter = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(outputFile)); codeDomProvider.GenerateCodeFromCompileUnit( generator.TargetCompileUnit, textWriter, options ); textWriter.Close(); }
public static void GenerateViaCodeDOM(string outputFileName, System.CodeDom.Compiler.CodeDomProvider provider, System.CodeDom.CodeCompileUnit compileunit) { System.CodeDom.Compiler.ICodeGenerator gen = provider.CreateGenerator(); System.CodeDom.Compiler.IndentedTextWriter tw; try { tw = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(outputFileName, false), " "); gen.GenerateCodeFromCompileUnit(compileunit, tw, new System.CodeDom.Compiler.CodeGeneratorOptions()); tw.Flush(); tw.Close(); } catch (System.Exception ex) { System.Diagnostics.Debug.WriteLine(ex); throw; } }
public static System.IO.Stream GenerateViaCodeDOM(Utility.OutputType outputType, System.CodeDom.CodeCompileUnit compileunit) { System.CodeDom.Compiler.CodeDomProvider provider = null; System.CodeDom.Compiler.ICodeGenerator gen; System.CodeDom.Compiler.IndentedTextWriter tw = null; System.IO.MemoryStream stream; System.IO.StreamWriter writer; switch (outputType) { case Utility.OutputType.VB: provider = new Microsoft.VisualBasic.VBCodeProvider(); break; case Utility.OutputType.CSharp: provider = new Microsoft.CSharp.CSharpCodeProvider(); break; } gen = provider.CreateGenerator(); try { stream = new System.IO.MemoryStream(); writer = new System.IO.StreamWriter(stream); tw = new System.CodeDom.Compiler.IndentedTextWriter(writer, " "); gen.GenerateCodeFromCompileUnit(compileunit, tw, new System.CodeDom.Compiler.CodeGeneratorOptions()); tw.Flush(); stream.Seek(0, System.IO.SeekOrigin.Begin); } catch (System.Exception ex) { System.Diagnostics.Debug.WriteLine(ex); if (tw != null) { tw.Flush(); tw.Close(); } throw; } return(stream); }
private static void GenerateCSCodeForServiceThread() { try { string outputFile = "WSDL-Output"; MetadataExchangeClient mexClient = new MetadataExchangeClient(server.metaAddress, MetadataExchangeClientMode.HttpGet); mexClient.ResolveMetadataReferences = true; mexClient.OperationTimeout = TimeSpan.FromSeconds(60); mexClient.MaximumResolvedReferences = 1000; MetadataSet metaDocs = mexClient.GetMetadata(); WsdlImporter importer = new WsdlImporter(metaDocs); ServiceContractGenerator generator = new ServiceContractGenerator(); // Add our custom DCAnnotationSurrogate // to write XSD annotations into the comments. object dataContractImporter; XsdDataContractImporter xsdDCImporter; if (!importer.State.TryGetValue(typeof(XsdDataContractImporter), out dataContractImporter)) { Console.WriteLine("Couldn't find the XsdDataContractImporter! Adding custom importer."); xsdDCImporter = new XsdDataContractImporter(); xsdDCImporter.Options = new ImportOptions(); importer.State.Add(typeof(XsdDataContractImporter), xsdDCImporter); } else { xsdDCImporter = (XsdDataContractImporter)dataContractImporter; if (xsdDCImporter.Options == null) { Console.WriteLine("There were no ImportOptions on the importer."); xsdDCImporter.Options = new ImportOptions(); } } ////TODO: This is a customer implementation using the IDataContractSurrogate interface // xsdDCImporter.Options.DataContractSurrogate = new DCAnnotationSurrogate(); // Uncomment the following code if you are going to do your work programmatically rather than add // the WsdlDocumentationImporters through a configuration file. /* * // The following code inserts a custom WsdlImporter without removing the other * // importers already in the collection. * System.Collections.Generic.IEnumerable<IWsdlImportExtension> exts = importer.WsdlImportExtensions; * System.Collections.Generic.List<IWsdlImportExtension> newExts * = new System.Collections.Generic.List<IWsdlImportExtension>(); * foreach (IWsdlImportExtension ext in exts) * { * Console.WriteLine("Default WSDL import extensions: {0}", ext.GetType().Name); * newExts.Add(ext); * } * newExts.Add(new WsdlDocumentationImporter()); * System.Collections.Generic.IEnumerable<IPolicyImportExtension> polExts = importer.PolicyImportExtensions; * importer = new WsdlImporter(metaDocs, polExts, newExts); */ System.Collections.ObjectModel.Collection <ContractDescription> contracts = importer.ImportAllContracts(); importer.ImportAllEndpoints(); foreach (ContractDescription contract in contracts) { generator.GenerateServiceContractType(contract); } if (generator.Errors.Count != 0) { throw new Exception("There were errors during code compilation."); } // Write the code dom System.CodeDom.Compiler.CodeGeneratorOptions options = new System.CodeDom.Compiler.CodeGeneratorOptions(); options.BracingStyle = "C"; System.CodeDom.Compiler.CodeDomProvider codeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("C#"); System.CodeDom.Compiler.IndentedTextWriter textWriter = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(outputFile)); codeDomProvider.GenerateCodeFromCompileUnit(generator.TargetCompileUnit, textWriter, options); textWriter.Close(); } catch (FaultException fx) { MessageBox.Show(fx.Message + " > " + fx.Reason + " > " + fx.Action + " > " + fx.Data + " > " + fx.Code + " > " + fx.InnerException); } catch (TimeoutException tx) { MessageBox.Show(tx.Message + " > " + tx.Data + " > " + tx.InnerException); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
static void GenerateVBCodeForService(EndpointAddress metadataAddress, string outputFile) { MetadataExchangeClient mexClient = new MetadataExchangeClient(metadataAddress); mexClient.ResolveMetadataReferences = true; MetadataSet metaDocs = mexClient.GetMetadata(); WsdlImporter importer = new WsdlImporter(metaDocs); ServiceContractGenerator generator = new ServiceContractGenerator(); // Uncomment the following code if you are going to do your work programmatically rather than add // the WsdlDocumentationImporters through a configuration file. /* // The following code inserts the custom WSDL programmatically adding the custom WsdlImporter without // removing the other importers already in the collection. System.Collections.Generic.IEnumerable<IWsdlImportExtension> exts = importer.WsdlExtensions; System.Collections.Generic.List<IWsdlImportExtension> newExts = new System.Collections.Generic.List<IWsdlImportExtension>(); foreach (IWsdlImportExtension ext in exts) newExts.Add(ext); newExts.Add(new WsdlDocumentationImporter()); importer = new WsdlImporter(newExts.ToArray(), metaDocs.MetadataSections); */ System.Collections.ObjectModel.Collection<ContractDescription> contracts = importer.ImportAllContracts(); foreach (ContractDescription contract in contracts) { generator.GenerateServiceContractType(contract); } if (generator.Errors.Count != 0) throw new ApplicationException("There were errors during code compilation."); // Write the code dom. System.CodeDom.Compiler.CodeGeneratorOptions options = new System.CodeDom.Compiler.CodeGeneratorOptions(); options.BracingStyle = "C"; System.CodeDom.Compiler.CodeDomProvider codeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("VB"); System.CodeDom.Compiler.IndentedTextWriter textWriter = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(outputFile)); codeDomProvider.GenerateCodeFromCompileUnit(generator.TargetCompileUnit, textWriter, options); textWriter.Close(); }
//<snippet8> static void GenerateCSCodeForService(EndpointAddress metadataAddress, string outputFile) { //<snippet10> MetadataExchangeClient mexClient = new MetadataExchangeClient(metadataAddress); mexClient.ResolveMetadataReferences = true; MetadataSet metaDocs = mexClient.GetMetadata(); WsdlImporter importer = new WsdlImporter(metaDocs); ServiceContractGenerator generator = new ServiceContractGenerator(); //</snippet10> // Add our custom DCAnnotationSurrogate // to write XSD annotations into the comments. object dataContractImporter; XsdDataContractImporter xsdDCImporter; if (!importer.State.TryGetValue(typeof(XsdDataContractImporter), out dataContractImporter)) { Console.WriteLine("Couldn't find the XsdDataContractImporter! Adding custom importer."); xsdDCImporter = new XsdDataContractImporter(); xsdDCImporter.Options = new ImportOptions(); importer.State.Add(typeof(XsdDataContractImporter), xsdDCImporter); } else { xsdDCImporter = (XsdDataContractImporter)dataContractImporter; if (xsdDCImporter.Options == null) { Console.WriteLine("There were no ImportOptions on the importer."); xsdDCImporter.Options = new ImportOptions(); } } xsdDCImporter.Options.DataContractSurrogate = new DCAnnotationSurrogate(); // Uncomment the following code if you are going to do your work programmatically rather than add // the WsdlDocumentationImporters through a configuration file. /* * // <snippet11> * // The following code inserts a custom WsdlImporter without removing the other * // importers already in the collection. * System.Collections.Generic.IEnumerable<IWsdlImportExtension> exts = importer.WsdlImportExtensions; * System.Collections.Generic.List<IWsdlImportExtension> newExts * = new System.Collections.Generic.List<IWsdlImportExtension>(); * foreach (IWsdlImportExtension ext in exts) * { * Console.WriteLine("Default WSDL import extensions: {0}", ext.GetType().Name); * newExts.Add(ext); * } * newExts.Add(new WsdlDocumentationImporter()); * System.Collections.Generic.IEnumerable<IPolicyImportExtension> polExts = importer.PolicyImportExtensions; * importer = new WsdlImporter(metaDocs, polExts, newExts); * // </snippet11> */ System.Collections.ObjectModel.Collection <ContractDescription> contracts = importer.ImportAllContracts(); importer.ImportAllEndpoints(); foreach (ContractDescription contract in contracts) { generator.GenerateServiceContractType(contract); } if (generator.Errors.Count != 0) { throw new Exception("There were errors during code compilation."); } // Write the code dom System.CodeDom.Compiler.CodeGeneratorOptions options = new System.CodeDom.Compiler.CodeGeneratorOptions(); options.BracingStyle = "C"; System.CodeDom.Compiler.CodeDomProvider codeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("C#"); System.CodeDom.Compiler.IndentedTextWriter textWriter = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(outputFile)); codeDomProvider.GenerateCodeFromCompileUnit( generator.TargetCompileUnit, textWriter, options ); textWriter.Close(); }
public static void DumpSourceToStream(Node n, System.IO.TextWriter t) { Console.WriteLine("*** Begin Source dump: ["); System.CodeDom.Compiler.IndentedTextWriter i = new System.CodeDom.Compiler.IndentedTextWriter(t, " "); n.ToSource(i); Console.WriteLine("] *** End source dump"); i.Close(); i = null; }
/// <summary> /// Persists the artifact in a single file /// </summary> /// <param name="artifact"></param> /// <param name="productionContext"></param> private void PersistSingleFile(GeneratedArtifact artifact, ProductionContext productionContext) { string filePath = resolveTemplate(artifact.GroupFilePathTemplate, productionContext); Writer = Services.IOService.OpenIndentedTextWrite(filePath); // write begin file ArtifactBegin(); // write autogenerated infos AutogeneratedInfoBegin(); artifact.WriteAutogeneratedInfosTo(Writer); AutogeneratedInfoEnd(); // write artifact imports List<string> writtenImports = new List<string>(); artifact.WriteImportsTo(Writer, writtenImports); foreach (ArtifactDataItem artifactDataItem in artifact.ArtifactDataItems) { artifactDataItem.WriteImportsTo(Writer, writtenImports); } string ns = null; int baseIndent = 0; // namespace can be null if not required by target technology if (!string.IsNullOrEmpty(artifact.NamespaceTemplate)) { // open namespace ns = resolveTemplate(artifact.NamespaceTemplate, productionContext); baseIndent = OpenNamespace(ns); } // write artifact code lines foreach (ArtifactDataItem artifactDataItem in artifact.ArtifactDataItems) { artifactDataItem.WriteCodeLinesTo(Writer, baseIndent); } Writer.Indent = Math.Max(0, Writer.Indent - baseIndent); if (ns != null) { // close namespace CloseNamespace(ns); } // write end file ArtifactEnd(); Writer.Close(); }
/// <summary> /// Persist each <see cref="ArtifactDataItem"/> in its own file. /// </summary> /// <param name="artifact"></param> /// <param name="productionContext"></param> private void PersistMultiFile(GeneratedArtifact artifact, ProductionContext productionContext) { foreach (ArtifactDataItem artifactDataItem in artifact.ArtifactDataItems) { // create writer string filePath = resolveTemplate(artifact.ItemFilePathTemplate, productionContext); Writer = Services.IOService.OpenIndentedTextWrite(filePath); // write begin file ArtifactBegin(); // write autogenerated infos AutogeneratedInfoBegin(); artifact.WriteAutogeneratedInfosTo(Writer); AutogeneratedInfoEnd(); // write artifact imports List<string> writtenImports = new List<string>(); artifact.WriteImportsTo(Writer, writtenImports); // write artifact item imports artifactDataItem.WriteImportsTo(Writer, writtenImports); // resolve and open namespace string ns = resolveTemplate(artifact.NamespaceTemplate, productionContext); int baseIndent = OpenNamespace(ns); // write artifact item code lines artifactDataItem.WriteCodeLinesTo(Writer, baseIndent); // close namespace CloseNamespace(ns); // write end file ArtifactEnd(); Writer.Close(); } }
/// <summary> /// Generate proxy to the Web service. /// </summary> /// <param name="wsdlUrl"></param> /// <param name="generatedSourceFilename"></param> /// <param name="generatedNamespace"></param> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> public bool GenerateWsdlProxyClass(string wsdlUrl, string generatedSourceFilename, string generatedNamespace, string username, string password) { // erase the source file if (File.Exists(generatedSourceFilename)) File.Delete(generatedSourceFilename); // download the WSDL content into a service description WebClient http = new WebClient(); System.Web.Services.Description.ServiceDescription sd = null; if (!string.IsNullOrEmpty(username)) http.Credentials = new NetworkCredential(username, password); try { sd = System.Web.Services.Description.ServiceDescription.Read(http.OpenRead(wsdlUrl)); } catch (Exception ex) { this.ErrorMessage = "Wsdl Download failed: " + ex.Message; return false; } // create an importer and associate with the ServiceDescription ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); importer.ProtocolName = "SOAP"; importer.CodeGenerationOptions = CodeGenerationOptions.None; importer.AddServiceDescription(sd, null, null); // Download and inject any imported schemas (ie. WCF generated WSDL) foreach (XmlSchema wsdlSchema in sd.Types.Schemas) { // Loop through all detected imports in the main schema foreach (XmlSchemaObject externalSchema in wsdlSchema.Includes) { // Read each external schema into a schema object and add to importer if (externalSchema is XmlSchemaImport) { Uri baseUri = new Uri(wsdlUrl); Uri schemaUri = new Uri(baseUri, ((XmlSchemaExternal)externalSchema).SchemaLocation); Stream schemaStream = http.OpenRead(schemaUri); System.Xml.Schema.XmlSchema schema = XmlSchema.Read(schemaStream, null); importer.Schemas.Add(schema); } } } // set up for code generation by creating a namespace and adding to importer CodeNamespace ns = new CodeNamespace(generatedNamespace); CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(ns); importer.Import(ns, ccu); // final code generation in specified language CSharpCodeProvider provider = new CSharpCodeProvider(); System.CodeDom.Compiler.IndentedTextWriter tw = new System.CodeDom.Compiler.IndentedTextWriter(new StreamWriter(generatedSourceFilename)); provider.GenerateCodeFromCompileUnit(ccu, tw, new System.CodeDom.Compiler.CodeGeneratorOptions()); tw.Close(); return File.Exists(generatedSourceFilename); }
/// <summary> /// Generates the service model client code for the metadat set. /// </summary> /// <param name="metaDocs">The metadata set document.</param> /// <param name="codeFile">The output file to write the code to.</param> public static void GenerateServiceModelClient(MetadataSet metaDocs, string codeFile) { // Make sure the page reference exists. if (metaDocs == null) { throw new ArgumentNullException("metaDocs"); } if (codeFile == null) { throw new ArgumentNullException("codeFile"); } WsdlImporter importer = new WsdlImporter(metaDocs); ServiceContractGenerator generator = new ServiceContractGenerator(); // Add our custom DCAnnotationSurrogate // to write XSD annotations into the comments. object dataContractImporter; XsdDataContractImporter xsdDCImporter; if (!importer.State.TryGetValue(typeof(XsdDataContractImporter), out dataContractImporter)) { xsdDCImporter = new XsdDataContractImporter(); xsdDCImporter.Options = new ImportOptions(); importer.State.Add(typeof(XsdDataContractImporter), xsdDCImporter); } else { xsdDCImporter = (XsdDataContractImporter)dataContractImporter; if (xsdDCImporter.Options == null) { xsdDCImporter.Options = new ImportOptions(); } } // Get all the contract type bindings System.Collections.ObjectModel.Collection <ContractDescription> contracts = importer.ImportAllContracts(); // Generate all the contracts foreach (ContractDescription contract in contracts) { generator.GenerateServiceContractType(contract); } if (generator.Errors.Count != 0) { throw new System.Exception("There were errors during code compilation."); } // Write the code dom System.CodeDom.Compiler.CodeGeneratorOptions options = new System.CodeDom.Compiler.CodeGeneratorOptions(); options.BracingStyle = "C"; System.CodeDom.Compiler.IndentedTextWriter textWriter = null; try { // Write data to the code file. System.CodeDom.Compiler.CodeDomProvider codeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("C#"); textWriter = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(codeFile)); codeDomProvider.GenerateCodeFromCompileUnit(generator.TargetCompileUnit, textWriter, options); } finally { if (textWriter != null) { textWriter.Close(); } } }
static void Main(string[] args) { if (!args.Any()) { Console.Error.WriteLine("Needs a file as an argument"); return; } Debug.WriteLine("Input file is \"{0}\"", args.First()); var file = new StreamReader(args.First()); var levelstack = new Stack<int>(); // Parse mlst file List<Function> functions = new List<Function>(); List<string> @using = new List<string>(); @using.Add("JsonApi.Client"); @using.Add("JsonApi.Client.Classes"); @using.Add("JsonApi.Client.DataTypes"); @using.Add("System"); @using.Add("System.Collections.Generic"); @using.Add("System.Linq"); @using.Add("System.Text"); string @namespace = "JsonApi.Client.Extensions"; string @class = "CustomRequests"; Debug.WriteLine("Default imported namespaces: {0}", @using.Count); Debug.WriteLine("Default namespace: {0}", @namespace, null); // Yep, laziness found here. Debug.WriteLine("Default class: {0}", @class, null); string line = file.ReadLine().TrimEnd(); while (!file.EndOfStream) { Debug.WriteLine("Current line, expecting new function or compiler directive: Level {1} => {0}", line.Trim(), GetLevel(line)); if (string.IsNullOrWhiteSpace(line) || string.IsNullOrEmpty(line)) { Debug.WriteLine("Ignoring because empty."); line = file.ReadLine().TrimEnd(); continue; } if (line.StartsWith(".")) { // compiler command var lspl = line.Split(' '); var argline = string.Join(" ", lspl.Skip(1)); var argarray = lspl.Skip(1); Debug.WriteLine("Compiler command being processed: {0} (with {1} arguments)", lspl[0].ToLower().Substring(1), argarray.Count()); line = file.ReadLine().TrimEnd(); // for next processing, we should ignore that from now on. switch (lspl[0].ToLower().Substring(1)) { case "using": if ([email protected](argline, StringComparer.OrdinalIgnoreCase)) { Debug.WriteLine("Importing {0}", argline); @using.Add(argline); } else Console.Error.WriteLine("Warning: Tried adding \"using {0}\", but namespace has already been imported.", argline, null); break; case "namespace": Debug.WriteLine("Changing to namespace {0}", argline, null); @namespace = argline; break; case "class": Debug.WriteLine("Changing to class {0}", argline, null); @class = argline; break; } continue; } var cFunction = new Function(); cFunction.Name = line.Trim(); Debug.WriteLine("Generating new function: {0}", cFunction.Name, null); levelstack.Push(GetLevel(line)); // root level push line = file.ReadLine().TrimEnd(); while (line != null && !(line.TrimEnd() == "") && GetLevel(line) > levelstack.Peek()) { Debug.WriteLine("Current line, expecting new descriptive keyword: Level {1} => {0}", line.Trim(), GetLevel(line)); switch (line.Trim().ToLower()) { default: { Console.Error.WriteLine("Warning: Found unknown descriptive keyword \"{0}\", ignoring", line.Trim().ToLower(), null); line = file.ReadLine().TrimEnd(); } break; case "description": { Debug.WriteLine("Found description for {0}", cFunction.Name, null); if (!string.IsNullOrEmpty(cFunction.Description)) { throw new Exception(string.Format("Function \"{0}\" already contains a description. Can't define twice.", cFunction.Name)); } StringBuilder descriptionBuilder = new StringBuilder(); levelstack.Push(GetLevel(line)); // command level push while (GetLevel(line = file.ReadLine()) > levelstack.Peek()) { Debug.WriteLine("Adding 1 line to description"); descriptionBuilder.AppendLine(line.Trim()); } levelstack.Pop(); // command level pop cFunction.Description = descriptionBuilder.ToString().Trim(); Debug.WriteLine("Description: {0}", cFunction.Description, null); } break; case "arguments": { Debug.WriteLine("Found arguments for {0}", cFunction.Name, null); levelstack.Push(GetLevel(line)); // command level push line = file.ReadLine().TrimEnd(); while (GetLevel(line) > levelstack.Peek()) { var spl = line.Trim().Split(' '); var type = new DataType() { TypeName = spl[0] }; var name = string.Empty; if (spl.Length > 1) name = spl.Last(); else { name = "arg" + cFunction.Arguments.Count; } Debug.WriteLine("Adding argument {0} of type {1}", name, type.TypeName); StringBuilder descriptionBuilder = new StringBuilder(); levelstack.Push(GetLevel(line)); // argument level push while (GetLevel(line = file.ReadLine()) > levelstack.Peek()) { Debug.WriteLine("Adding 1 line to description"); descriptionBuilder.AppendLine(line.Trim()); } levelstack.Pop(); // argument level pop type.Description = descriptionBuilder.ToString().Trim(); cFunction.Arguments.Add(name, type); } levelstack.Pop(); // command level pop } break; case "return": case "returns": { var type = new DataType() { TypeName = (line = file.ReadLine()).Trim() }; Debug.WriteLine("Found return type {0}", type.TypeName, null); StringBuilder descriptionBuilder = new StringBuilder(); levelstack.Push(GetLevel(line)); // command level push while (GetLevel(line = file.ReadLine()) > levelstack.Peek()) descriptionBuilder.AppendLine(line.Trim()); levelstack.Pop(); // command level pop type.Description = descriptionBuilder.ToString().Trim(); cFunction.ReturnType = type; } break; } } levelstack.Pop(); // root level pop functions.Add(cFunction); } // using directives var stream = Console.OpenStandardOutput(); var streamwriter = new System.CodeDom.Compiler.IndentedTextWriter(new StreamWriter(stream)); foreach (string importedNamespace in @using) streamwriter.WriteLine("using {0};", importedNamespace); // Start namespace streamwriter.WriteLine("namespace {0}", @namespace); streamwriter.WriteLine("{"); streamwriter.Indent++; // Start class streamwriter.WriteLine("public static class {0}", @class); streamwriter.WriteLine("{"); streamwriter.Indent++; // Functions foreach (var function in functions) { // Fix return type if (function.ReturnType == null) function.ReturnType = new DataType() { TypeName = "void" }; if (function.ReturnType.TypeName.Equals("boolean", StringComparison.OrdinalIgnoreCase)) function.ReturnType.TypeName = "bool"; // Fix argument types foreach (var aName in function.Arguments.Keys) { var aVal = function.Arguments[aName]; if (aVal.TypeName.Equals("boolean", StringComparison.OrdinalIgnoreCase)) aVal.TypeName = "bool"; } // Request generation function foreach (string l in function.GetMetadataXml().Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries)) streamwriter.WriteLine("/// {0}", l.Trim(), null); streamwriter.Flush(); streamwriter.WriteLine("public static StandardAPIRequest {0}({1})", function.NormalizedName, function.GetParameterSignature()); streamwriter.Write("{ "); streamwriter.Write("return new StandardAPIRequest(\"{0}\"{1});", function.Name, function.Arguments.Count > 0 ? ", " + function.GetParameterPass() : ""); streamwriter.WriteLine(" }"); streamwriter.WriteLine(); streamwriter.Flush(); // Actual standard API request function foreach (string l in function.GetMetadataXml().Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries)) streamwriter.WriteLine("/// {0}", l.Trim(), null); streamwriter.Flush(); streamwriter.WriteLine("public static {2} {0}(this Client client{1})", function.NormalizedName, function.Arguments.Count > 0 ? ", " + function.GetParameterSignature() : "", function.ReturnType == null ? "void" : function.ReturnType.TypeName); streamwriter.Write("{ "); if(function.ReturnType != null && function.ReturnType.TypeName != "void") streamwriter.Write("return client.Request<{2}>({0}({1}));", function.NormalizedName, function.GetParameterPass(), function.ReturnType.TypeName); else streamwriter.Write("client.Request({0}({1}));", function.NormalizedName, function.GetParameterPass()); streamwriter.WriteLine(" }"); streamwriter.WriteLine(); streamwriter.Flush(); } // End class streamwriter.Indent--; streamwriter.WriteLine("}"); // End namespace streamwriter.Indent--; streamwriter.WriteLine("}"); // Finalize streamwriter.Flush(); streamwriter.Close(); streamwriter.Dispose(); }