public void GenerateDataset() { if (namesp == null) { namesp = ""; } if (uri == null) { uri = ""; } string targetFile = ""; DataSet dataset = new DataSet(); foreach (string fileName in schemaNames) { dataset.ReadXmlSchema(fileName); if (targetFile == "") { targetFile = Path.GetFileNameWithoutExtension(fileName); } else { targetFile += "_" + Path.GetFileNameWithoutExtension(fileName); } } targetFile += "." + provider.FileExtension; CodeCompileUnit cunit = new CodeCompileUnit(); CodeNamespace codeNamespace = new CodeNamespace(namesp); cunit.Namespaces.Add(codeNamespace); codeNamespace.Comments.Add(new CodeCommentStatement("\nThis source code was auto-generated by MonoXSD\n")); // Generate the code ICodeGenerator gen = provider.CreateGenerator(); TypedDataSetGenerator.Generate(dataset, codeNamespace, gen); string genFile = Path.Combine(outputDir, targetFile); StreamWriter sw = new StreamWriter(genFile, false); gen.GenerateCodeFromCompileUnit(cunit, sw, new CodeGeneratorOptions()); sw.Close(); Console.WriteLine("Written file " + genFile); }
public static bool TryCreateGenerator(Type dataSetType, out DataSetGenerator generator) { generator = default; if (dataSetType == typeof(DataSet)) { generator = new UntypedDataSetGenerator(); } else if (typeof(DataSet).IsAssignableFrom(dataSetType)) { generator = new TypedDataSetGenerator(dataSetType); } return(generator != null); }
public void RelationConnectsSameTable() { DataSet ds = new DataSet(); ds.ReadXmlSchema("Test/System.Data/schemas/bug77248.xsd"); CodeNamespace cns = new CodeNamespace(); TypedDataSetGenerator.Generate(ds, cns, gen); CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cns); CompilerResults r = compiler.CompileAssemblyFromDom( new CompilerParameters(), ccu); Assert.AreEqual(0, r.Errors.Count); }
public void TestGenerateIdName() { Assert.AreEqual("a", TypedDataSetGenerator.GenerateIdName("a", gen), "#1"); Assert.AreEqual("_int", TypedDataSetGenerator.GenerateIdName("int", gen), "#2"); Assert.AreEqual("_", TypedDataSetGenerator.GenerateIdName("_", gen), "#3"); Assert.AreEqual("_", TypedDataSetGenerator.GenerateIdName("_", gen), "#3-2"); Assert.AreEqual("_1", TypedDataSetGenerator.GenerateIdName("1", gen), "#4"); Assert.AreEqual("_1", TypedDataSetGenerator.GenerateIdName("1", gen), "#4-2"); Assert.AreEqual("_1a", TypedDataSetGenerator.GenerateIdName("1a", gen), "#5"); Assert.AreEqual("_1_2", TypedDataSetGenerator.GenerateIdName("1*2", gen), "#6"); Assert.AreEqual("__", TypedDataSetGenerator.GenerateIdName("-", gen), "#7"); Assert.AreEqual("__", TypedDataSetGenerator.GenerateIdName("+", gen), "#8"); Assert.AreEqual("_", TypedDataSetGenerator.GenerateIdName("", gen), "#9"); Assert.AreEqual("___", TypedDataSetGenerator.GenerateIdName("--", gen), "#10"); Assert.AreEqual("___", TypedDataSetGenerator.GenerateIdName("++", gen), "#11"); Assert.AreEqual("\u3042", TypedDataSetGenerator.GenerateIdName("\u3042", gen), "#12"); }
public void TestGenerateIdName() { AssertEquals("#1", "a", TypedDataSetGenerator.GenerateIdName("a", gen)); AssertEquals("#2", "_int", TypedDataSetGenerator.GenerateIdName("int", gen)); AssertEquals("#3", "_", TypedDataSetGenerator.GenerateIdName("_", gen)); AssertEquals("#3-2", "_", TypedDataSetGenerator.GenerateIdName("_", gen)); AssertEquals("#4", "_1", TypedDataSetGenerator.GenerateIdName("1", gen)); AssertEquals("#4-2", "_1", TypedDataSetGenerator.GenerateIdName("1", gen)); AssertEquals("#5", "_1a", TypedDataSetGenerator.GenerateIdName("1a", gen)); AssertEquals("#6", "_1_2", TypedDataSetGenerator.GenerateIdName("1*2", gen)); AssertEquals("#7", "__", TypedDataSetGenerator.GenerateIdName("-", gen)); AssertEquals("#8", "__", TypedDataSetGenerator.GenerateIdName("+", gen)); AssertEquals("#9", "_", TypedDataSetGenerator.GenerateIdName("", gen)); AssertEquals("#10", "___", TypedDataSetGenerator.GenerateIdName("--", gen)); AssertEquals("#11", "___", TypedDataSetGenerator.GenerateIdName("++", gen)); AssertEquals("#12", "\u3042", TypedDataSetGenerator.GenerateIdName("\u3042", gen)); }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { string namespaceFromVirtualPath = Util.GetNamespaceFromVirtualPath(base.VirtualPathObject); XmlDocument document = new XmlDocument(); using (Stream stream = base.OpenStream()) { document.Load(stream); } string outerXml = document.OuterXml; CodeCompileUnit compileUnit = new CodeCompileUnit(); CodeNamespace namespace2 = new CodeNamespace(namespaceFromVirtualPath); compileUnit.Namespaces.Add(namespace2); if (CompilationUtil.IsCompilerVersion35OrAbove(assemblyBuilder.CodeDomProvider.GetType())) { TypedDataSetGenerator.GenerateOption none = TypedDataSetGenerator.GenerateOption.None; none |= TypedDataSetGenerator.GenerateOption.HierarchicalUpdate; none |= TypedDataSetGenerator.GenerateOption.LinqOverTypedDatasets; Hashtable customDBProviders = null; TypedDataSetGenerator.Generate(outerXml, compileUnit, namespace2, assemblyBuilder.CodeDomProvider, customDBProviders, none); } else { TypedDataSetGenerator.Generate(outerXml, compileUnit, namespace2, assemblyBuilder.CodeDomProvider); } if (TypedDataSetGenerator.ReferencedAssemblies != null) { bool flag2 = CompilationUtil.IsCompilerVersion35(assemblyBuilder.CodeDomProvider.GetType()); foreach (Assembly assembly in TypedDataSetGenerator.ReferencedAssemblies) { if (flag2) { AssemblyName name = assembly.GetName(); if (name.Name == "System.Data.DataSetExtensions") { name.Version = new Version(3, 5, 0, 0); CompilationSection.RecordAssembly(name.FullName, assembly); } } assemblyBuilder.AddAssemblyReference(assembly); } } assemblyBuilder.AddCodeCompileUnit(this, compileUnit); }
private void GenerateCode(ServiceDescriptionCollection sources, XmlSchemas schemas, string uriToWSDL, ICodeGenerator codeGen, string fileExtension) { proxyCode = " <ERROR> "; StringWriter w = null; compileUnit = new CodeCompileUnit(); var importer = new ServiceDescriptionImporter(); importer.Schemas.Add(schemas); foreach (ServiceDescription description in sources) { importer.AddServiceDescription(description, "", ""); } importer.Style = ServiceDescriptionImportStyle.Client; Protocol protocol = WsdlProperties.Protocol; importer.ProtocolName = WsdlProperties.Protocol.ToString(); var namespace2 = new CodeNamespace(proxyNamespace); compileUnit.Namespaces.Add(namespace2); ServiceDescriptionImportWarnings warnings = importer.Import(namespace2, compileUnit); try { try { w = new StringWriter(); } catch { throw; } MemoryStream stream = null; if (schemas.Count > 0) { compileUnit.ReferencedAssemblies.Add("System.Data.dll"); foreach (XmlSchema schema in schemas) { string targetNamespace = null; try { targetNamespace = schema.TargetNamespace; if (XmlSchemas.IsDataSet(schema)) { if (stream == null) { stream = new MemoryStream(); } stream.Position = 0L; stream.SetLength(0L); schema.Write(stream); stream.Position = 0L; var dataSet = new DataSet(); dataSet.ReadXmlSchema(stream); TypedDataSetGenerator.Generate(dataSet, namespace2, codeGen); } } catch { throw; } } } try { GenerateVersionComment(compileUnit.Namespaces[0]); ChangeBaseType(compileUnit); codeGen.GenerateCodeFromCompileUnit(compileUnit, w, null); } catch (Exception exception) { if (w != null) { w.Write("Exception in generating code"); w.Write(exception.Message); } throw new InvalidOperationException("Error generating ", exception); } } finally { proxyCode = w.ToString(); if (w != null) { w.Close(); } } }
private void GenerateCode(ServiceDescriptionCollection sources, XmlSchemas schemas, string uriToWSDL, ICodeGenerator codeGen, string fileExtension) { proxyCode = " <ERROR> "; StringWriter writer1 = null; compileUnit = new CodeCompileUnit(); ServiceDescriptionImporter importer1 = new ServiceDescriptionImporter(); importer1.Schemas.Add(schemas); foreach (ServiceDescription description1 in sources) { importer1.AddServiceDescription(description1, "", ""); } importer1.Style = ServiceDescriptionImportStyle.Client; Protocol protocol1 = WsdlProperties.Protocol; importer1.ProtocolName = WsdlProperties.Protocol.ToString(); CodeNamespace namespace1 = new CodeNamespace(proxyNamespace); compileUnit.Namespaces.Add(namespace1); ServiceDescriptionImportWarnings warnings1 = importer1.Import(namespace1, compileUnit); try { try { writer1 = new StringWriter(); } catch { throw; } MemoryStream stream1 = null; if (schemas.Count > 0) { compileUnit.ReferencedAssemblies.Add("System.Data.dll"); foreach (XmlSchema schema1 in schemas) { string text1 = null; try { text1 = schema1.TargetNamespace; if (XmlSchemas.IsDataSet(schema1)) { if (stream1 == null) { stream1 = new MemoryStream(); } stream1.Position = 0; stream1.SetLength((long)0); schema1.Write(stream1); stream1.Position = 0; DataSet set1 = new DataSet(); set1.ReadXmlSchema(stream1); TypedDataSetGenerator.Generate(set1, namespace1, codeGen); } continue; } catch { throw; } } } try { GenerateVersionComment(compileUnit.Namespaces[0]); ChangeBaseType(compileUnit); codeGen.GenerateCodeFromCompileUnit(compileUnit, writer1, null); } catch (Exception exception1) { if (writer1 != null) { writer1.Write("Exception in generating code"); writer1.Write(exception1.Message); } throw new InvalidOperationException("Error generating ", exception1); } } finally { proxyCode = writer1.ToString(); if (writer1 != null) { writer1.Close(); } } }
public void TestGenerateIdNameNullProvider() { TypedDataSetGenerator.GenerateIdName("a", null); }
public void TestGenerateIdNameNullName() { TypedDataSetGenerator.GenerateIdName(null, gen); }
/// <summary> /// Builds the assembly from WSDL. /// </summary> /// <param name="strWsdl">STR WSDL.</param> /// <returns></returns> private Assembly BuildAssemblyFromWsdl(string strWsdl) { // Use an XmlTextReader to get the Web Service description StringReader wsdlStringReader = new StringReader(strWsdl); XmlTextReader tr = new XmlTextReader(wsdlStringReader); ServiceDescription.Read(tr); tr.Close(); // WSDL service description importer CodeNamespace cns = new CodeNamespace(CodeConstants.CODENAMESPACE); sdi = new ServiceDescriptionImporter(); //sdi.AddServiceDescription(sd, null, null); // check for optional imports in the root WSDL CheckForImports(wsdl); sdi.ProtocolName = protocolName; sdi.Import(cns, null); // change the base class // get all available Service classes - not only the default one ArrayList newCtr = new ArrayList(); foreach (CodeTypeDeclaration ctDecl in cns.Types) { if (ctDecl.BaseTypes.Count > 0) { if (ctDecl.BaseTypes[0].BaseType == CodeConstants.DEFAULTBASETYPE) { newCtr.Add(ctDecl); } } } foreach (CodeTypeDeclaration ctDecl in newCtr) { cns.Types.Remove(ctDecl); ctDecl.BaseTypes[0] = new CodeTypeReference(CodeConstants.CUSTOMBASETYPE); cns.Types.Add(ctDecl); } // source code generation CSharpCodeProvider cscp = new CSharpCodeProvider(); ICodeGenerator icg = cscp.CreateGenerator(); StringBuilder srcStringBuilder = new StringBuilder(); StringWriter sw = new StringWriter(srcStringBuilder, CultureInfo.CurrentCulture); if (schemas != null) { foreach (XmlSchema xsd in schemas) { if (XmlSchemas.IsDataSet(xsd)) { MemoryStream mem = new MemoryStream(); mem.Position = 0; xsd.Write(mem); mem.Position = 0; DataSet dataSet1 = new DataSet(); dataSet1.Locale = CultureInfo.InvariantCulture; dataSet1.ReadXmlSchema(mem); TypedDataSetGenerator.Generate(dataSet1, cns, icg); } } } icg.GenerateCodeFromNamespace(cns, sw, null); proxySource = srcStringBuilder.ToString(); sw.Close(); // assembly compilation string location = ""; if (HttpContext.Current != null) { location = HttpContext.Current.Server.MapPath("."); location += @"\bin\"; } CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add("System.Xml.dll"); cp.ReferencedAssemblies.Add("System.Web.Services.dll"); cp.ReferencedAssemblies.Add("System.Data.dll"); cp.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); cp.ReferencedAssemblies.Add(location + "Thinktecture.Tools.Web.Services.Extensions.Messages.dll"); cp.GenerateExecutable = false; cp.GenerateInMemory = false; cp.IncludeDebugInformation = false; cp.TempFiles = new TempFileCollection(CompiledAssemblyCache.GetLibTempPath()); ICodeCompiler icc = cscp.CreateCompiler(); CompilerResults cr = icc.CompileAssemblyFromSource(cp, proxySource); if (cr.Errors.Count > 0) { throw new DynamicCompilationException(string.Format(CultureInfo.CurrentCulture, @"Building dynamic assembly failed: {0} errors", cr.Errors.Count)); } Assembly compiledAssembly = cr.CompiledAssembly; //rename temporary assembly in order to cache it for later use CompiledAssemblyCache.RenameTempAssembly(cr.PathToAssembly, wsdl); return(compiledAssembly); }
static void Main() { ArgItemCollection argitems = new ArgItemCollection(); argitems.Add(new ArgItem("xsd", null, ArgTypeEnum.Path, false)); argitems.Add(new ArgItem("paramfile", null, ArgTypeEnum.Path, false)); argitems.Add(new ArgItem("adapter", null, ArgTypeEnum.Text, false)); argitems.Add(new ArgItem("method", null, ArgTypeEnum.Text, false)); argitems.Add(new ArgItem("sql", null, ArgTypeEnum.Text, false)); argitems.Add(new ArgItem("query", null, ArgTypeEnum.Text, false)); argitems.Add(new ArgItem("paramname", null, ArgTypeEnum.Text, false)); argitems.Add(new ArgItem("paramtype", null, ArgTypeEnum.Text, false)); argitems.Add(new ArgItem("paramsize", null, ArgTypeEnum.Number, false)); argitems.Add(new ArgItem("regen", null, ArgTypeEnum.Text, false)); StreamReader sr = null; try { string line = Environment.CommandLine; argitems.LoadArgs(line, true); // load up the xsd file contents into a string. if (!argitems.GetArgItem("xsd").Specified) { throw new Exception("Requiring parameter missing: -xsd"); } string xsdfile = argitems["xsd"]; XDocument xsd = XDocument.Load(xsdfile); // either process a file of operations or just process the command line if (argitems.GetArgItem("paramfile").Specified) { // check no other parameters specified if (argitems.GetArgItem("adapter").Specified || argitems.GetArgItem("method").Specified || argitems.GetArgItem("sql").Specified || argitems.GetArgItem("query").Specified || argitems.GetArgItem("paramname").Specified || argitems.GetArgItem("paramtype").Specified) { throw new Exception("Invalid commandline. If -paramfile specified all other parameters must be in the file."); } // read each line from the file and load args try { sr = new StreamReader(argitems["paramfile"]); int lineno = 0; while (!sr.EndOfStream) { line = sr.ReadLine(); if ((line.Length > 0) && (line[0] != ':')) // blank line or : (comment) skipped { argitems.Reset(); argitems.LoadArgs(line, false); if (argitems.GetArgItem("xsd").Specified || argitems.GetArgItem("paramfile").Specified || argitems.GetArgItem("regen").Specified) { throw GetException("-xsd, -paramfile, -regen are invalid in a paramfile. ", lineno, line); } Process(xsd, argitems, lineno, line); } lineno++; } sr.Close(); } finally { if (sr != null) { sr.Close(); } } } else { Process(xsd, argitems, -1, line); } // write out the modified xsd file // create backup //xsdfile string tempfile = Path.ChangeExtension(xsdfile, ".temp.xsd"); string bakfile = Path.ChangeExtension(xsdfile, ".xsd.bak"); xsd.Save(tempfile); File.Delete(bakfile); File.Move(xsdfile, bakfile); File.Move(tempfile, xsdfile); Console.WriteLine("FixXSD: .xsd File processed successfully."); if (argitems.GetArgItem("regen").Specified) { string nspace = argitems["regen"]; if (string.IsNullOrEmpty(nspace)) { nspace = Path.GetFileNameWithoutExtension(xsdfile); } sr = null; string xsdfilecontent = null; try { sr = new StreamReader(xsdfile); xsdfilecontent = sr.ReadToEnd(); sr.Close(); } finally { if (sr != null) { sr.Close(); } } StreamWriter filewriter = null; try { var codeCompileUnit = new CodeCompileUnit(); var codeNamespace = new CodeNamespace(argitems["n"]); Dictionary <string, string> providerOptions = new Dictionary <string, string>(); providerOptions.Add("CompilerVersion", "v4"); var codeDomProvider = CodeDomProvider.CreateProvider("CSharp", providerOptions); TypedDataSetGenerator.Generate(xsdfilecontent, codeCompileUnit, codeNamespace, codeDomProvider, TypedDataSetGenerator.GenerateOption.HierarchicalUpdate | TypedDataSetGenerator.GenerateOption.LinqOverTypedDatasets); string outputfile = Path.ChangeExtension(xsdfile, ".designer.cs"); bakfile = outputfile + ".bak"; File.Delete(bakfile); File.Move(outputfile, bakfile); filewriter = new StreamWriter(outputfile, false); var generatorOptions = new CodeGeneratorOptions(); var cscodeprovider = new CSharpCodeProvider(); cscodeprovider.GenerateCodeFromNamespace(codeNamespace, filewriter, generatorOptions); cscodeprovider.GenerateCodeFromCompileUnit(codeCompileUnit, filewriter, generatorOptions); Console.Write("FixXSD: TypedDataSet (.designer.cs) regenerated sucessfully."); } finally { if (filewriter != null) { filewriter.Close(); } } } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(usage); #if DEBUG Console.ReadKey(); #endif return; } }
static void Main() { // define and parse arguments. Default implementation can't handle paths or quoted arguments properly. ArgItemCollection argitems = new ArgItemCollection(); argitems.Add(new ArgItem("in", "i", ArgTypeEnum.Path, true)); argitems.Add(new ArgItem("out", "o", ArgTypeEnum.Path, false)); argitems.Add(new ArgItem("namespace", "n", ArgTypeEnum.Text, false)); try { MDWCLUtil.LoadArgs(argitems, Environment.CommandLine); } catch (Exception ex) { Console.WriteLine(MDWCLUtil.GetExceptionText(ex)); Console.WriteLine(usage); #if DEBUG Console.ReadKey(); #endif return; } if (!argitems.GetArgItem("out").Specified) { argitems["out"] = Path.ChangeExtension(argitems["in"], ".designer.cs"); } if (!argitems.GetArgItem("namespace").Specified) { argitems["namespace"] = Path.GetFileNameWithoutExtension(argitems["in"]); } StreamReader sr = null; string xsdFileContent = null; try { // read the input file and store in xsdFileContent sr = new StreamReader(argitems["in"]); xsdFileContent = sr.ReadToEnd(); sr.Close(); } finally { if (sr != null) { sr.Close(); } } StreamWriter filewriter = null; try { var codeCompileUnit = new CodeCompileUnit(); var codeNamespace = new CodeNamespace(argitems["namespace"]); Dictionary <string, string> providerOptions = new Dictionary <string, string>(); providerOptions.Add("CompilerVersion", "v4"); // HierarchicalUpdate = create a TableAdapterManager, TypedDataSetGenerator.Generate(xsdFileContent, codeCompileUnit, codeNamespace, CodeDomProvider.CreateProvider("CSharp", providerOptions), TypedDataSetGenerator.GenerateOption.HierarchicalUpdate | TypedDataSetGenerator.GenerateOption.LinqOverTypedDatasets); filewriter = new StreamWriter(argitems["out"], false); var cscodeprovider = new CSharpCodeProvider(); var generatorOptions = new CodeGeneratorOptions(); // no idea why need both of these, you just do. Discovered this by dumb luck. cscodeprovider.GenerateCodeFromNamespace(codeNamespace, filewriter, generatorOptions); cscodeprovider.GenerateCodeFromCompileUnit(codeCompileUnit, filewriter, generatorOptions); filewriter.Close(); filewriter = null; } catch (Exception ex) { Console.WriteLine(MDWCLUtil.GetExceptionText(ex)); Console.WriteLine(usage); #if DEBUG Console.ReadKey(); #endif } finally { if (filewriter != null) { filewriter.Close(); } } }