public static object InvokeWebService(string url, string classname, string methodname, object[] args) { string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling"; if ((classname == null) || (classname == "")) { classname = WebServiceProxy.GetWsClassName(url); } try { //获取WSDL WebClient wc = new WebClient(); Stream stream = wc.OpenRead(url + "?WSDL"); ServiceDescription sd = ServiceDescription.Read(stream); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(@namespace); //生成客户端代理类代码 CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider csc = new CSharpCodeProvider(); ICodeCompiler icc = csc.CreateCompiler(); //设定编译参数 CompilerParameters cplist = new CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } //生成代理实例,并调用方法 System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(@namespace + "." + classname, true, true); object obj = Activator.CreateInstance(t); System.Reflection.MethodInfo mi = t.GetMethod(methodname); return mi.Invoke(obj, args); } catch (Exception ex) { throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); } }
static CodeNamespace BuildProgram() { // namespaceの作成 var ns = new CodeNamespace("MetaWorld"); // import編成 var systemImport = new CodeNamespaceImport("System"); // class作成 var programClass = new CodeTypeDeclaration("Program"); // mainメソッドの定義 var methodMain = new CodeMemberMethod() { Attributes = MemberAttributes.Static, Name = "Main" }; methodMain.Statements.Add( new CodeMethodInvokeExpression( new CodeSnippetExpression("Console"), "WriteLine", new CodePrimitiveExpression("Hello World") ) ); // コード構造の編成 programClass.Members.Add(methodMain); ns.Imports.Add(systemImport); ns.Types.Add(programClass); return ns; }
protected override void Generate(CodeNamespace nameSpace) { if (!config.SkipInterfaceTypeInfo) { GenerateStatic(nameSpace); } }
public CodeObject CreateCodeObject() { var conditions = _types .Select(CreateNumberSetValueCondition) .Concat(_types .Concat(_arrayTypes) .Select(CreateArraySetValueCondition)); var firstCondition = conditions.First(); var currentCondition = firstCondition; foreach (var condition in conditions.Skip(1)) { currentCondition.FalseStatements.Add(condition); currentCondition = condition; } currentCondition.FalseStatements.Add(CodeHelper.Return(CodeHelper.False())); var type = new CodeTypeDeclaration("AphidObject") { IsPartial = true }; type.Members.Add(TrySetProperty(firstCondition)); var ns = new CodeNamespace(); ns.Imports.Add(new CodeNamespaceImport("System.Linq")); ns.Name = "Components.Aphid.Interpreter"; ns.Types.Add(type); var unit = new CodeCompileUnit(); unit.Namespaces.Add(ns); return unit; }
public void CreateModels(IEnumerable<OvhApi> apis) { Dictionary<string,ModelType> modelsByNamespace = new Dictionary<string, ModelType>(); foreach (var ovhApi in apis) { foreach (var model in ovhApi.Models) { string fullTypeName = Util.GetType(model.Key); if (modelsByNamespace.ContainsKey(fullTypeName)) continue; modelsByNamespace.Add(fullTypeName, new ModelType(model.Value)); } } foreach (var st in modelsByNamespace) { string modelNamespace = Util.GetNamespace(st.Value.Model); if (modelsByNamespace.ContainsKey(modelNamespace)) { modelsByNamespace[modelNamespace].AddChild(st.Value); } } foreach (var type in modelsByNamespace.Where(x => x.Value.Parent == null)) { CodeNamespace ns = new CodeNamespace(Util.GetNamespace(type.Value.Model)); ns.Types.Add(CreateType(type.Value)); _code.Namespaces.Add(ns); } }
public string CreateSpecs(out int specCount) { var files = FindSpecFiles().ToArray(); specCount = files.Length; if (specCount < 1) return string.Empty; var compile = new CodeCompileUnit(); var globalns = new CodeNamespace(); globalns.Imports.Add(new CodeNamespaceImport("NUnit.Framework")); globalns.Imports.Add(new CodeNamespaceImport(config.MyNamespace)); compile.Namespaces.Add(globalns); var specNamespace = new CodeNamespace(config.TargetNamespace + ".ChutzpahSpecs"); compile.Namespaces.Add(specNamespace); foreach (var fileInfo in files) { AddSpec(specNamespace, fileInfo); } //specNamespace.Types.AddRange(files.Select(CreateSpec).ToArray()); var provider = CreateProvider(); var options = new CodeGeneratorOptions { BracingStyle = "C", BlankLinesBetweenMembers = false }; var stringBuilder = new StringBuilder(); using (var writer = new StringWriter(stringBuilder)) { provider.GenerateCodeFromCompileUnit(compile, writer, options); writer.Flush(); writer.Close(); } var result = stringBuilder.ToString(); return result; }
// Builds a codedom delegate expression and attaches it to the given codedom namespace. public static void Emit(CodeNamespace codeNamespace, DelegateDeclaration del) { // Create the codedom delegate and attach it to the namespace. var codeDelegate = new CodeTypeDelegate(); codeNamespace.Types.Add(codeDelegate); // Assign the name of the delegate codeDelegate.Name = del.Name; // Set the type of the delegate: make sure to check for null if (del.ReturnTypeName == "void") codeDelegate.ReturnType = null; else codeDelegate.ReturnType = new CodeTypeReference(del.ReturnTypeName); // Translate the accessibililty of the delegate MemberAttributes attributes = MemberAttributes.Public; switch(del.Accessibility) { case Accessibility.Public: attributes = MemberAttributes.Public; break; case Accessibility.Protected: attributes = MemberAttributes.Family; break; case Accessibility.Private: attributes = MemberAttributes.Private; break; case Accessibility.Internal: attributes = MemberAttributes.FamilyAndAssembly; break; } // Shared = static if (del.IsShared) attributes |= MemberAttributes.Static; codeDelegate.Attributes = attributes; // Translate the parameters of the delegate. foreach (Expression p in del.Parameters) { if (p is SimpleParameter) // ex "int i" codeDelegate.Parameters.Add(new CodeParameterDeclarationExpression((p as SimpleParameter).TypeName, (p as SimpleParameter).Name)); if (p is DirectionedParameter) // ex "ref int t" { var codeParameter = new CodeParameterDeclarationExpression((p as DirectionedParameter).TypeName, (p as DirectionedParameter).Name); switch ((p as DirectionedParameter).Direction) { case ParameterDirection.Out: codeParameter.Direction = FieldDirection.Out; break; case ParameterDirection.Ref: codeParameter.Direction = FieldDirection.Ref; break; } codeDelegate.Parameters.Add(codeParameter); } } }
public ImproveEnumFieldsCommand(CodeNamespace code) { if (code == null) throw new ArgumentNullException("code"); this.code = code; }
public override void Execute(System.CodeDom.CodeNamespace codeNamespace) { foreach (CodeTypeDeclaration type in codeNamespace.Types) { if (!type.IsClass) { continue; } CodeAttributeDeclaration declToRemove = null; foreach (CodeAttributeDeclaration decl in type.CustomAttributes) { if (decl.Name == "System.Diagnostics.DebuggerStepThroughAttribute") { declToRemove = decl; break; } } if (declToRemove != null) { type.CustomAttributes.Remove(declToRemove); } } }
public override void ProcessGeneratedCode(CodeCompileUnit codeCompileUnit, CodeNamespace generatedNamespace, CodeTypeDeclaration generatedClass, CodeMemberMethod executeMethod) { base.ProcessGeneratedCode(codeCompileUnit, generatedNamespace, generatedClass, executeMethod); // Create the Href wrapper CodeTypeMember hrefMethod = new CodeSnippetTypeMember(@" // Resolve package relative syntax // Also, if it comes from a static embedded resource, change the path accordingly public override string Href(string virtualPath, params object[] pathParts) { virtualPath = ApplicationPart.ProcessVirtualPath(GetType().Assembly, VirtualPath, virtualPath); return base.Href(virtualPath, pathParts); }"); generatedClass.Members.Add(hrefMethod); Debug.Assert(generatedClass.Name.Length > 0); if (!(Char.IsLetter(generatedClass.Name[0]) || generatedClass.Name[0] == '_')) { generatedClass.Name = '_' + generatedClass.Name; } // If the generatedClass starts with an underscore, add a ClsCompliant(false) attribute. if (generatedClass.Name[0] == '_') { generatedClass.CustomAttributes.Add(new CodeAttributeDeclaration(typeof(CLSCompliantAttribute).FullName, new CodeAttributeArgument(new CodePrimitiveExpression(false)))); } }
public override string ImportSchemaType(XmlSchemaType type, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider) { if (type == null) { return null; } if (importedTypes[type] != null) { mainNamespace.Imports.Add(new CodeNamespaceImport(typeof(DataSet).Namespace)); compileUnit.ReferencedAssemblies.Add("System.Data.dll"); return (string)importedTypes[type]; } if (!(context is XmlSchemaElement)) return null; if (type is XmlSchemaComplexType) { XmlSchemaComplexType ct = (XmlSchemaComplexType)type; if (ct.Particle is XmlSchemaSequence) { XmlSchemaObjectCollection items = ((XmlSchemaSequence)ct.Particle).Items; if (items.Count == 2 && items[0] is XmlSchemaAny && items[1] is XmlSchemaAny) { XmlSchemaAny any0 = (XmlSchemaAny)items[0]; XmlSchemaAny any1 = (XmlSchemaAny)items[1]; if (any0.Namespace == XmlSchema.Namespace && any1.Namespace == "urn:schemas-microsoft-com:xml-diffgram-v1") { string typeName = typeof(DataTable).FullName; importedTypes.Add(type, typeName); mainNamespace.Imports.Add(new CodeNamespaceImport(typeof(DataTable).Namespace)); compileUnit.ReferencedAssemblies.Add("System.Data.dll"); return typeName; } } } } return null; }
public void CodeSnippetBlankLines () { var opt = new CodeGeneratorOptions () { BlankLinesBetweenMembers = false, VerbatimOrder = false }; var ccu = new CodeCompileUnit (); var ns = new CodeNamespace ("Foo"); ccu.Namespaces.Add (ns); var t = new CodeTypeDeclaration ("Bar"); ns.Types.Add (t); t.Members.Add (new CodeSnippetTypeMember ("#line hidden")); t.Members.Add (new CodeSnippetTypeMember ("#line hidden2")); t.Members.Add (new CodeMemberMethod () { Name = "Foo" }); using (var sw = new StringWriter ()) { new CSharpCodeProvider ().GenerateCodeFromCompileUnit (ccu, sw, opt); var str = sw.ToString (); Assert.IsFalse (str.Contains ("hidden2private"), "#0"); Assert.IsTrue (str.Contains( "#line hidden#line hidden2"), "#1"); } }
/// <summary> /// Ensures that we have a top-level namespace (cached in our topNamespace field) /// </summary> private void InitTopNamespace() { if (vsTopNamespace == null) { vsTopNamespace = new CodeDomCodeNamespace(DTE, String.Empty, this); foreach (CDCodeNamespace ns in _ccu.Namespaces) { if (String.IsNullOrEmpty(ns.Name)) { topNamespace = ns; break; } } if (topNamespace == null) { topNamespace = new CDCodeNamespace(String.Empty); _ccu.Namespaces.Add(topNamespace); } vsTopNamespace.CodeObject = topNamespace; topNamespace.UserData[CodeKey] = vsTopNamespace; } }
static CodeTypeDeclaration CreatePartialClass (SteticCompilationUnit globalUnit, List<SteticCompilationUnit> units, GenerationOptions options, string name) { SteticCompilationUnit unit; if (options.GenerateSingleFile) unit = globalUnit; else { unit = new SteticCompilationUnit (name); units.Add (unit); } string ns = ""; int i = name.LastIndexOf ('.'); if (i != -1) { ns = name.Substring (0, i); name = name.Substring (i+1); } CodeTypeDeclaration type = new CodeTypeDeclaration (name); type.IsPartial = true; type.Attributes = MemberAttributes.Public; type.TypeAttributes = TypeAttributes.Public; CodeNamespace cns = new CodeNamespace (ns); cns.Types.Add (type); unit.Namespaces.Add (cns); return type; }
public override string ImportSchemaType( string name, string ns, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider) { if (ns != "http://www.w3.org/2001/XMLSchema") return null; switch (name) { case "anyURI": return "System.Uri"; case "gDay": return "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapDay"; case "gMonth": return "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapMonth"; case "gMonthDay": return "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapMonthDay"; case "gYear": return "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapYear"; case "gYearMonth": return "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapYearMonth"; case "duration": return "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapDuration"; default: return null; } }
public void CanCreateDataTableAssignment() { CodeNamespace nsdecl = new CodeNamespace("My.Data"); CodeTypeDeclaration cdecl = new CodeTypeDeclaration("ResultSet"); CodeMemberMethod method = new CodeMemberMethod(); method.Name = "GetData"; method.Attributes = MemberAttributes.Public | MemberAttributes.Final; method.ReturnType = new CodeTypeReference("System.Data.DataTable"); method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "name")); method.Statements.Add(new CodeVariableDeclarationStatement( typeof(DataTable), "result", new CodeObjectCreateExpression(typeof(DataTable)))); cdecl.Members.Add(method); method.Statements.Add( new CodeVariableDeclarationStatement( typeof(DataColumnCollection), "columns", new CodePropertyReferenceExpression( new CodeVariableReferenceExpression("result"), "Columns"))); method.Statements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("columns"), "Add", new CodeTypeOfExpression(typeof(string)), new CodeSnippetExpression("name"))); nsdecl.Types.Add(cdecl); CSharpCodeProvider provider = new CSharpCodeProvider(); provider.GenerateCodeFromNamespace(nsdecl, Console.Out, new System.CodeDom.Compiler.CodeGeneratorOptions()); }
protected internal override object InsideCodeNamespace(CodeNamespace ns) { foreach (var atom in Atoms) atom.Visit (ns); return null; }
protected override void GenerateNamespaceStart(System.CodeDom.CodeNamespace e) { //if (e.Name != null && e.Name.Length > 0) //{ // Output.WriteLine("Unit " + e.Name + ";"); //} }
static void GenerateWidgetCode(SteticCompilationUnit globalUnit, CodeNamespace globalNs, GenerationOptions options, List<SteticCompilationUnit> units, Gtk.Widget w, ArrayList warnings) { // Generate the build method CodeTypeDeclaration type = CreatePartialClass (globalUnit, units, options, w.Name); CodeMemberMethod met = new CodeMemberMethod (); met.Name = "Build"; type.Members.Add (met); met.ReturnType = new CodeTypeReference (typeof(void)); met.Attributes = MemberAttributes.Family; if (options.GenerateEmptyBuildMethod) { GenerateWrapperFields (type, Wrapper.Widget.Lookup (w)); return; } met.Statements.Add ( new CodeMethodInvokeExpression ( new CodeTypeReferenceExpression (globalNs.Name + ".Gui"), "Initialize", new CodeThisReferenceExpression () ) ); Stetic.Wrapper.Widget wwidget = Stetic.Wrapper.Widget.Lookup (w); if (wwidget.GeneratePublic) type.TypeAttributes = TypeAttributes.Public; else type.TypeAttributes = TypeAttributes.NotPublic; Stetic.WidgetMap map = Stetic.CodeGenerator.GenerateCreationCode (globalNs, type, w, new CodeThisReferenceExpression (), met.Statements, options, warnings); CodeGenerator.BindSignalHandlers (new CodeThisReferenceExpression (), wwidget, map, met.Statements, options); }
/// <summary>Called when extension shall processs generated CodeDOM</summary> /// <param name="code">Object tree representing generated CodeDOM</param> /// <param name="schema">Input XML schema</param> /// <param name="provider">CodeDOM provider (the language)</param> /// <version version="1.5.3">Added documentation</version> /// <version version="1.5.3">Parameter <c>Provider</c> renamed to <c>provider</c></version> public void Process(System.CodeDom.CodeNamespace code, System.Xml.Schema.XmlSchema schema, CodeDomProvider provider) { foreach (CodeTypeDeclaration type in code.Types) { ParseType(type); } }
/// <summary> /// Generates source code from given namespace. /// </summary> private static string GenerateFromNamespace(CodeDomProvider codeProvider, System.CodeDom.CodeNamespace codeNamespace, bool blankLinesBetweenMembers, bool isCSharp) { var result = new StringBuilder(); using (var writer = new StringWriter(result)) { var options = new CodeGeneratorOptions { BlankLinesBetweenMembers = blankLinesBetweenMembers, ElseOnClosing = true, VerbatimOrder = true, BracingStyle = "C", }; // generate the code: codeProvider.GenerateCodeFromNamespace(codeNamespace, writer, options); // send it to the StringBuilder object: writer.Flush(); } if (isCSharp) { result.Replace(" class ", " static class "); result.Replace(" partial static ", " static partial "); result.Replace(" static System.Guid ", " static readonly System.Guid "); } return(result.ToString()); }
public void PostProcessGeneratedCodeAddsApplicationInstanceProperty() { const string expectedPropertyCode = @" protected Foo.Bar ApplicationInstance { get { return ((Foo.Bar)(Context.ApplicationInstance)); } } "; // Arrange CodeCompileUnit generatedCode = new CodeCompileUnit(); CodeNamespace generatedNamespace = new CodeNamespace(); CodeTypeDeclaration generatedClass = new CodeTypeDeclaration(); CodeMemberMethod executeMethod = new CodeMemberMethod(); WebPageRazorHost host = new WebPageRazorHost("Foo.cshtml") { GlobalAsaxTypeName = "Foo.Bar" }; // Act host.PostProcessGeneratedCode(generatedCode, generatedNamespace, generatedClass, executeMethod); // Assert CodeMemberProperty property = generatedClass.Members[0] as CodeMemberProperty; Assert.IsNotNull(property); CSharpCodeProvider provider = new CSharpCodeProvider(); StringBuilder builder = new StringBuilder(); using(StringWriter writer = new StringWriter(builder)) { provider.GenerateCodeFromMember(property, writer, new CodeDom.Compiler.CodeGeneratorOptions()); } Assert.AreEqual(expectedPropertyCode, builder.ToString()); }
/// <summary>Called when extension shall processs generated CodeDOM</summary> /// <param name="code">Object tree representing generated CodeDOM</param> /// <param name="schema">Input XML schema</param> /// <param name="provider">CodeDOM provider (the language)</param> /// <version version="1.5.3">Added documentation</version> /// <version version="1.5.3">Parameter <c>Provider</c> renamed to <c>provider</c></version> public void Process(System.CodeDom.CodeNamespace code, System.Xml.Schema.XmlSchema schema, CodeDomProvider provider) { foreach (CodeTypeDeclaration type in code.Types) { if (type.IsClass || type.IsStruct) { // Copy the colletion to an array for safety. We will be // changing this collection. CodeTypeMember[] members = new CodeTypeMember[type.Members.Count]; type.Members.CopyTo(members, 0); foreach (CodeTypeMember member in members) { // Process fields only. if (member is CodeMemberField) { CodeMemberProperty prop = new CodeMemberProperty(); prop.Name = member.Name; prop.Attributes = member.Attributes; prop.Type = ((CodeMemberField)member).Type; // Copy attributes from field to the property. prop.CustomAttributes.AddRange(member.CustomAttributes); member.CustomAttributes.Clear(); // Copy comments from field to the property. prop.Comments.AddRange(member.Comments); member.Comments.Clear(); // Modify the field. member.Attributes = MemberAttributes.Private; Char[] letters = member.Name.ToCharArray(); letters[0] = Char.ToLower(letters[0]); member.Name = String.Concat("_", new string(letters)); prop.HasGet = true; prop.HasSet = true; // Add get/set statements pointing to field. Generates: // return this._fieldname; prop.GetStatements.Add( new CodeMethodReturnStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), member.Name))); // Generates: // this._fieldname = value; prop.SetStatements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), member.Name), new CodeArgumentReferenceExpression("value"))); // Finally add the property to the type type.Members.Add(prop); } } } } }
/// <summary> /// Customizes the generated code to better conform to the NHibernate's coding conventions. /// </summary> /// <param name="code">The customizable code DOM.</param> /// <param name="sourceSchema">The source XML Schema.</param> protected override void CustomizeGeneratedCode(CodeNamespace code, XmlSchema sourceSchema) { new ImproveHbmTypeNamesCommand(code).Execute(); new ImproveEnumFieldsCommand(code).Execute(); // TODO: Rename class fields? }
public void Build(DataStructure dataStructure, string rendererFilename = "") { if (string.IsNullOrEmpty(rendererFilename)) { rendererFilename = this.GetFilename(dataStructure); } var rendererType = new CodeTypeDeclaration(dataStructure.RendererName); rendererType.IsClass = true; rendererType.IsPartial = true; rendererType.BaseTypes.Add(typeof(Renderer)); rendererType.Comments.Add(new CodeCommentStatement("<summary>", true)); rendererType.Comments.Add(new CodeCommentStatement(string.Format("Renderer of {0}", dataStructure.TargetName), true)); rendererType.Comments.Add(new CodeCommentStatement("</summary>", true)); BuildCreate(rendererType, dataStructure); BuildConstructor(rendererType, dataStructure); BuildDoInitialize(rendererType, dataStructure); BuildDoRender(rendererType, dataStructure); var parserNamespace = new CodeNamespace("CSharpGL"); parserNamespace.Imports.Add(new CodeNamespaceImport(typeof(System.Object).Namespace)); parserNamespace.Imports.Add(new CodeNamespaceImport(typeof(System.Collections.Generic.List<int>).Namespace)); parserNamespace.Types.Add(rendererType); //生成代码 using (var stream = new StreamWriter(rendererFilename, false)) { CSharpCodeProvider codeProvider = new CSharpCodeProvider(); CodeGeneratorOptions opentions = new CodeGeneratorOptions();//代码生成选项 opentions.BlankLinesBetweenMembers = true; opentions.BracingStyle = "C"; opentions.ElseOnClosing = false; opentions.IndentString = " "; opentions.VerbatimOrder = true; codeProvider.GenerateCodeFromNamespace(parserNamespace, stream, opentions); } }
public CodeDomEntity(JToken structualType, string targetNamespace) { this.targetNamespace = targetNamespace; outputFileName = string.Format("{0}.cs", structualType["shortName"].Value<string>()); this.structualType = structualType; targetUnit = new CodeCompileUnit(); CodeNamespace breezeEntities = new CodeNamespace(targetNamespace); breezeEntities.Imports.Add(new CodeNamespaceImport("System")); breezeEntities.Imports.Add(new CodeNamespaceImport("Breeze.Sharp")); breezeEntities.Imports.Add(new CodeNamespaceImport("System.Collections.Generic")); targetClass = new CodeTypeDeclaration(structualType["shortName"].Value<string>()); if (structualType["baseTypeName"] != null) { //use base class from the base type (it will still be BaseEntity) string baseType = structualType["baseTypeName"].Value<string>(); targetClass.BaseTypes.Add(new CodeTypeReference(baseType.Substring(0, baseType.IndexOf(':')))); } else { //this entity type has no base class so use BaseEntity targetClass.BaseTypes.Add(new CodeTypeReference("BaseEntity")); } targetClass.IsClass = true; targetClass.TypeAttributes = TypeAttributes.Public; breezeEntities.Types.Add(targetClass); targetUnit.Namespaces.Add(breezeEntities); }
static void Main(string[] args) { CodeCompileUnit compileUnit = new CodeCompileUnit(); CodeNamespace myNamespace = new CodeNamespace("MyNamespace"); myNamespace.Imports.Add(new CodeNamespaceImport("System")); CodeTypeDeclaration myClass = new CodeTypeDeclaration("MyClass"); CodeEntryPointMethod start = new CodeEntryPointMethod(); CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Console"), "WriteLine", new CodePrimitiveExpression("Hello World")); compileUnit.Namespaces.Add(myNamespace); myNamespace.Types.Add(myClass); myClass.Members.Add(start); start.Statements.Add(cs1); CSharpCodeProvider provider = new CSharpCodeProvider(); using(StreamWriter sw = new StreamWriter("HelloWorld.cs", false)) { IndentedTextWriter tw = new IndentedTextWriter(sw, " "); provider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions()); tw.Close(); } Console.WriteLine("HelloWorld.cs generated in .../bin/Debug or .../bin/Release project folders."); Console.Write("Press a key to exit"); Console.ReadKey(); }
/// <summary> /// Adiciona using no namespace /// </summary> /// <param name="customNamespace"></param> /// <param name="nameSpaces"></param> public void CreateImports(ref CodeNamespace customNamespace, params string[] nameSpaces) { foreach (var item in nameSpaces) { customNamespace.Imports.Add(new CodeNamespaceImport(item)); } }
public CodeCompileUnit Generate(ClassData classData) { if (classData == null) { throw FxTrace.Exception.ArgumentNull("classData"); } CodeCompileUnit result = new CodeCompileUnit(); // Add global namespace CodeNamespace globalNamespace = new CodeNamespace(); result.Namespaces.Add(globalNamespace); CodeTypeDeclaration classDeclaration = GenerateClass(classData); if (!String.IsNullOrEmpty(classData.Namespace)) { // Add namespace the class is defined in CodeNamespace classNamespace = new CodeNamespace(classData.Namespace); result.Namespaces.Add(classNamespace); classNamespace.Types.Add(classDeclaration); } else { // Add class to global namespace globalNamespace.Types.Add(classDeclaration); } return result; }
public override void ProcessGeneratedCode(CodeCompileUnit codeCompileUnit, CodeNamespace generatedNamespace, CodeTypeDeclaration generatedClass, CodeMemberMethod executeMethod) { if (!String.IsNullOrEmpty(_suffix)) { generatedClass.Name += _suffix; } }
internal XmlSerializerOperationGenerator(XmlSerializerImportOptions options) { operationGenerator = new OperationGenerator(); this.options = options; this.codeNamespace = GetTargetCodeNamespace(options); partInfoTable = new Dictionary<MessagePartDescription, PartInfo>(); }
private static CodeTypeDeclaration LoadFileElement(XmlElement element, CodeNamespace codeNamespace) { string className = element.GetAttribute("class"); CodeTypeDeclaration codeType = new CodeTypeDeclaration(className); codeType.Attributes = MemberAttributes.Assembly; codeType.BaseTypes.Add(new CodeTypeReference("DbEntry")); int order = 0; foreach(XmlNode node in element.ChildNodes) { if(!(node is XmlElement)) continue; XmlElement childElement = (XmlElement)node; CodeMemberProperty codeProperty; if(childElement.Name == "field") LoadFieldElement(childElement, codeType, out codeProperty); else if(childElement.Name == "enum") LoadEnumElement(childElement, codeType, out codeProperty); else continue; codeProperty.CustomAttributes.Add(new CodeAttributeDeclaration( new CodeTypeReference("PropertyOrderAttribute"), new CodeAttributeArgument(new CodePrimitiveExpression(order++)))); } CodeMemberMethod stringMethod = new CodeMemberMethod(); stringMethod.Name = "ToString"; stringMethod.Attributes = MemberAttributes.Public | MemberAttributes.Override; string stringMethodBody = element["string"].InnerText.TrimEnd(';'); stringMethod.Statements.Add(new CodeSnippetExpression(stringMethodBody)); stringMethod.ReturnType = new CodeTypeReference("System.String"); codeType.Members.Add(stringMethod); return codeType; }
/// <summary> /// Generates code from the specified <paramref name="constructor"/>. /// </summary> /// <param name="constructor">Class constructor for which code needs to be generated.</param> /// <param name="type">Type declaration.</param> /// <param name="namespace">Namespace declaration.</param> /// <param name="options">Code generation options.</param> /// <remarks> /// This method is a workaround for <see cref="CodeDomProvider.GenerateCodeFromMember"/> /// not generating constructors properly. /// </remarks> private void GenerateCodeFromConstructor( CodeConstructor constructor, CodeTypeDeclaration type, CodeNamespace @namespace, CodeGeneratorOptions options) { const string StartMarker = "___startMarker___"; const string EndMarker = "___endMarker___"; // Insert marker fields around the target constructor int indexOfMember = type.Members.IndexOf(constructor); type.Members.Insert(indexOfMember + 1, new CodeMemberField(typeof(int), EndMarker)); type.Members.Insert(indexOfMember, new CodeMemberField(typeof(int), StartMarker)); using (StringWriter buffer = new StringWriter(CultureInfo.InvariantCulture)) { // Generate type declaration in verbatim order to preserve placement of marker fields options = options ?? new CodeGeneratorOptions(); options.VerbatimOrder = true; this.LanguageProvider.GenerateCodeFromNamespace(@namespace, buffer, options); // Extract constructor code from the generated type code const string ConstructorCode = "constructor"; Regex regex = new Regex( @"^[^\r\n]*" + StartMarker + @"[^\n]*$" + @"(?<" + ConstructorCode + @">.*)" + @"^[^\r\n]*" + EndMarker + @"[^\n]*$", RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.ExplicitCapture); string code = regex.Match(buffer.ToString()).Groups[ConstructorCode].Value; // Write constructor code to the output buffer this.ClassCode.Write(code); } }
/// <summary> /// Adds a namespace to the top level namespace. /// </summary> /// <param name="Name">Required. The name of the new namespace.</param> /// <param name="Position">Optional. Default = 0. The code element after which to add the new element. If the value is a CodeElement, then the new element is added immediately after it.</param> /// <returns></returns> public VSCodeNamespace AddNamespace(string Name, object Position) { Initialize(); InitTopNamespace(); CDCodeNamespace cn = new CDCodeNamespace(Name); EnsureNamespaceLinked(cn); VSCodeNamespace after = Position as VSCodeNamespace; if (after != null) { for (int i = 0; i < _ccu.Namespaces.Count; i++) { if (_ccu.Namespaces[i].UserData[CodeKey] == after) { _ccu.Namespaces.Insert(i + 1, cn); } } } else { int index = (int)Position - 1; _ccu.Namespaces.Insert(index, cn); } CommitChanges(); return((VSCodeNamespace)cn.UserData[CodeKey]); }
public static string GenTableAdapters(System.IO.Stream xmlStream, TypedDataSetGenerator.GenerateOption genOption, string customToolNamespace) { try { EnsureCustomDbProviders(); var designSource = Activator.CreateInstance(assm.GetType("System.Data.Design.DesignDataSource")); designSource.Invoke("ReadXmlSchema", xmlStream, string.Empty ); var dataSourceGeneratorType = assm.GetType("System.Data.Design.TypedDataSourceCodeGenerator"); //get the specific constructor var constructor = dataSourceGeneratorType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, CallingConventions.Any, new Type[0], new ParameterModifier[0]); var dataSourceGenerator = constructor.Invoke(null); var codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); dataSourceGenerator.SetInternalPropertyValue("CodeProvider", codeProvider); var codeCompileUnit = new CodeCompileUnit(); var codeNamespace = new CodeNamespace(customToolNamespace); codeCompileUnit.Namespaces.Add(codeNamespace); dataSourceGenerator.InvokeInternal("GenerateDataSource", designSource, codeCompileUnit, codeNamespace, customToolNamespace, genOption ); var writer = new StringWriter(); var adapterNameSpace = codeCompileUnit.Namespaces[1]; codeProvider.GenerateCodeFromNamespace(adapterNameSpace, writer, new CodeGeneratorOptions()); //codeProvider.GenerateCodeFromCompileUnit(codeCompileUnit, writer, options); var res = writer.ToString(); return (string)res; } catch (Exception e) { return e.ToString(); } }
public override void EnterNamespace_(XSharpParser.Namespace_Context context) { String newNamespaceName = context.Name.GetText(); // We already have something in Stack // so we are nesting Namespaces, get the previous name prefix if (this.NamespaceStack.Count > 0) { newNamespaceName = this.CurrentNamespace.Name + "." + newNamespaceName; } CodeNamespace newNamespace = new CodeNamespace(newNamespaceName); // this.NamespaceStack.Push(this.CurrentNamespace); // if (String.IsNullOrEmpty(this.CurrentNamespace.Name)) { // We could just have the empty fake Namespace here, but // if we have some Usings inside we must copy them if ((this.CurrentNamespace.Types.Count == 0) && (this.CurrentNamespace.Imports.Count > 0)) { // No Types means no Classes // Ok, copy foreach (CodeNamespaceImport import in this.CurrentNamespace.Imports) newNamespace.Imports.Add(import); } } // this.CurrentNamespace = newNamespace; }
public SoapCodeExporter (CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit) { this.codeCompileUnit = codeCompileUnit; this.codeNamespace = codeNamespace; codeGenerator = new SoapMapCodeGenerator (codeNamespace, codeCompileUnit); }
/// <summary> 根据参数执行WebService </summary> public static object InvokeWebService(string url, string classname, string methodname, object[] args) { try { string _namespace = "WebService"; if (string.IsNullOrEmpty(classname)) { classname = GetClassName(url); } //获取服务描述语言(WSDL) Net.WebClient wc = new Net.WebClient(); Stream stream = wc.OpenRead(url + "?WSDL"); //【1】 Web.Services.Description.ServiceDescription sd = Web.Services.Description.ServiceDescription.Read(stream); //【2】 Web.Services.Description.ServiceDescriptionImporter sdi = new Web.Services.Description.ServiceDescriptionImporter(); //【3】 sdi.AddServiceDescription(sd, "", ""); CodeDom.CodeNamespace cn = new CodeDom.CodeNamespace(_namespace); //【4】 //生成客户端代理类代码 CodeDom.CodeCompileUnit ccu = new CodeDom.CodeCompileUnit(); //【5】 ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); //CSharpCodeProvider csc = new CSharpCodeProvider();//【6】 CodeDom.Compiler.CodeDomProvider csc = CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp"); //ICodeCompiler icc = csc.CreateCompiler();//【7】 //设定编译器的参数 CodeDom.Compiler.CompilerParameters cplist = new CodeDom.Compiler.CompilerParameters();//【8】 cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 CodeDom.Compiler.CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);//【9】 if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new StringBuilder(); foreach (CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } //生成代理实例,并调用方法 System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(_namespace + "." + classname, true, true); object bj = Activator.CreateInstance(t); //【10】 System.Reflection.MethodInfo mi = t.GetMethod(methodname); //【11】 return(mi.Invoke(bj, args)); } catch (System.Exception ex) { Common.LogHelper.Instance.WriteError(ex.Message + "|" + ex.StackTrace); //MessageManager.ShowErrorMsg(ex.Message.ToString(), "test"); return(null); } }
public void Generate() { _model = (Model)_propertyBag["Generic.Model"]; if (_model.GenerateMonoRailProject && !String.IsNullOrEmpty(_model.MonoRailProjectName) && !String.IsNullOrEmpty(_model.MonoRailProjectPath)) { _dte = (DTE)_propertyBag["Generic.DTE"]; if (_dte == null) { throw new NullReferenceException("Could not get a reference to active DTE object."); } else { _language = (CodeLanguage)_propertyBag["Generic.Language"]; Project project = null; project = GetProject(_dte, _model.MonoRailProjectName); if (project == null) { project = CreateProject(_dte, _model.MonoRailProjectPath + Path.DirectorySeparatorChar + _model.MonoRailProjectName, _model.MonoRailProjectName); } CodeCompileUnit compileUnit = (CodeCompileUnit)_propertyBag["CodeGeneration.CodeCompileUnit"]; // We will handle the first namespace by default. if (compileUnit.Namespaces.Count > 0) { CodeNamespace ns = compileUnit.Namespaces[0]; List <CodeTypeDeclaration> classes = null; if (ns.Types.Count > 0) { classes = new List <CodeTypeDeclaration>(); foreach (CodeTypeDeclaration type in ns.Types) { if (type.IsClass) { foreach (CodeAttributeDeclaration attribute in type.CustomAttributes) { if (attribute.Name == "ActiveRecord") { classes.Add(type); break; } } } } if (classes.Count > 0) { // TODO: ... } } } } } }
/// <summary>Method to create a version comment</summary> /// <param name="codeNamespace">CodeDOM unit to place comments inside</param> protected virtual void GenerateVersionComment(System.CodeDom.CodeNamespace codeNamespace) { codeNamespace.Comments.Add(new CodeCommentStatement(string.Empty)); codeNamespace.Comments.Add(new CodeCommentStatement(String.Format(Tools.ResourcesT.ResourcesVsCs.ThisSourceCodeWasAutoGeneratedBy0Version1, System.Reflection.Assembly.GetExecutingAssembly().GetName().Name, System.Environment.Version.ToString()))); codeNamespace.Comments.Add(new CodeCommentStatement(string.Empty)); }
/// <summary> /// method to create a version comment /// </summary> /// <param name="codeNamespace"></param> protected virtual void GenerateVersionComment(System.CodeDom.CodeNamespace codeNamespace) { codeNamespace.Comments.Add(new CodeCommentStatement(string.Empty)); codeNamespace.Comments.Add(new CodeCommentStatement(String.Format("This source code was auto-generated by {0}, Version {1}.", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name, System.Environment.Version.ToString()))); codeNamespace.Comments.Add(new CodeCommentStatement(string.Empty)); }
private static CodeClass AddClass(string className, EnvDTE.Project project) { var codeDomProvider = CodeDomProvider.CreateProvider("CSharp"); if (!codeDomProvider.IsValidIdentifier(className)) { throw new ArgumentException(string.Format("Invalid Class Name: {0}", className)); } var targetClass = codeDomProvider.CreateValidIdentifier(className); string targetNamespace; try { targetNamespace = project.Properties.Item("DefaultNamespace").Value.ToString(); } catch { targetNamespace = project.FullName; } var codeNamespace = new CodeNamespace(targetNamespace); codeNamespace.Imports.Add(new CodeNamespaceImport("System")); codeNamespace.Imports.Add(new CodeNamespaceImport("Gauge.CSharp.Lib")); codeNamespace.Imports.Add(new CodeNamespaceImport("Gauge.CSharp.Lib.Attribute")); var codeTypeDeclaration = new CodeTypeDeclaration(targetClass) { IsClass = true, TypeAttributes = TypeAttributes.Public }; codeNamespace.Types.Add(codeTypeDeclaration); var codeCompileUnit = new CodeCompileUnit(); codeCompileUnit.Namespaces.Add(codeNamespace); var targetFileName = Path.Combine(Path.GetDirectoryName(project.FullName), $"{targetClass}.cs"); using (var streamWriter = new StreamWriter(targetFileName)) { var options = new CodeGeneratorOptions { BracingStyle = "C" }; codeDomProvider.GenerateCodeFromCompileUnit(codeCompileUnit, streamWriter, options); } var file = project.ProjectItems.AddFromFile(targetFileName); var classes = GetCodeElementsFor(file.FileCodeModel.CodeElements, vsCMElement.vsCMElementClass).ToList(); return(classes.First(element => element.Name == targetClass) as CodeClass); }
private void EnsureNamespaceLinked(CDCodeNamespace member) { if (member.UserData[CodeKey] == null) { CodeDomCodeNamespace cdcn = new CodeDomCodeNamespace(DTE, member.Name, this); cdcn.CodeObject = member; member.UserData[CodeKey] = cdcn; } }
public static object WebserviceInvoke(string p_strUrl, string p_strNameSpace, string p_strClassName, string p_strMethodName, object[] p_objArgs) { object oReturnValue = null; try { if (p_strNameSpace == "") { p_strNameSpace = "EnterpriseServerBase.WebService.DynamicWebCalling"; } if (p_strClassName == "") { p_strClassName = WebServiceHelper.GetWsClassName(p_strUrl); } System.Net.WebClient wc = new System.Net.WebClient(); System.IO.Stream stream = wc.OpenRead(p_strUrl + "?wsdl"); System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream); System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace(p_strNameSpace); System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); System.CodeDom.Compiler.CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(p_strNameSpace + "." + p_strClassName, true, true); object obj = Activator.CreateInstance(t); System.Reflection.MethodInfo mi = t.GetMethod(p_strMethodName); oReturnValue = mi.Invoke(obj, p_objArgs); } catch (Exception ex) { throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); } return(oReturnValue); }
/// <summary> /// method to create a version comment /// </summary> /// <param name="codeNamespace"></param> protected virtual void GenerateVersionComment(System.CodeDom.CodeNamespace codeNamespace) { codeNamespace.Comments.Add(new CodeCommentStatement(string.Empty)); codeNamespace.Comments.Add( new CodeCommentStatement( string.Format(Resources.VersionComment, Assembly.GetExecutingAssembly().GetName().Name, System.Environment.Version.ToString()))); codeNamespace.Comments.Add(new CodeCommentStatement(string.Empty)); }
private static string GenerateCodeForType(Type type, string targetNamespace, string previousOutput) { string output = GetXmlSerializerOutput(type); System.CodeDom.CodeNamespace ns = InitializeCodeDom(targetNamespace); output = CleanupXmlSerializerCode(targetNamespace, output); // Find the methods that are the entry points for reading and writing the object. Match readMatch = PublicRead.Match(output); Match writeMatch = PublicWrite.Match(output); string rootObject = readMatch.Groups[MethodObjectName].Value; output = MakeSerializerPartial(output, rootObject); output = RenameClasses(output, rootObject); output = NestTypesOnSerialier(output, rootObject); output = AppendReaderWriterMembersToObjectSerializer(type, output, rootObject); CodeTypeDeclaration readerDeclaration = CreateAndAddEventRisingReader(targetNamespace, ns, rootObject, output, previousOutput); output = PrivateReadMethodsToProtectedVirtual(output); CodeTypeDeclaration writerDeclaration = CreateAndAddTypedWriter(targetNamespace, ns, rootObject); // Renders TemplateReadMethod (see that constant declaration) output = AddTypedRead(readerDeclaration, type, output, readMatch); // Renders TemplateWriteMethod (see that constant declaration) output = AddTypedWrite(writerDeclaration, type, output, writeMatch); output = MergeOutputWithCodeDom(output, ns); output = MakeClassesInternal(output); output = NormalizeLineEndings(output); output = NestTypesOnSerialier(output, rootObject); output = FixInstantiationOfNestedTypes(output, rootObject); output = @" #pragma warning disable 0642, 0219 " + output + @" #pragma warning restore 0642, 0219"; output = CustomTool.GetToolGeneratedCodeWarning(typeof(XGenTool)) + output; #if DEBUG return(@"#region Original XmlSerializer code /* ------------------------------------------------------------------------------------- " + GetXmlSerializerOutput(type) + @" -------------------------------------------------------------------------------------*/ " + @"#endregion " + output); #else return(output); #endif }
public string GenerateBaseFile(GeneralProperty GeneralProperty, string Namespace, string Language) { CodeCompileUnit ccu = new CodeCompileUnit(); System.CodeDom.CodeNamespace cns = _getNamespace(GeneralProperty, Namespace); CodeTypeDeclaration model = _getType(GeneralProperty); cns.Types.Add(model); ccu.Namespaces.Add(cns); return(_getString(ccu, Language)); }
private static System.CodeDom.CodeNamespace InitializeCodeDom(string targetNamespace) { System.CodeDom.CodeNamespace ns = new System.CodeDom.CodeNamespace(targetNamespace); ns.Imports.Add(new CodeNamespaceImport("System.Xml.Serialization")); ns.Imports.Add(new CodeNamespaceImport("System")); // CodeTypeDeclaration serializer = new CodeTypeDeclaration(type.Name + "Serializer"); // serializer.BaseTypes.Add(typeof(XmlSerializer)); // serializer.Comments.Add(new CodeCommentStatement( // "<summary>Custom serializer for " + type.Name + " type.</summary", true)); // ns.Types.Add(serializer); return(ns); }
private static string MergeOutputWithCodeDom(string output, System.CodeDom.CodeNamespace ns) { CodeGeneratorOptions opt = new CodeGeneratorOptions(); opt.BracingStyle = "C"; StringWriter finalcode = new StringWriter(); new Microsoft.CSharp.CSharpCodeProvider().GenerateCodeFromNamespace(ns, finalcode, opt); finalcode.WriteLine(output); return(finalcode.ToString()); }
///------------------------------------------------------------------------------------------------------------- /// <summary> /// /// </summary> ///------------------------------------------------------------------------------------------------------------- private void GenerateClass() { // Break full name into namespace and name if (!string.IsNullOrEmpty(_className_Full)) { int lastdot = _className_Full.LastIndexOf('.'); if (lastdot >= 0) { _className_Name = _className_Full.Substring(lastdot + 1); _className_Namespace = _className_Full.Substring(0, lastdot); } else { _className_Name = _className_Full; _className_Namespace = null; } } // Create namespace and add to compile unit System.CodeDom.CodeNamespace codeNS = null; string ns = GetClassNamespace(); if (!string.IsNullOrEmpty(ns)) { codeNS = new System.CodeDom.CodeNamespace(ns); } else { codeNS = new System.CodeDom.CodeNamespace(); } if (_ccu.Namespaces != null && _ccu.Namespaces.Count > 0 && String.CompareOrdinal(_ccu.Namespaces[0].Name, ns) == 0) { codeNS = _ccu.Namespaces[0]; } else { _ccu.Namespaces.Add(codeNS); } // Create class definition and add to namespace _ctd = new CodeTypeDeclaration(_className_Name); _ctd.IsPartial = !IsPartialClassDisabled; if (codeNS.Types != null && codeNS.Types.Count > 0 && String.CompareOrdinal(codeNS.Types[0].Name, _className_Name) == 0) { _ctd = codeNS.Types[0]; } else { codeNS.Types.Add(_ctd); } }
private System.CodeDom.CodeNamespace _getNamespace(GeneralProperty gp, string Namespace) { System.CodeDom.CodeNamespace cns = new System.CodeDom.CodeNamespace(Namespace); cns.Imports.Add(new CodeNamespaceImport("System")); cns.Imports.Add(new CodeNamespaceImport("Burst")); cns.Imports.Add(new CodeNamespaceImport("Burst.Data")); cns.Imports.Add(new CodeNamespaceImport("Burst.Data.Entity")); if (gp != null && gp.IsWebUserModel) { cns.Imports.Add(new CodeNamespaceImport("Burst.Web")); } return(cns); }
public static object InvokeWebSer(string url, string @namespace, string classname, string methodname, object[] args) { System.Net.WebClient wc = new System.Net.WebClient(); string URL = string.Empty; if ((url.Substring(url.Length - 5, 5) != null) && ((url.Substring(url.Length - 5, 5).ToLower() != "?wsdl"))) { URL = url + "?WSDL"; } else { URL = url; } System.IO.Stream stream = wc.OpenRead(URL); System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream); System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace(@namespace); System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); System.CodeDom.Compiler.CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(@namespace + "." + classname, true, true); object obj = Activator.CreateInstance(t); System.Reflection.MethodInfo mi = t.GetMethod(methodname); return(mi.Invoke(obj, args)); }
public void Generate() { if (Context.Model.GenerateMonoRailProject && !String.IsNullOrEmpty(Context.Model.MonoRailProjectName) && !String.IsNullOrEmpty(Context.Model.MonoRailProjectPath)) { if (Context.DTE == null) { throw new NullReferenceException("Could not get a reference to active DTE object."); } Project project = null; project = GetProject(Context.DTE, Context.Model.MonoRailProjectName); if (project == null) { project = CreateProject(Context.DTE, Context.Model.MonoRailProjectPath + Path.DirectorySeparatorChar + Context.Model.MonoRailProjectName, Context.Model.MonoRailProjectName); } // We will handle the first namespace by default. if (Context.CompileUnit.Namespaces.Count > 0) { CodeNamespace ns = Context.CompileUnit.Namespaces[0]; List <CodeTypeDeclaration> classes = null; if (ns.Types.Count > 0) { classes = new List <CodeTypeDeclaration>(); foreach (CodeTypeDeclaration type in ns.Types) { if (type.IsClass) { foreach (CodeAttributeDeclaration attribute in type.CustomAttributes) { if (attribute.Name == "ActiveRecord") { classes.Add(type); break; } } } } if (classes.Count > 0) { // TODO: ... } } } } }
public void ConstructWithParametersBuildSystemCodeNamespaceOutputDirectoryCodeGeneratorTest() { var codeNamespace = new System.CodeDom.CodeNamespace(); var outputDirectory = "Value of outputDirectory"; var testObject = new NStubCore(new FakeBuildSystem(), codeNamespace, outputDirectory, _mockCodeGenerator); Assert.Throws <ArgumentNullException>(() => new NStubCore(null, codeNamespace, outputDirectory, _mockCodeGenerator)); Assert.Throws <ArgumentNullException>(() => new NStubCore(new FakeBuildSystem(), null, outputDirectory, _mockCodeGenerator)); Assert.Throws <ArgumentNullException>(() => new NStubCore(new FakeBuildSystem(), codeNamespace, null, _mockCodeGenerator)); Assert.Throws <ArgumentException>(() => new NStubCore(new FakeBuildSystem(), codeNamespace, string.Empty, _mockCodeGenerator)); Assert.Throws <ArgumentNullException>(() => new NStubCore(new FakeBuildSystem(), codeNamespace, outputDirectory, null)); Assert.Throws <System.IO.DirectoryNotFoundException>(() => new NStubCore(new FakeBuildSystem() { FakeDirectoryExists = false }, codeNamespace, outputDirectory, _mockCodeGenerator)); }
public static System.CodeDom.CodeCompileUnit BuildGraph(System.Xml.XmlDocument xmlMetaData, string tableName) { System.Xml.XmlNodeList nodeList; System.CodeDom.CodeCompileUnit compileUnit = new System.CodeDom.CodeCompileUnit(); System.CodeDom.CodeNamespace nSpace; System.CodeDom.CodeTypeDeclaration clsTable; nodeList = xmlMetaData.SelectNodes("/DataSet/Table[@Name='" + tableName + "']/Column"); nSpace = new System.CodeDom.CodeNamespace("ClassViaCodeDOM"); compileUnit.Namespaces.Add(nSpace); nSpace.Imports.Add(new System.CodeDom.CodeNamespaceImport("System")); clsTable = new System.CodeDom.CodeTypeDeclaration(tableName); nSpace.Types.Add(clsTable); System.CodeDom.CodeMemberField field; foreach (System.Xml.XmlNode node in nodeList) { field = new System.CodeDom.CodeMemberField(); field.Name = "m_" + node.Attributes["Name"].Value; field.Attributes = System.CodeDom.MemberAttributes.Private; field.Type = new System.CodeDom.CodeTypeReference(node.Attributes["Type"].Value); clsTable.Members.Add(field); } System.CodeDom.CodeMemberProperty prop; string name; foreach (System.Xml.XmlNode node in nodeList) { prop = new System.CodeDom.CodeMemberProperty(); name = node.Attributes["Name"].Value; prop.Name = name; prop.Attributes = System.CodeDom.MemberAttributes.Public; prop.Type = new System.CodeDom.CodeTypeReference(node.Attributes["Type"].Value); prop.GetStatements.Add(new System.CodeDom.CodeMethodReturnStatement(new System.CodeDom.CodeFieldReferenceExpression(new System.CodeDom.CodeThisReferenceExpression(), "m_" + name))); prop.SetStatements.Add(new System.CodeDom.CodeAssignStatement(new System.CodeDom.CodeFieldReferenceExpression(new System.CodeDom.CodeThisReferenceExpression(), "m_" + name), new System.CodeDom.CodePropertySetValueReferenceExpression())); clsTable.Members.Add(prop); } return(compileUnit); }
/// <include file='doc\VsCodeDomParser.uex' path='docs/doc[@for="VsCodeDomParser.OnNamespacePopulateTypes"]/*' /> /// <devdoc> /// Populate the types from a namespace. /// </devdoc> private void OnNamespacePopulateTypes(object sender, EventArgs e) { CodeNamespace ns = (CodeNamespace)sender; EnvDTE.CodeNamespace vsNamespace = (EnvDTE.CodeNamespace)GetVsElementFromCodeObject(ns); EventHandler populateTypes = new EventHandler(this.OnNamespacePopulateTypes); foreach (CodeElement codeElement in vsNamespace.Members) { // get all the classes out // if (codeElement.Kind == vsCMElement.vsCMElementClass) { CodeTypeDeclaration codeTypeDecl = CodeTypeDeclarationFromCodeClass((EnvDTE.CodeClass)codeElement); ns.Types.Add(codeTypeDecl); } else if (codeElement.Kind == vsCMElement.vsCMElementNamespace) { // set it up and sink it's handler. CodeNamespace nestedNamespace = new CodeNamespace(((EnvDTE.CodeNamespace)codeElement).FullName); SetVsElementToCodeObject(codeElement, nestedNamespace); nestedNamespace.PopulateTypes += populateTypes; CodeCompileUnit codeUnit = (CodeCompileUnit)ns.UserData[typeof(CodeCompileUnit)]; if (codeUnit != null) { int nsIndex = codeUnit.Namespaces.IndexOf(ns); if (nsIndex != -1) { codeUnit.Namespaces[nsIndex] = nestedNamespace; nestedNamespace.UserData[typeof(CodeCompileUnit)] = codeUnit; } } // force generation // object coll = nestedNamespace.Types; } } }
/// <summary> /// Generates source code from given namespace. /// </summary> private static string GenerateFromNamespace(CodeDomProvider codeProvider, System.CodeDom.CodeNamespace codeNamespace, bool blankLinesBetweenMembers) { var result = new StringBuilder(); var writer = new StringWriter(result); var options = new CodeGeneratorOptions(); options.BlankLinesBetweenMembers = blankLinesBetweenMembers; options.ElseOnClosing = true; options.VerbatimOrder = true; options.BracingStyle = "C"; // generate the code: codeProvider.GenerateCodeFromNamespace(codeNamespace, writer, options); // send it to the StringBuilder object: writer.Flush(); return(result.ToString()); }
private void MergeNamespaces(CDCodeNamespace newNs, CDCodeNamespace oldNs) { CopyLineInfo(newNs, oldNs); int curIndex = 0; foreach (CodeTypeDeclaration ctd in newNs.Types) { bool found = false; foreach (CodeTypeDeclaration oldCtd in oldNs.Types) { if (oldCtd.Name == ctd.Name) { oldCtd.UserData[merged] = merged; found = true; MergeTypes(ctd, oldCtd); break; } } if (!found) { oldNs.Types.Insert(curIndex, ctd); } curIndex++; } foreach (CodeTypeDeclaration ctd in oldNs.Types) { if (ctd.UserData[merged] == null) { oldNs.Types.Remove(ctd); } ctd.UserData.Remove(merged); } }
public static System.CodeDom.CodeCompileUnit BuildGraph() { System.CodeDom.CodeCompileUnit CompileUnit = new System.CodeDom.CodeCompileUnit(); System.CodeDom.CodeNamespace nSpace = new System.CodeDom.CodeNamespace("HelloWorldViaCodeDOM"); CompileUnit.Namespaces.Add(nSpace); nSpace.Imports.Add(new System.CodeDom.CodeNamespaceImport("System")); System.CodeDom.CodeTypeDeclaration clsStartup = new System.CodeDom.CodeTypeDeclaration("Startup"); nSpace.Types.Add(clsStartup); System.CodeDom.CodeEntryPointMethod main = new System.CodeDom.CodeEntryPointMethod(); System.CodeDom.CodePrimitiveExpression exp = new System.CodeDom.CodePrimitiveExpression("Hello World!"); System.CodeDom.CodeTypeReferenceExpression refExp = new System.CodeDom.CodeTypeReferenceExpression("System.Console"); System.CodeDom.CodeMethodInvokeExpression invoke = new System.CodeDom.CodeMethodInvokeExpression(refExp, "WriteLine", exp); main.Statements.Add(new System.CodeDom.CodeExpressionStatement(invoke)); clsStartup.Members.Add(main); return(CompileUnit); }
internal CodeExporter(System.CodeDom.CodeNamespace codeNamespace, System.CodeDom.CodeCompileUnit codeCompileUnit, CodeDomProvider codeProvider, CodeGenerationOptions options, Hashtable exportedMappings) { if (codeNamespace != null) { CodeGenerator.ValidateIdentifiers(codeNamespace); } this.codeNamespace = codeNamespace; if (codeCompileUnit != null) { if (!codeCompileUnit.ReferencedAssemblies.Contains("System.dll")) { codeCompileUnit.ReferencedAssemblies.Add("System.dll"); } if (!codeCompileUnit.ReferencedAssemblies.Contains("System.Xml.dll")) { codeCompileUnit.ReferencedAssemblies.Add("System.Xml.dll"); } } this.codeCompileUnit = codeCompileUnit; this.options = options; this.exportedMappings = exportedMappings; this.codeProvider = codeProvider; }