示例#1
1
    object CreateWebServiceFromWsdl(byte[] wsdl) {
        // generate CodeDom from WSDL
        ServiceDescription sd = ServiceDescription.Read(new MemoryStream(wsdl));
        ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
        importer.ServiceDescriptions.Add(sd);
        CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
        CodeNamespace codeNamespace = new CodeNamespace("");
        codeCompileUnit.Namespaces.Add(codeNamespace);
        importer.CodeGenerationOptions = CodeGenerationOptions.GenerateNewAsync | CodeGenerationOptions.GenerateOldAsync;
        importer.Import(codeNamespace, codeCompileUnit);

        // update web service proxy CodeDom tree to add dynamic support
        string wsProxyTypeName = FindProxyTypeAndAugmentCodeDom(codeNamespace);
        // compile CodeDom tree into an Assembly
        CodeDomProvider provider = CodeDomProvider.CreateProvider("CS");
        CompilerParameters compilerParams = new CompilerParameters();
        compilerParams.GenerateInMemory = true;
        compilerParams.IncludeDebugInformation = false;
        compilerParams.ReferencedAssemblies.Add(typeof(Ops).Assembly.Location); //DLR
        CompilerResults results = provider.CompileAssemblyFromDom(compilerParams, codeCompileUnit);
        Assembly generatedAssembly = results.CompiledAssembly;

        // find the type derived from SoapHttpClientProtocol
        Type wsProxyType = generatedAssembly.GetType(wsProxyTypeName);

        if (wsProxyType == null) {
            throw new InvalidOperationException("Web service proxy type not generated.");
        }

        // create an instance of the web proxy type
        return Activator.CreateInstance(wsProxyType);
    }
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {

        if (!(provider is JScriptCodeProvider)) {
            // GENERATES (C#):
            //
            //  namespace Namespace1 {
            //      
            //      public class TEST {
            //          
            //          public static void Main() {
            //              // the following is repeated Char.MaxValue times
            //              System.Console.WriteLine(/* character value goes here */);
            //          }
            //      }
            //  }
            CodeNamespace ns = new CodeNamespace ("Namespace1");
            ns.Imports.Add (new CodeNamespaceImport ("System"));
            cu.Namespaces.Add (ns);

            CodeTypeDeclaration cd = new CodeTypeDeclaration ("TEST");
            cd.IsClass = true;
            ns.Types.Add (cd);
            CodeEntryPointMethod methodMain = new CodeEntryPointMethod ();

            for (int i = 0; i < Char.MaxValue; i+=50)
                methodMain.Statements.Add (CDHelper.ConsoleWriteLineStatement (new CodePrimitiveExpression (System.Convert.ToChar (i))));

            cd.Members.Add (methodMain);
        }
    }
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {

        // GENERATES (C#):
        //
        //  namespace NSPC {
        //      
        //      public class ClassWithMethod {
        //          
        //          public int MethodName() {
        //              This is a CODE SNIPPET #*$*@;
        //              return 3;
        //          }
        //      }
        //  }
        AddScenario ("FindSnippet", "Find code snippet in the code.");
        CodeNamespace nspace = new CodeNamespace ("NSPC");
        cu.Namespaces.Add (nspace);

        CodeTypeDeclaration class1 = new CodeTypeDeclaration ("ClassWithMethod");
        class1.IsClass = true;
        nspace.Types.Add (class1);

        CodeMemberMethod cmm = new CodeMemberMethod ();
        cmm.Name = "MethodName";
        cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
        cmm.ReturnType = new CodeTypeReference (typeof (int));
        cmm.Statements.Add (new CodeExpressionStatement (new CodeSnippetExpression ("This is a CODE SNIPPET #*$*@")));
        cmm.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (3)));
        class1.Members.Add (cmm);
    }
	// Compile a CodeDom compile unit.
	protected virtual CompilerResults FromDom
				(CompilerParameters options, CodeCompileUnit e)
			{
				CodeCompileUnit[] list = new CodeCompileUnit [1];
				list[0] = e;
				return FromDomBatch(options, list);
			}
    public override void BuildTree(CodeDomProvider provider, CodeCompileUnit cu) {
        //cu.UserData["AllowLateBound"] = true;

        // GENERATES (C#):
        //  namespace Namespace1 {
        //      using System;
        //      
        //      
        //      public class Class1 {
        //          
        //          public virtual string Foo1(string format, [System.Runtime.InteropServices.OptionalAttribute()] params object[] array) {
        //              string str;
        //              str = format.Replace("{0}", array[0].ToString());
        //              str = str.Replace("{1}", array[1].ToString());
        //              str = str.Replace("{2}", array[2].ToString());
        //              return str;
        //          }
        //      }
        //  }

        CodeNamespace ns = new CodeNamespace("Namespace1");
        ns.Imports.Add(new CodeNamespaceImport("System"));
        cu.Namespaces.Add(ns);

        // Full Verification Objects
        CodeTypeDeclaration class1 = new CodeTypeDeclaration();
        class1.Name = "Class1";

        ns.Types.Add(class1);

        AddScenario ("CheckFoo1");
        CodeMemberMethod fooMethod1 = new CodeMemberMethod();
        fooMethod1.Name = "Foo1";
        fooMethod1.Attributes = MemberAttributes.Public ; 
        fooMethod1.ReturnType = new CodeTypeReference(typeof(string));

        CodeParameterDeclarationExpression parameter1 = new CodeParameterDeclarationExpression();
        parameter1.Name = "format";
        parameter1.Type = new CodeTypeReference(typeof(string));
        fooMethod1.Parameters.Add(parameter1);

        CodeParameterDeclarationExpression parameter2 = new CodeParameterDeclarationExpression();
        parameter2.Name = "array";
        parameter2.Type = new CodeTypeReference(typeof(object[]));

        if (Supports (provider, GeneratorSupport.ParameterAttributes)) {
            parameter2.CustomAttributes.Add( new CodeAttributeDeclaration("System.ParamArrayAttribute"));
            parameter2.CustomAttributes.Add( new CodeAttributeDeclaration("System.Runtime.InteropServices.OptionalAttribute"));
        }
        fooMethod1.Parameters.Add(parameter2);
        class1.Members.Add(fooMethod1);
        
        fooMethod1.Statements.Add( new CodeVariableDeclarationStatement(typeof(string), "str")); 
            
        fooMethod1.Statements.Add(CreateStatement(new CodeArgumentReferenceExpression ("format"), 0));
        fooMethod1.Statements.Add(CreateStatement(new CodeVariableReferenceExpression ("str"), 1));
        fooMethod1.Statements.Add(CreateStatement(new CodeVariableReferenceExpression ("str"), 2));
       
        fooMethod1.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("str")));
    }
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {
#if WHIDBEY
        if (!(provider is JScriptCodeProvider)) {
            cu.ReferencedAssemblies.Add("System.dll");
            cu.UserData["AllowLateBound"] = true;

            CodeNamespace ns = new CodeNamespace("Namespace1");
            ns.Imports.Add(new CodeNamespaceImport("System"));
            cu.Namespaces.Add(ns);

            AddScenario ("FindPartialClass", "Attempt to find 'PartialClass'");
            BuildClassesIntoNamespace (provider, ns, "PartialClass", ClassTypes.Class, TypeAttributes.Public);
            AddScenario ("FindSealedPartialClass", "Attempt to find 'SealedPartialClass'");
            BuildClassesIntoNamespace (provider, ns, "SealedPartialClass", ClassTypes.Class, TypeAttributes.Sealed);
            BuildClassesIntoNamespace (provider, ns, "AbstractPartialClass", ClassTypes.Class, TypeAttributes.Abstract);
            BuildClassesIntoNamespace (provider, ns, "PrivatePartialClass", ClassTypes.Class, TypeAttributes.NotPublic);

            if (Supports (provider, GeneratorSupport.DeclareValueTypes)) {
                AddScenario ("FindSealedPartialStruct", "Attempt to find 'SealedPartialStruct'");
                BuildClassesIntoNamespace (provider, ns, "SealedPartialStruct", ClassTypes.Struct, TypeAttributes.Sealed);
                BuildClassesIntoNamespace (provider, ns, "AbstractPartialStruct", ClassTypes.Struct, TypeAttributes.Abstract);
            }
        }
#endif
    }
示例#7
0
		private static void AddAllAssemblyAsReference(CodeCompileUnit cu)
		{
			foreach (var v in AppDomain.CurrentDomain.GetAssemblies())
			{
				cu.ReferencedAssemblies.Add(v.Location);
			}
		}
示例#8
0
		protected virtual CompilerResults FromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
		{
			string[] fileNames = new string[ea.Length];
			int i = 0;
			if (options == null)
				options = new CompilerParameters ();
			
			StringCollection assemblies = options.ReferencedAssemblies;

			foreach (CodeCompileUnit e in ea) {
				fileNames[i] = Path.ChangeExtension (Path.GetTempFileName(), FileExtension);
				FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
				StreamWriter s = new StreamWriter (f);
				if (e.ReferencedAssemblies != null) {
					foreach (string str in e.ReferencedAssemblies) {
						if (!assemblies.Contains (str))
							assemblies.Add (str);
					}
				}

				((ICodeGenerator)this).GenerateCodeFromCompileUnit (e, s, new CodeGeneratorOptions());
				s.Close();
				f.Close();
				i++;
			}
			return Compile (options, fileNames, false);
		}
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {
        CodeNamespace ns = new CodeNamespace ("Namespace1");
        cu.Namespaces.Add (ns);

        // GENERATES (C#):
        //
        //   namespace Namespace1 {
        //      public class Class1 {
        //          public int Method1 {
        //              #line 300 "LinedStatement"
        //              return 0;
        //
        //              #line default
        //              #line hidden
        //          }
        //      }
        //   }

        CodeTypeDeclaration class1 = new CodeTypeDeclaration ("Class1");
        class1.IsClass = true;
        class1.Attributes = MemberAttributes.Public;
        ns.Types.Add (class1);

        CodeMemberMethod method1 = new CodeMemberMethod ();
        method1.ReturnType = new CodeTypeReference (typeof (int));
        method1.Name = "Method1";
        class1.Members.Add (method1);

        AddScenario ("FindLinedStatement");
        CodeMethodReturnStatement ret = new CodeMethodReturnStatement (new CodePrimitiveExpression (0));
        ret.LinePragma = new CodeLinePragma ("LinedStatement", 300);
        method1.Statements.Add (ret);
    }
示例#10
0
    public GeneratorData(Smoke* smoke, string defaultNamespace, List<string> imports, List<Assembly> references,
	                     CodeCompileUnit unit, string destination, string docs)
    {
        Destination = destination;
        Docs = docs;
        Smoke = smoke;
        string argNamesFile = GetArgNamesFile(Smoke);
        if (File.Exists(argNamesFile))
        {
            foreach (string[] strings in File.ReadAllLines(argNamesFile).Select(line => line.Split(';')))
            {
                ArgumentNames[strings[0]] = strings[1].Split(',');
            }
        }
        CompileUnit = unit;
        Imports = imports;

        References = references;
        DefaultNamespace = new CodeNamespace(defaultNamespace);
        this.AddUsings(DefaultNamespace);

        foreach (Assembly assembly in References)
        {
            smokeClassAttribute = assembly.GetType("QtCore.SmokeClass", false);
            if (smokeClassAttribute != null)
            {
                smokeClassGetSignature = smokeClassAttribute.GetProperty("Signature").GetGetMethod();
                break;
            }
        }
        foreach (Assembly assembly in References)
        {
            foreach (Type type in assembly.GetTypes())
            {
                object[] attributes = type.GetCustomAttributes(smokeClassAttribute, false);
                if (attributes.Length != 0)
                {
                    string smokeClassName = (string) smokeClassGetSignature.Invoke(attributes[0], null);
                    Type t;
                    if (ReferencedTypeMap.TryGetValue(smokeClassName, out t) && t.IsInterface)
                    {
                        continue;
                    }
                    ReferencedTypeMap[smokeClassName] = type;
                }
                else
                {
                    ReferencedTypeMap[type.Name] = type;
                }
            }
        }

        CompileUnit.Namespaces.Add(DefaultNamespace);
        NamespaceMap[defaultNamespace] = DefaultNamespace;
    }
    public static StringBuilder GenerateCode(CodeNamespace ns)
    {
        var compileUnit = new CodeCompileUnit();
        var codeProvider = new CSharpCodeProvider();
        var builder = new StringBuilder();
        var writer = new StringWriter(builder);

        compileUnit.Namespaces.Add(ns);
        codeProvider.GenerateCodeFromCompileUnit(compileUnit, writer, new CodeGeneratorOptions());
        writer.Flush();
        return builder;
    }
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {

        // GENERATES (C#):
        //
        //  public class MyConverter : System.ComponentModel.TypeConverter {
        //      
        //      private void Foo() {
        //          this.Foo(null);
        //      }
        //      
        //      private void Foo(string s) {
        //      }
        //      
        //      public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) {
        //          return base.CanConvertFrom(context, sourceType);
        //      }
        //  }

        CodeNamespace ns = new CodeNamespace ();
        cu.Namespaces.Add (ns);

        CodeTypeDeclaration class1 = new CodeTypeDeclaration ();
        class1.Name = "MyConverter";
        class1.BaseTypes.Add (new CodeTypeReference (typeof (System.ComponentModel.TypeConverter)));
        ns.Types.Add (class1);

        CodeMemberMethod foo1 = new CodeMemberMethod ();
        foo1.Name = "Foo";
        foo1.Statements.Add (new CodeMethodInvokeExpression (new CodeThisReferenceExpression (), "Foo", new CodePrimitiveExpression (null)));
        class1.Members.Add (foo1);

        CodeMemberMethod foo2 = new CodeMemberMethod ();
        foo2.Name = "Foo";
        foo2.Parameters.Add (new CodeParameterDeclarationExpression (typeof (string), "s"));
        class1.Members.Add (foo2);

        CodeMemberMethod convert = new CodeMemberMethod ();
        convert.Name = "CanConvertFrom";
        convert.Attributes = MemberAttributes.Public | MemberAttributes.Override | MemberAttributes.Overloaded;
        convert.ReturnType = new CodeTypeReference (typeof (bool));
        convert.Parameters.Add (new CodeParameterDeclarationExpression (typeof (System.ComponentModel.ITypeDescriptorContext), "context"));
        convert.Parameters.Add (new CodeParameterDeclarationExpression (typeof (System.Type), "sourceType"));
        convert.Statements.Add (
            new CodeMethodReturnStatement (
            new CodeMethodInvokeExpression (
            new CodeBaseReferenceExpression (),
            "CanConvertFrom",
            new CodeArgumentReferenceExpression ("context"),
            new CodeArgumentReferenceExpression ("sourceType"))));
        class1.Members.Add (convert);
    }
示例#13
0
文件: NDocGen.cs 项目: tgassner/NDoc
	static void Main(string[] args)
	{
		int namespaces = 10;
		int classesPerNamespace = 10;
		int methodsPerClass = 10;

		CodeCompileUnit codeCompileUnit = new CodeCompileUnit();

		for (int i = 0; i < namespaces; ++i)
		{
			CodeNamespace codeNamespace = new CodeNamespace();
			codeCompileUnit.Namespaces.Add(codeNamespace);
			codeNamespace.Name = "Namespace" + i;

			for (int j = 0; j < classesPerNamespace; ++j)
			{
				CodeTypeDeclaration codeTypeDeclaration = new CodeTypeDeclaration();
				codeNamespace.Types.Add(codeTypeDeclaration);
				codeTypeDeclaration.Name = "Class" + j;
				codeTypeDeclaration.TypeAttributes = TypeAttributes.Public;
				
				codeTypeDeclaration.Comments.Add(
					new CodeCommentStatement(
						"<summary>This is a summary.</summary>",
						true
					)
				);

				for (int k = 0; k < methodsPerClass; ++k)
				{
					CodeMemberMethod codeMemberMethod = new CodeMemberMethod();
					codeTypeDeclaration.Members.Add(codeMemberMethod);
					codeMemberMethod.Name = "Method" + k;
					codeMemberMethod.Attributes = MemberAttributes.Public;

					codeMemberMethod.Comments.Add(
						new CodeCommentStatement(
							"<summary>This is a summary.</summary>",
							true
						)
					);
				}
			}
		}

		CodeDomProvider codeDomProvider = new CSharpCodeProvider();
		ICodeGenerator codeGenerator = codeDomProvider.CreateGenerator();
		CodeGeneratorOptions codeGeneratorOptions = new CodeGeneratorOptions();
		codeGenerator.GenerateCodeFromCompileUnit(codeCompileUnit, Console.Out, codeGeneratorOptions);
	}
示例#14
0
		protected override StreamWriter GetTargetStream(string destDirectory, CodeCompileUnit cu)
		{
			string cun = cu.Namespaces[0].Name;
			int li = cun.LastIndexOf('.');
			string filNam = cun.Substring(li + 1);
			cun = cun.Substring(0, li);

			string packagedDirectory = destDirectory + "/" + cun.Replace('.', '/');

			if (!Directory.Exists(packagedDirectory))
				Directory.CreateDirectory(packagedDirectory);

			return new StreamWriter(packagedDirectory + "/" + filNam + FileExtension, false);
		}
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {
        CodeNamespace ns = new CodeNamespace ();
        ns.Name = "MyNamespace";
        cu.Namespaces.Add (ns);

        // GENERATES (C#):
        //
        // namespace MyNamespace {
        //     public class MyClass {
        //         private void PrimitiveTest() {
        //             char var1 = 'a';
        //             char var2 = '\0';
        //             string var3 = "foo\0bar\0baz\0";
        //             object var4 = null;
        //             int var5 = 42;
        //             double var6 = 3.14;
        //             System.Console.Write(var1);
        //             System.Console.Write(var2);
        //             System.Console.Write(var3);
        //             System.Console.Write(var4);
        //             System.Console.Write(var5);
        //             System.Console.Write(var6);
        //         }
        //     }
        // }
        
        CodeTypeDeclaration class1 = new CodeTypeDeclaration ();
        class1.Name = "MyClass";
        class1.IsClass = true;
        class1.Attributes = MemberAttributes.Public;
        ns.Types.Add (class1);


        CodeMemberMethod method = new CodeMemberMethod ();
        method.Name = "PrimitiveTest";
        method.Statements.Add (new CodeVariableDeclarationStatement (typeof (char), "var1", new CodePrimitiveExpression ('a')));
        method.Statements.Add (new CodeVariableDeclarationStatement (typeof (char), "var2", new CodePrimitiveExpression ('\0')));
        method.Statements.Add (new CodeVariableDeclarationStatement (typeof (string), "var3", new CodePrimitiveExpression ("foo\0bar\0baz\0")));
        method.Statements.Add (new CodeVariableDeclarationStatement (typeof (Object), "var4", new CodePrimitiveExpression (null)));
        method.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "var5", new CodePrimitiveExpression (42)));
        method.Statements.Add (new CodeVariableDeclarationStatement (typeof (double), "var6", new CodePrimitiveExpression (3.14)));
        method.Statements.Add (new CodeMethodInvokeExpression (new CodeTypeReferenceExpression (typeof (Console)), "Write", new CodeVariableReferenceExpression ("var1")));
        method.Statements.Add (new CodeMethodInvokeExpression (new CodeTypeReferenceExpression (typeof (Console)), "Write", new CodeVariableReferenceExpression ("var2")));
        method.Statements.Add (new CodeMethodInvokeExpression (new CodeTypeReferenceExpression (typeof (Console)), "Write", new CodeVariableReferenceExpression ("var3")));
        method.Statements.Add (new CodeMethodInvokeExpression (new CodeTypeReferenceExpression (typeof (Console)), "Write", new CodeVariableReferenceExpression ("var4")));
        method.Statements.Add (new CodeMethodInvokeExpression (new CodeTypeReferenceExpression (typeof (Console)), "Write", new CodeVariableReferenceExpression ("var5")));
        method.Statements.Add (new CodeMethodInvokeExpression (new CodeTypeReferenceExpression (typeof (Console)), "Write", new CodeVariableReferenceExpression ("var6")));
        class1.Members.Add (method);
    }
示例#16
0
		public virtual CodeNamespace GetNamespace(string name)
		{
			CodeNamespace nm;
			if (!Namespaces.TryGetValue(name, out nm))
			{
				CodeCompileUnit cu = new CodeCompileUnit();
				CodeNamespace n = new CodeNamespace(name);
				AddDefaultImports(n);
				cu.Namespaces.Add(n);
				CompileUnits.Add(cu);
				Namespaces[name] = n;
				nm = n;
			}
			return nm;
		}
示例#17
0
        CompilerResults ICodeCompiler.CompileAssemblyFromDom(CompilerParameters options, CodeCompileUnit e)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            try
            {
                return FromDom(options, e);
            }
            finally
            {
                options.TempFiles.SafeDelete();
            }
        }
示例#18
0
		private static Type CreateFor(Type t, Dictionary<string, List<string>> influences)
		{
			var provider = new CSharpCodeProvider();
			CompilerParameters cp = new CompilerParameters();
			cp.GenerateInMemory = true;
			CodeCompileUnit cu = new CodeCompileUnit();
			AddAllAssemblyAsReference(cu);
			cu.Namespaces.Add(CreateNamespace(t, influences));
#if DEBUG
			StringWriter sw = new StringWriter();
			provider.GenerateCodeFromCompileUnit(cu, sw, new CodeGeneratorOptions() { BracingStyle = "C" });
			Trace.WriteLine(sw.GetStringBuilder());
#endif
			CompilerResults cr = provider.CompileAssemblyFromDom(cp, cu);
			if (cr.Errors.Count > 0)
			{
				ThrowErrors(cr.Errors);
			}
			return cr.CompiledAssembly.GetTypes()[0];
		}
示例#19
0
        public void Compilation_NotSupported()
        {
            CodeDomProvider provider = GetProvider();

            var options = new CompilerParameters(new string[] { }, "test.exe");

            var cu = new CodeCompileUnit();
            var ns = new CodeNamespace("ns");
            var cd = new CodeTypeDeclaration("Program");
            var mm = new CodeEntryPointMethod();
            cd.Members.Add(mm);
            ns.Types.Add(cd);
            cu.Namespaces.Add(ns);

            string tempPath = Path.GetTempFileName();
            try
            {
                File.WriteAllText(tempPath, GetEmptyProgramSource());

                Assert.Throws<PlatformNotSupportedException>(() => provider.CompileAssemblyFromFile(options, tempPath));
                Assert.Throws<PlatformNotSupportedException>(() => provider.CompileAssemblyFromDom(options, cu));
                Assert.Throws<PlatformNotSupportedException>(() => provider.CompileAssemblyFromSource(options, GetEmptyProgramSource()));

#pragma warning disable 0618 // obsolete
                ICodeCompiler cc = provider.CreateCompiler();
                Assert.Throws<PlatformNotSupportedException>(() => cc.CompileAssemblyFromDom(options, cu));
                Assert.Throws<PlatformNotSupportedException>(() => cc.CompileAssemblyFromDomBatch(options, new[] { cu }));
                Assert.Throws<PlatformNotSupportedException>(() => cc.CompileAssemblyFromFile(options, tempPath));
                Assert.Throws<PlatformNotSupportedException>(() => cc.CompileAssemblyFromFileBatch(options, new[] { tempPath }));
                Assert.Throws<PlatformNotSupportedException>(() => cc.CompileAssemblyFromSource(options, GetEmptyProgramSource()));
                Assert.Throws<PlatformNotSupportedException>(() => cc.CompileAssemblyFromSourceBatch(options, new[] { GetEmptyProgramSource() }));
#pragma warning restore 0618
            }
            finally
            {
                File.Delete(tempPath);
            }
        }
	// Compile an array of CodeDom compile units.
	protected virtual CompilerResults FromDomBatch
				(CompilerParameters options, CodeCompileUnit[] ea)
			{
				// Write all of the CodeDom units to temporary files.
				String[] tempFiles = new String [ea.Length];
				int src;
				Stream stream;
				StreamWriter writer;
				for(src = 0; src < ea.Length; ++src)
				{
					foreach(String assembly in ea[src].ReferencedAssemblies)
					{
						if(!options.ReferencedAssemblies.Contains(assembly))
						{
							options.ReferencedAssemblies.Add(assembly);
						}
					}
					tempFiles[src] = options.TempFiles.AddExtension
							(src + FileExtension);
					stream = new FileStream(tempFiles[src], FileMode.Create,
											FileAccess.Write, FileShare.Read);
					try
					{
						writer = new StreamWriter(stream, Encoding.UTF8);
						((ICodeGenerator)this).GenerateCodeFromCompileUnit
								(ea[src], writer, Options);
						writer.Flush();
						writer.Close();
					}
					finally
					{
						stream.Close();
					}
				}
				
				// Compile the temporary files.
				return FromFileBatch(options, tempFiles);
			}
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {

        // create a namespace
        CodeNamespace ns = new CodeNamespace ("NS");
        ns.Imports.Add (new CodeNamespaceImport ("System"));
        ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Forms"));
        cu.ReferencedAssemblies.Add ("System.Windows.Forms.dll");
        cu.Namespaces.Add (ns);

        // create a class
        CodeTypeDeclaration class1 = new CodeTypeDeclaration ();
        class1.Name = "Test";
        class1.IsClass = true;
        ns.Types.Add (class1);


        // create method to test casting enum -> int
        //     GENERATE (C#):
        //        public int EnumToInt(System.Windows.Forms.AnchorStyles enum1) {
        //            return ((int)(enum1));
        //        }
        AddScenario ("CheckEnumToInt1", "Check the return value of EnumToInt() with a single flag");
        AddScenario ("CheckEnumToInt2", "Check the return value of EnumToInt() with multiple flags");
        CodeMemberMethod enumToInt = new CodeMemberMethod ();
        enumToInt.Name = "EnumToInt";
        enumToInt.ReturnType = new CodeTypeReference (typeof (int));
        enumToInt.Attributes = MemberAttributes.Public;
        CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (typeof (System.Windows.Forms.AnchorStyles), "enum1");
        enumToInt.Parameters.Add (param);
        enumToInt.Statements.Add (new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new CodeArgumentReferenceExpression ("enum1"))));
        class1.Members.Add (enumToInt);

        // create method to test casting enum -> int
        //     GENERATE (C#):
        //       public virtual int CastReturnValue(string value) {
        //          float val = System.Single.Parse(value, System.Globalization.CultureInfo.InvariantCulture);
        //          return ((int) val);
        //       }
        AddScenario ("CheckCastReturnValue", "Check the return value of CastReturnValue()");
        CodeMemberMethod castReturnValue = new CodeMemberMethod ();
        castReturnValue.Name = "CastReturnValue";
        castReturnValue.ReturnType = new CodeTypeReference (typeof (int));
        castReturnValue.Attributes = MemberAttributes.Public;
        CodeParameterDeclarationExpression strParam = new CodeParameterDeclarationExpression (typeof (string), "value");
        castReturnValue.Parameters.Add (strParam);
        castReturnValue.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "val",
                    CDHelper.CreateMethodInvoke (new CodeTypeReferenceExpression (new CodeTypeReference ("System.Int32")), // F#: Type conversion "int -> float" is not a type-cast!
                        "Parse", new CodeArgumentReferenceExpression ("value"),
                        new CodePropertyReferenceExpression (new CodeTypeReferenceExpression ("System.Globalization.CultureInfo"),
                            "InvariantCulture"))));
        castReturnValue.Statements.Add (new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new CodeVariableReferenceExpression ("val"))));
        class1.Members.Add (castReturnValue);


        // create method to test casting interface -> class
        //     GENERATE (C#):
        //        public string CastInterface(System.ICloneable value) {
        //            return ((string)(value));
        //        }
        AddScenario ("CheckCastInterface", "Check the return value of CastInterface()");
        CodeMemberMethod castInterface = new CodeMemberMethod ();
        castInterface.Name = "CastInterface";
        castInterface.ReturnType = new CodeTypeReference (typeof (string));
        castInterface.Attributes = MemberAttributes.Public;
        CodeParameterDeclarationExpression interfaceParam = new CodeParameterDeclarationExpression (typeof (System.ICloneable), "value");
        castInterface.Parameters.Add (interfaceParam);
        castInterface.Statements.Add (new CodeMethodReturnStatement (new CodeCastExpression (typeof (string), new CodeArgumentReferenceExpression ("value"))));
        class1.Members.Add (castInterface);

        // create method to test casting value type -> reference type
        //     GENERATE (C#):
        //         public object ValueToReference(int value) {
        //             return ((object)(value));
        //         }
        AddScenario ("CheckValueToReference", "Check the return value of ValueToReference()");
        CodeMemberMethod valueToReference = new CodeMemberMethod ();
        valueToReference.Name = "ValueToReference";
        valueToReference.ReturnType = new CodeTypeReference (typeof (System.Object));
        valueToReference.Attributes = MemberAttributes.Public;
        CodeParameterDeclarationExpression valueParam = new CodeParameterDeclarationExpression (typeof (int), "value");
        valueToReference.Parameters.Add (valueParam);
        valueToReference.Statements.Add (new CodeMethodReturnStatement (new CodeCastExpression (typeof (System.Object), new CodeArgumentReferenceExpression ("value"))));
        class1.Members.Add (valueToReference);

    }
 public CodeCompileUnitToCSharp(CodeCompileUnit codeCompileUnit) : base(codeCompileUnit)
 {
 }
示例#23
0
        public void 自动生成类的实验1()
        {
            #region 准备一个代码编译器单元
            CodeCompileUnit unit = new CodeCompileUnit();
            #endregion

            #region 命名空间
            CodeNamespace CurrentNameSpace = new CodeNamespace("生成代码的实验");
            CurrentNameSpace.Imports.Add(new CodeNamespaceImport("System"));
            CurrentNameSpace.Imports.Add(new CodeNamespaceImport("System.Text"));
            //CodeTypeDeclaration ctd = new CodeTypeDeclaration(Name);
            //return CurrentNameSpace;
            #endregion

            #region  类
            CodeTypeDeclaration ctd = new CodeTypeDeclaration("T_AJ_INSURE");
            ctd.IsClass    = true;
            ctd.Attributes = MemberAttributes.Public;
            #endregion

            #region 声明方法(程序入口点)?
            //CodeEntryPointMethod method = new CodeEntryPointMethod();
            //method.Attributes = MemberAttributes.Public;
            #endregion

            #region 声明方法?
            CodeMemberProperty property = new CodeMemberProperty();
            property.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            property.Name       = "ID";
            property.HasGet     = true;
            property.HasSet     = true;
            property.Type       = new CodeTypeReference(typeof(System.Int32));
            property.Comments.Add(new CodeCommentStatement("这是ID属性"));
            #endregion

            #region 把类放在命名空间里面
            CurrentNameSpace.Types.Add(ctd);
            #endregion

            #region 把该命名空间加入到编译器单元的命名空间集合中
            unit.Namespaces.Add(CurrentNameSpace);
            #endregion

            #region 把该命名空间加入到编译器单元的命名空间集合中
            unit.Namespaces.Add(CurrentNameSpace);
            #endregion

            #region 加入这种方法
            ctd.Members.Add(property);
            #endregion

            #region 添加字段
            //CodeMemberField field = new CodeMemberField(typeof(System.String), "_Id");
            //field.Attributes = MemberAttributes.Private;
            //ctd.Members.Add(field);
            #endregion

            string outputFile = "\\Customer.cs";
            string path       = Application.StartupPath;

            #region 生成代码
            //生成代码

            CodeDomProvider provider = CodeDomProvider.CreateProvider("C#");

            CodeGeneratorOptions options = new CodeGeneratorOptions();

            options.BracingStyle = "C";

            options.BlankLinesBetweenMembers = true;

            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path + outputFile))
            {
                provider.GenerateCodeFromCompileUnit(unit, sw, options);
            }
            #endregion
        }
示例#24
0
        static double Calculate(string formula)
        {
            // create compile unit
            CodeCompileUnit compileUnit = new CodeCompileUnit();
            // add a namespace
            CodeNamespace codeNamespace = new CodeNamespace("MyCalculator");

            compileUnit.Namespaces.Add(codeNamespace);

            // add imports/using
            codeNamespace.Imports.Add(new CodeNamespaceImport("System"));

            // create a class
            CodeTypeDeclaration classType = new CodeTypeDeclaration("Calculator");

            classType.Attributes = MemberAttributes.Public;
            codeNamespace.Types.Add(classType);

            // create a method
            CodeMemberMethod method = new CodeMemberMethod();

            method.Name       = "Calc";
            method.Attributes = MemberAttributes.Public;
            method.ReturnType = new CodeTypeReference(typeof(double));
            classType.Members.Add(method);

            // add the return statement with the calculation
            CodeMethodReturnStatement returnStatement = new CodeMethodReturnStatement(
                new CodeSnippetExpression(formula));

            method.Statements.Add(returnStatement);

            // add assemblies for linking
            String[] assemblyNames =
            {
                typeof(System._AppDomain).Assembly.Location,
                typeof(System.CodeDom.Compiler.GeneratedCodeAttribute).Assembly.Location,
            };

            // compile in memory
            CodeDomProvider    provider   = CodeDomProvider.CreateProvider("CS");
            CompilerParameters parameters = new CompilerParameters(assemblyNames);

            parameters.GenerateExecutable    = false;
            parameters.GenerateInMemory      = true;
            parameters.TreatWarningsAsErrors = false;

            // check for errors
            CompilerResults compilerResults = provider.CompileAssemblyFromDom(parameters, compileUnit);
            StringBuilder   errors          = new StringBuilder();
            string          errorText       = String.Empty;

            foreach (CompilerError compilerError in compilerResults.Errors)
            {
                errorText += compilerError.ToString() + "\n";
            }

            if (errors.Length == 0)
            {
                Type   type        = compilerResults.CompiledAssembly.GetType("MyCalculator.Calculator");
                object objInstance = Activator.CreateInstance(type);
                object result      = type.GetMethod("Calc").Invoke(objInstance, new object[] { });
                return((double)result);
            }
            else
            {
                throw new Exception(errorText);
            }
        }
示例#25
0
        private void GenRepository(Table table)
        {
            var className = this.Format($"{table.Name}Repository");

            var targetUnit = new CodeCompileUnit();
            var nameSpace  = new CodeNamespace("Repository");

            nameSpace.Imports.Add(new CodeNamespaceImport("System"));
            nameSpace.Imports.Add(new CodeNamespaceImport("Dapper.Contrib.Extensions"));

            var targetClass = new CodeTypeDeclaration(className);

            targetClass.IsClass        = true;
            targetClass.TypeAttributes = TypeAttributes.Public;

            nameSpace.Types.Add(targetClass);
            targetUnit.Namespaces.Add(nameSpace);

            var getAllMethod = new CodeMemberMethod();

            getAllMethod.Attributes = MemberAttributes.Public;
            getAllMethod.Name       = "Get";
            getAllMethod.ReturnType = new CodeTypeReference(typeof(IList <object>));
            targetClass.Members.Add(getAllMethod);


            var getMethod = new CodeMemberMethod();

            getMethod.Attributes = MemberAttributes.Public;
            getMethod.Name       = "Get";
            getMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "id"));
            getMethod.ReturnType = new CodeTypeReference(typeof(object));
            targetClass.Members.Add(getMethod);

            var newMethod = new CodeMemberMethod();

            newMethod.Attributes = MemberAttributes.Public;
            newMethod.Name       = "New";
            newMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "entity"));
            newMethod.ReturnType = new CodeTypeReference(typeof(bool));
            targetClass.Members.Add(newMethod);

            var updateMethod = new CodeMemberMethod();

            updateMethod.Attributes = MemberAttributes.Public;
            updateMethod.Name       = "Update";
            updateMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "entity"));
            updateMethod.ReturnType = new CodeTypeReference(typeof(bool));
            targetClass.Members.Add(updateMethod);

            var deleteMethod = new CodeMemberMethod();

            deleteMethod.Attributes = MemberAttributes.Public;
            deleteMethod.Name       = "Delete";
            deleteMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "id"));
            deleteMethod.ReturnType = new CodeTypeReference(typeof(bool));
            targetClass.Members.Add(deleteMethod);


            var outputFileName = $"{className}.cs";
            var provider       = CodeDomProvider.CreateProvider("CSharp");
            var options        = new CodeGeneratorOptions();

            options.BracingStyle = "C";
            using (var sourceWriter = new StreamWriter($@"c:\temp\{outputFileName}"))
            {
                provider.GenerateCodeFromCompileUnit(targetUnit, sourceWriter, options);
            }
        }
        protected override string CreateProxyFile(DotNetProject dotNetProject, FilePath basePath, string proxyNamespace, string referenceName)
        {
            CodeCompileUnit ccu = new CodeCompileUnit();
            CodeNamespace   cns = new CodeNamespace(proxyNamespace);

            ccu.Namespaces.Add(cns);

            bool targetMoonlight = dotNetProject.TargetFramework.Id.Identifier == ("Silverlight");
            bool targetMonoTouch = dotNetProject.TargetFramework.Id.Identifier == ("MonoTouch");
            bool targetMonoDroid = dotNetProject.TargetFramework.Id.Identifier == ("MonoDroid");

            bool targetCoreClr       = targetMoonlight || targetMonoDroid || targetMonoTouch;
            bool generateSyncMethods = targetMonoDroid | targetMonoTouch;

            ServiceContractGenerator generator = new ServiceContractGenerator(ccu);

            generator.Options = ServiceContractGenerationOptions.ChannelInterface | ServiceContractGenerationOptions.ClientClass;
            if (refGroup.ClientOptions.GenerateAsynchronousMethods || targetCoreClr)
            {
                generator.Options |= ServiceContractGenerationOptions.AsynchronousMethods;
            }
            if (refGroup.ClientOptions.GenerateInternalTypes)
            {
                generator.Options |= ServiceContractGenerationOptions.InternalTypes;
            }
            if (refGroup.ClientOptions.GenerateMessageContracts)
            {
                generator.Options |= ServiceContractGenerationOptions.TypedMessages;
            }
//			if (targetMoonlight || targetMonoTouch)
//				generator.Options |= ServiceContractGenerationOptions.EventBasedAsynchronousMethods;

            MetadataSet mset;

            if (protocol != null)
            {
                mset = ToMetadataSet(protocol);
            }
            else
            {
                mset = metadata;
            }

            CodeDomProvider code_provider = GetProvider(dotNetProject);

            List <IWsdlImportExtension> list = new List <IWsdlImportExtension> ();

            list.Add(new TransportBindingElementImporter());
            list.Add(new XmlSerializerMessageContractImporter());

            WsdlImporter importer = new WsdlImporter(mset);
            Collection <ContractDescription> contracts = importer.ImportAllContracts();

            foreach (ContractDescription cd in contracts)
            {
                cd.Namespace = proxyNamespace;
                if (targetCoreClr)
                {
                    var moonctx = new MoonlightChannelBaseContext();
                    cd.Behaviors.Add(new MoonlightChannelBaseContractExtension(moonctx, generateSyncMethods));
                    foreach (var od in cd.Operations)
                    {
                        od.Behaviors.Add(new MoonlightChannelBaseOperationExtension(moonctx, generateSyncMethods));
                    }
                    generator.GenerateServiceContractType(cd);
                    moonctx.Fixup();
                }
                else
                {
                    generator.GenerateServiceContractType(cd);
                }
            }

            string fileSpec = Path.Combine(basePath, referenceName + "." + code_provider.FileExtension);

            using (TextWriter w = File.CreateText(fileSpec)) {
                code_provider.GenerateCodeFromCompileUnit(ccu, w, null);
            }
            return(fileSpec);
        }
        private void RunTestInternal(string name,
                                     string baselineName,
                                     bool generatePragmas,
                                     bool designTimeMode,
                                     IList <GeneratedCodeMapping> expectedDesignTimePragmas,
                                     TestSpan[] spans,
                                     bool withTabs,
                                     Action <RazorEngineHost> hostConfig)
        {
            // Load the test files
            if (baselineName == null)
            {
                baselineName = name;
            }

            string source         = TestFile.Create(String.Format("CodeGenerator.{1}.Source.{0}.{2}", name, LanguageName, FileExtension)).ReadAllText();
            string expectedOutput = TestFile.Create(String.Format("CodeGenerator.{1}.Output.{0}.{2}", baselineName, LanguageName, BaselineExtension)).ReadAllText();

            // Set up the host and engine
            RazorEngineHost host = CreateHost();

            host.NamespaceImports.Add("System");
            host.DesignTimeMode   = designTimeMode;
            host.StaticHelpers    = true;
            host.DefaultClassName = name;

            // Add support for templates, etc.
            host.GeneratedClassContext = new GeneratedClassContext(GeneratedClassContext.DefaultExecuteMethodName,
                                                                   GeneratedClassContext.DefaultWriteMethodName,
                                                                   GeneratedClassContext.DefaultWriteLiteralMethodName,
                                                                   "WriteTo",
                                                                   "WriteLiteralTo",
                                                                   "Template",
                                                                   "DefineSection",
                                                                   "BeginContext",
                                                                   "EndContext")
            {
                LayoutPropertyName   = "Layout",
                ResolveUrlMethodName = "Href"
            };
            if (hostConfig != null)
            {
                hostConfig(host);
            }

            host.IsIndentingWithTabs = withTabs;

            RazorTemplateEngine engine = new RazorTemplateEngine(host);

            // Generate code for the file
            GeneratorResults results = null;

            using (StringTextBuffer buffer = new StringTextBuffer(source))
            {
                results = engine.GenerateCode(buffer, className: name, rootNamespace: TestRootNamespaceName, sourceFileName: generatePragmas ? String.Format("{0}.{1}", name, FileExtension) : null);
            }

            // Generate code
            CodeCompileUnit ccu          = results.GeneratedCode;
            CodeDomProvider codeProvider = (CodeDomProvider)Activator.CreateInstance(host.CodeLanguage.CodeDomProviderType);

            CodeGeneratorOptions options = new CodeGeneratorOptions();

            // Both run-time and design-time use these settings. See:
            // * $/Dev10/pu/SP_WebTools/venus/html/Razor/Impl/RazorCodeGenerator.cs:204
            // * $/Dev10/Releases/RTMRel/ndp/fx/src/xsp/System/Web/Compilation/BuildManagerHost.cs:373
            options.BlankLinesBetweenMembers = false;
            options.IndentString             = String.Empty;

            StringBuilder output = new StringBuilder();

            using (StringWriter writer = new StringWriter(output))
            {
                codeProvider.GenerateCodeFromCompileUnit(ccu, writer, options);
            }

            WriteBaseline(String.Format(@"test\System.Web.Razor.Test\TestFiles\CodeGenerator\{0}\Output\{1}.{2}", LanguageName, baselineName, BaselineExtension), MiscUtils.StripRuntimeVersion(output.ToString()));

#if !GENERATE_BASELINES
            string textOutput = MiscUtils.StripRuntimeVersion(output.ToString());

            //// Verify code against baseline
            Assert.Equal(expectedOutput, textOutput);
#endif

            IEnumerable <Span> generatedSpans = results.Document.Flatten();

            foreach (var span in generatedSpans)
            {
                VerifyNoBrokenEndOfLines(span.Content);
            }

            // Verify design-time pragmas
            if (designTimeMode)
            {
                if (spans != null)
                {
                    Assert.Equal(spans, generatedSpans.Select(span => new TestSpan(span)).ToArray());
                }

                if (expectedDesignTimePragmas != null)
                {
                    Assert.True(results.DesignTimeLineMappings != null && results.DesignTimeLineMappings.Count > 0);

                    Assert.Equal(expectedDesignTimePragmas.Count, results.DesignTimeLineMappings.Count);

                    Assert.Equal(
                        expectedDesignTimePragmas.ToArray(),
                        results.DesignTimeLineMappings
                        .OrderBy(p => p.Key)
                        .Select(p => p.Value)
                        .ToArray());
                }
            }
        }
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {
#if WHIDBEY
        // VB code provider doesn't currently generate checksum statements.  This
        // will be completed before the next release of the CLR.
        // JScript does not currently support checksum pragmas.
        if (!(provider is VBCodeProvider) && !(provider is JScriptCodeProvider)) {
            // GENERATES (C#):
            // #pragma checksum "c:\foo\bar\OuterLinePragma.txt" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "DEAD"
            // #pragma checksum "bogus.txt" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "F00BAA"
            // #pragma checksum "" "{00000000-0000-0000-0000-000000000000}" ""
            //
            //  // Namespace Comment
            //  namespace Namespace1 {
            //      
            //      
            //      // Outer Type Comment
            //      
            //      #line 300 "c:\foo\bar\OuterLinePragma.txt"
            //      public class Class1 {
            //          
            //          public void Method1() {
            //          }
            //          
            //          // Method 2 Comment
            //          public void Method2() {
            //          }
            //      }
            //      
            //      #line default
            //      #line hidden
            //  }

            AddScenario ("CheckPragmasInSrcCode", "Checks to see if the pragmas are in the generated source code.");
            CodeChecksumPragma pragma1 = new CodeChecksumPragma();
            pragma1.FileName = "c:\\foo\\bar\\OuterLinePragma.txt";
            pragma1.ChecksumAlgorithmId = HashMD5;
            pragma1.ChecksumData = new byte[] {0xDE, 0xAD};            
            cu.StartDirectives.Add(pragma1);
            CodeChecksumPragma pragma2 = new CodeChecksumPragma("bogus.txt", HashSHA1, new byte[]{0xF0, 0x0B, 0xAA});
            cu.StartDirectives.Add(pragma2);
            CodeChecksumPragma pragma3 = new CodeChecksumPragma();
            cu.StartDirectives.Add(pragma3);

            CodeNamespace ns = new CodeNamespace("Namespace1");
            ns.Comments.Add(new CodeCommentStatement("Namespace Comment"));

            cu.Namespaces.Add(ns);

            CodeTypeDeclaration cd = new CodeTypeDeclaration ("Class1");
            ns.Types.Add(cd);

            cd.Comments.Add(new CodeCommentStatement("Outer Type Comment"));
            cd.LinePragma = new CodeLinePragma("c:\\foo\\bar\\OuterLinePragma.txt", 300);

            CodeMemberMethod method1 = new CodeMemberMethod();
            method1.Name = "Method1";
            method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;            


            CodeMemberMethod method2 = new CodeMemberMethod();
            method2.Name = "Method2";
            method2.Attributes = (method2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            method2.Comments.Add(new CodeCommentStatement("Method 2 Comment"));                                            

            cd.Members.Add(method1);
            cd.Members.Add(method2);
        }
#endif
    }
示例#29
0
        private static CodeCompileUnit InternalCreate(Dictionary <string, ResourceData> resourceList, string baseName, string generatedCodeNamespace, string resourcesNamespace, CodeDomProvider codeProvider, bool internalClass, out string[] unmatchable)
        {
            Hashtable hashtable;

            if (baseName == null)
            {
                throw new ArgumentNullException("baseName");
            }
            if (codeProvider == null)
            {
                throw new ArgumentNullException("codeProvider");
            }
            ArrayList  errors = new ArrayList(0);
            SortedList list2  = VerifyResourceNames(resourceList, codeProvider, errors, out hashtable);
            string     str    = baseName;

            if (!codeProvider.IsValidIdentifier(str))
            {
                string str2 = VerifyResourceName(str, codeProvider);
                if (str2 != null)
                {
                    str = str2;
                }
            }
            if (!codeProvider.IsValidIdentifier(str))
            {
                throw new ArgumentException(Microsoft.Build.Tasks.SR.GetString("InvalidIdentifier", new object[] { str }));
            }
            if (!string.IsNullOrEmpty(generatedCodeNamespace) && !codeProvider.IsValidIdentifier(generatedCodeNamespace))
            {
                string str3 = VerifyResourceName(generatedCodeNamespace, codeProvider, true);
                if (str3 != null)
                {
                    generatedCodeNamespace = str3;
                }
            }
            CodeCompileUnit e = new CodeCompileUnit();

            e.ReferencedAssemblies.Add("System.dll");
            e.UserData.Add("AllowLateBound", false);
            e.UserData.Add("RequireVariableDeclaration", true);
            CodeNamespace namespace2 = new CodeNamespace(generatedCodeNamespace);

            namespace2.Imports.Add(new CodeNamespaceImport("System"));
            e.Namespaces.Add(namespace2);
            CodeTypeDeclaration declaration = new CodeTypeDeclaration(str);

            namespace2.Types.Add(declaration);
            AddGeneratedCodeAttributeforMember(declaration);
            TypeAttributes attributes = internalClass ? TypeAttributes.AnsiClass : TypeAttributes.Public;

            declaration.TypeAttributes = attributes;
            declaration.Comments.Add(new CodeCommentStatement("<summary>", true));
            declaration.Comments.Add(new CodeCommentStatement(Microsoft.Build.Tasks.SR.GetString("ClassDocComment"), true));
            CodeCommentStatement statement = new CodeCommentStatement(Microsoft.Build.Tasks.SR.GetString("ClassComments1"), true);

            declaration.Comments.Add(statement);
            statement = new CodeCommentStatement(Microsoft.Build.Tasks.SR.GetString("ClassComments3"), true);
            declaration.Comments.Add(statement);
            declaration.Comments.Add(new CodeCommentStatement("</summary>", true));
            CodeTypeReference attributeType = new CodeTypeReference(typeof(DebuggerNonUserCodeAttribute))
            {
                Options = CodeTypeReferenceOptions.GlobalReference
            };

            declaration.CustomAttributes.Add(new CodeAttributeDeclaration(attributeType));
            CodeTypeReference reference2 = new CodeTypeReference(typeof(CompilerGeneratedAttribute))
            {
                Options = CodeTypeReferenceOptions.GlobalReference
            };

            declaration.CustomAttributes.Add(new CodeAttributeDeclaration(reference2));
            bool useStatic        = internalClass || codeProvider.Supports(GeneratorSupport.PublicStaticMembers);
            bool supportsTryCatch = codeProvider.Supports(GeneratorSupport.TryCatchStatements);

            EmitBasicClassMembers(declaration, generatedCodeNamespace, baseName, resourcesNamespace, internalClass, useStatic, supportsTryCatch);
            foreach (DictionaryEntry entry in list2)
            {
                string key          = (string)entry.Key;
                string resourceName = (string)hashtable[key];
                if (resourceName == null)
                {
                    resourceName = key;
                }
                if (!DefineResourceFetchingProperty(key, resourceName, (ResourceData)entry.Value, declaration, internalClass, useStatic))
                {
                    errors.Add(entry.Key);
                }
            }
            unmatchable = (string[])errors.ToArray(typeof(string));
            CodeGenerator.ValidateIdentifiers(e);
            return(e);
        }
示例#30
0
    static int Main(string[] args)
    {
        if (args.Length < 3)
        {
            Console.WriteLine("Usage: <out-dir> <corefx dir> <test assembly filename> <xunit console options>");
            return(1);
        }

        var testAssemblyName = Path.GetFileNameWithoutExtension(args [2]);
        var testAssemblyFull = Path.GetFullPath(args[2]);
        var outdir_name      = Path.Combine(args [0], testAssemblyName);
        var sdkdir           = args [1] + "/artifacts/bin/runtime/netcoreapp-OSX-Debug-x64";

        args = args.Skip(2).ToArray();
        // Response file support
        var extra_args = new List <string> ();

        for (int i = 0; i < args.Length; ++i)
        {
            var arg = args [i];
            if (arg [0] == '@')
            {
                foreach (var line in File.ReadAllLines(arg.Substring(1)))
                {
                    if (line.Length == 0 || line [0] == '#')
                    {
                        continue;
                    }
                    extra_args.AddRange(line.Split(' '));
                }
                args [i] = "";
            }
        }
        args = args.Where(s => s != String.Empty).Concat(extra_args).ToArray();

        // Despite a lot of effort, couldn't get dotnet to load these assemblies from the sdk dir, so copy them to our binary dir
//		File.Copy ($"{sdkdir}/Microsoft.DotNet.PlatformAbstractions.dll", AppContext.BaseDirectory, true);
        File.Copy($"{sdkdir}/CoreFx.Private.TestUtilities.dll", AppContext.BaseDirectory, true);
        File.Copy($"{sdkdir}/Microsoft.DotNet.XUnitExtensions.dll", AppContext.BaseDirectory, true);

        var cmdline = CommandLine.Parse(args);

        // Ditto
        File.Copy(cmdline.Project.Assemblies.First().AssemblyFilename, AppContext.BaseDirectory, true);

        var assembly = Assembly.LoadFrom(Path.Combine(AppContext.BaseDirectory, Path.GetFileName(cmdline.Project.Assemblies.First().AssemblyFilename)));

        var msg_sink = new MsgSink();
        var xunit2   = new Xunit2Discoverer(AppDomainSupport.Denied, new NullSourceInformationProvider(), new ReflectionAssemblyInfo(assembly), null, null, msg_sink);
        var sink     = new TestDiscoverySink();
        var config   = new TestAssemblyConfiguration()
        {
            DiagnosticMessages = true, InternalDiagnosticMessages = true, PreEnumerateTheories = false
        };

        xunit2.Find(false, sink, TestFrameworkOptions.ForDiscovery(config));
        sink.Finished.WaitOne();

        foreach (XunitTestCase tc in sink.TestCases)
        {
            ComputeTraits(assembly, tc);
        }

        // Compute testcase data
        var tc_data = new Dictionary <XunitTestCase, List <CaseData> > ();

        foreach (XunitTestCase tc in sink.TestCases)
        {
            var m = ((ReflectionMethodInfo)tc.Method).MethodInfo;
            var t = m.ReflectedType;

            var cases = new List <CaseData> ();

            if (m.GetParameters().Length > 0)
            {
                foreach (var cattr in m.GetCustomAttributes(true))
                {
                    if (cattr is InlineDataAttribute)
                    {
                        var data = ((InlineDataAttribute)cattr).GetData(null).First();
                        if (data == null)
                        {
                            data = new object [m.GetParameters().Length];
                        }
                        if (data.Length != m.GetParameters().Length)
                        {
                            throw new Exception();
                        }

                        bool unhandled = false;
                        foreach (var val in data)
                        {
                            if (val is float || val is double)
                            {
                                unhandled = true;
                            }
                            if (val is Type)
                            {
                                var type = val as Type;
                                if (!type.IsVisible)
                                {
                                    unhandled = true;
                                }
                            }
                            if (val is Enum)
                            {
                                if (!val.GetType().IsPublic)
                                {
                                    unhandled = true;
                                }
                            }
                        }
                        if (!unhandled)
                        {
                            cases.Add(new CaseData()
                            {
                                Values = data
                            });
                        }
                    }
                }
            }
            else
            {
                cases.Add(new CaseData());
            }
            tc_data [tc] = cases;
        }

#if FALSE
        //w.WriteLine ($"\t\ttypeof({typename}).GetMethod (\"{m.Name}\", BindingFlags.Static|BindingFlags.NonPublic).Invoke(null, null);");
        //w.WriteLine ($"\t\tusing (var o = new {typename} ()) {{");
        //if (cmdline.StopOnFail)
        //w.WriteLine ("\t\tif (nfailed > 0) return 1;");
        //w.WriteLine ("\t\tConsole.WriteLine (\"RUN: \" + nrun + \", FAILED: \" + nfailed);");
#endif

        var cu = new CodeCompileUnit();
        var ns = new CodeNamespace("");
        cu.Namespaces.Add(ns);
        ns.Imports.Add(new CodeNamespaceImport("System"));
        ns.Imports.Add(new CodeNamespaceImport("System.Reflection"));
        var code_class = new CodeTypeDeclaration("RunTests");
        ns.Types.Add(code_class);

        var code_main = new CodeEntryPointMethod();
        code_main.ReturnType = new CodeTypeReference("System.Int32");
        code_class.Members.Add(code_main);

        var statements = code_main.Statements;
        statements.Add(new CodeVariableDeclarationStatement(typeof(int), "nrun", new CodePrimitiveExpression(0)));
        statements.Add(new CodeVariableDeclarationStatement(typeof(int), "nfailed", new CodePrimitiveExpression(0)));

        int nskipped = 0;

        var filters = cmdline.Project.Filters;
        foreach (XunitTestCase tc in sink.TestCases)
        {
            var m = ((ReflectionMethodInfo)tc.Method).MethodInfo;
            //Console.WriteLine ("" + m.ReflectedType + " " + m + " " + (tc.TestMethodArguments == null));
            var t = m.ReflectedType;
            if (t.IsGenericType)
            {
                nskipped++;
                continue;
            }
            if (!filters.Filter(tc))
            {
                nskipped++;
                continue;
            }

            var cases = tc_data [tc];

            int caseindex = 0;
            foreach (var test in cases)
            {
                string typename = GetTypeName(t);
                string msg;
                if (cases.Count > 1)
                {
                    msg = $"{typename}.{m.Name}[{caseindex}] ...";
                }
                else
                {
                    msg = $"{typename}.{m.Name} ...";
                }
                caseindex++;
                statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Console"), "WriteLine", new CodeExpression [] { new CodePrimitiveExpression(msg) }));
                statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("nrun"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("nrun"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1))));
                var try1 = new CodeTryCatchFinallyStatement();
                statements.Add(try1);
                if (!m.IsStatic)
                {
                    // FIXME: Disposable
                    try1.TryStatements.Add(new CodeVariableDeclarationStatement("var", "o", new CodeObjectCreateExpression(t, new CodeExpression[] {})));
                }
                if (!m.IsPublic)
                {
                    // FIXME:
                    nskipped++;
                }
                else
                {
                    CodeMethodInvokeExpression call;

                    if (m.IsStatic)
                    {
                        call = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(t), m.Name, new CodeExpression [] {});
                    }
                    else
                    {
                        call = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("o"), m.Name, new CodeExpression [] {});
                    }

                    if (test.Values != null)
                    {
                        foreach (var val in test.Values)
                        {
                            call.Parameters.Add(EncodeValue(val));
                        }
                    }
                    try1.TryStatements.Add(call);
                }
                var catch1 = new CodeCatchClause("ex", new CodeTypeReference("System.Exception"));
                catch1.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("nfailed"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("nfailed"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1))));
                catch1.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Console"), "WriteLine", new CodeExpression [] {
                    new CodeBinaryOperatorExpression(
                        new CodePrimitiveExpression("FAILED: "),
                        CodeBinaryOperatorType.Add,
                        new CodeVariableReferenceExpression("ex"))
                }));
                try1.CatchClauses.Add(catch1);
            }
        }

        statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Console"), "WriteLine", new CodeExpression [] {
            new CodeBinaryOperatorExpression(
                new CodePrimitiveExpression("RUN: "),
                CodeBinaryOperatorType.Add,
                new CodeVariableReferenceExpression("nrun"))
        }));
        statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Console"), "WriteLine", new CodeExpression [] {
            new CodeBinaryOperatorExpression(
                new CodePrimitiveExpression("FAILURES: "),
                CodeBinaryOperatorType.Add,
                new CodeVariableReferenceExpression("nfailed"))
        }));
        statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Console"), "WriteLine", new CodeExpression [] {
            new CodeBinaryOperatorExpression(
                new CodePrimitiveExpression("SKIPPED: "),
                CodeBinaryOperatorType.Add,
                new CodePrimitiveExpression(nskipped))
        }));
        statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(0)));


        Directory.CreateDirectory(outdir_name);
        var outfile_name = Path.Combine(outdir_name, "runner.cs");
        var provider     = new CSharpCodeProvider();
        using (var w2 = File.CreateText(outfile_name)) {
            provider.GenerateCodeFromCompileUnit(cu, w2, new CodeGeneratorOptions());
        }

        var csproj_template = File.ReadAllText("gen-test.csproj.template");
        csproj_template = csproj_template.Replace("#XUNIT_LOCATION#", sdkdir);
        csproj_template = csproj_template.Replace("#TEST_ASSEMBLY#", testAssemblyName);
        csproj_template = csproj_template.Replace("#TEST_ASSEMBLY_LOCATION#", testAssemblyFull);

        File.WriteAllText(Path.Combine(outdir_name, testAssemblyName + "-runner.csproj"), csproj_template);

        return(0);
    }
        private void GenerateValidators(ConfigurationSectionModel model, CodeCompileUnit generationUnit)
        {
            bool hasCallback = false;

            foreach (PropertyValidator validator in model.PropertyValidators.Validators)
            {
                if (validator is CallbackValidator)
                {
                    hasCallback = true;
                    break;
                }
            }
            if (hasCallback)
            {
                // Create the namespace block
                CodeNamespace callbackValidatorNamespace = new CodeNamespace(model.Namespace);
                generationUnit.Namespaces.Add(callbackValidatorNamespace);

                foreach (PropertyValidator validator in model.PropertyValidators.Validators)
                {
                    CallbackValidator callbackValidator = validator as CallbackValidator;
                    if (callbackValidator == null)
                    {
                        continue;
                    }

                    string callbackClassName  = string.Format("{0}CallbackValidatorClass", callbackValidator.Name);
                    string callbackMethodName = string.Format("{0}Callback", callbackValidator.Callback);
                    string FQ = string.Format("{0}.{1}", model.Namespace, callbackClassName);

                    CodeTypeDeclaration validationCallbackClass = new CodeTypeDeclaration(callbackClassName);
                    callbackValidatorNamespace.Types.Add(validationCallbackClass);
                    validationCallbackClass.Comments.Add(DocComment("<summary>"));
                    validationCallbackClass.Comments.Add(DocComment(string.Format("Class for the {0} callback validator", callbackValidator.Name)));
                    validationCallbackClass.Comments.Add(DocComment("</summary>"));
                    validationCallbackClass.Attributes = MemberAttributes.Public;
                    validationCallbackClass.IsPartial  = true;
                    validationCallbackClass.IsClass    = true;

                    // Generate callback method
                    CodeMemberMethod callbackCallbackMethod = new CodeMemberMethod();
                    callbackCallbackMethod.Comments.Add(DocComment("<summary>"));
                    callbackCallbackMethod.Comments.Add(DocComment(string.Format("Validation callback for the {0} callback validator", callbackValidator.Name)));
                    callbackCallbackMethod.Comments.Add(DocComment("</summary>"));
                    callbackCallbackMethod.Comments.Add(DocComment("<param name=\"value\">The value to validate.</param>"));
                    callbackCallbackMethod.Comments.Add(DocComment(string.Format("<exception cref=\"{0}\">The value was not valid.</exception>", GetTypeReferenceString(typeof(System.ArgumentException)))));
                    callbackCallbackMethod.CustomAttributes.Add(_generatedCodeAttribute);
                    callbackCallbackMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static | MemberAttributes.Final;
                    callbackCallbackMethod.ReturnType = _void;
                    callbackCallbackMethod.Name       = callbackMethodName;
                    callbackCallbackMethod.Parameters.Add(new CodeParameterDeclarationExpression(_object, "value"));
                    callbackCallbackMethod.Statements.Add(Comment("IMPORTANT NOTE: The code below does not build by default."));
                    callbackCallbackMethod.Statements.Add(Comment("You have placed a callback validator on this property."));
                    callbackCallbackMethod.Statements.Add(Comment("Copy the commented code below to a separate file and "));
                    callbackCallbackMethod.Statements.Add(Comment("implement the method."));
                    callbackCallbackMethod.Statements.Add(Comment(""));

                    // Generate a partial class with a callback method, then put that
                    // generated code into the comments for the callback
                    // method as an instruction to the user on how to handle the callback.
                    {
                        CodeTypeDeclaration partialElementDeclaration = new CodeTypeDeclaration(validationCallbackClass.Name);
                        partialElementDeclaration.Attributes = MemberAttributes.Public;
                        partialElementDeclaration.IsPartial  = true;
                        partialElementDeclaration.IsClass    = true;

                        CodeMemberMethod callbackMethod = new CodeMemberMethod();
                        partialElementDeclaration.Members.Add(callbackMethod);
                        callbackMethod.Attributes = callbackCallbackMethod.Attributes;
                        callbackMethod.ReturnType = _void;
                        callbackMethod.Name       = callbackValidator.Callback;
                        callbackMethod.Parameters.Add(new CodeParameterDeclarationExpression(_object, "value"));

                        // Throw NotImplementedException as per what is normal in generated methods that
                        // are intended to be filled.
                        callbackMethod.Statements.Add(
                            new CodeThrowExceptionStatement(
                                new CodeObjectCreateExpression(
                                    GlobalReference(typeof(NotImplementedException))
                                    )
                                )
                            );

                        // Convert to string and place in comments
                        string generatedCode = CodeTypeDeclarationToString(partialElementDeclaration);
                        foreach (string line in generatedCode.Split(new string[] { "\r\n" }, int.MaxValue, StringSplitOptions.None))
                        {
                            callbackCallbackMethod.Statements.Add(Comment(line));
                        }

                        callbackCallbackMethod.Statements.Add(
                            new CodeMethodInvokeExpression(
                                new CodeTypeReferenceExpression(GlobalSelfReference(FQ)),
                                callbackValidator.Callback,
                                new CodeArgumentReferenceExpression("value")
                                )
                            );
                    }

                    validationCallbackClass.Members.Add(callbackCallbackMethod);
                }
            }
        }
示例#32
0
 public CompilerResults CompileAssemblyFromDom(CompilerParameters options, CodeCompileUnit compilationUnit)
 {
     throw new NotImplementedException();
 }
示例#33
0
        internal static CodeCompileUnit GenerateCodeFromFileBatch(string[] files, WorkflowCompilerParameters parameters, WorkflowCompilerResults results)
        {
            WorkflowCompilationContext context = WorkflowCompilationContext.Current;

            if (context == null)
            {
                throw new Exception(SR.GetString(SR.Error_MissingCompilationContext));
            }

            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();

            foreach (string fileName in files)
            {
                Activity rootActivity = null;
                try
                {
                    DesignerSerializationManager manager = new DesignerSerializationManager(context.ServiceProvider);
                    using (manager.CreateSession())
                    {
                        WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(manager);
                        xomlSerializationManager.WorkflowMarkupStack.Push(parameters);
                        xomlSerializationManager.LocalAssembly = parameters.LocalAssembly;
                        using (XmlReader reader = XmlReader.Create(fileName))
                            rootActivity = WorkflowMarkupSerializationHelpers.LoadXomlDocument(xomlSerializationManager, reader, fileName);

                        if (parameters.LocalAssembly != null)
                        {
                            foreach (object error in manager.Errors)
                            {
                                if (error is WorkflowMarkupSerializationException)
                                {
                                    results.Errors.Add(new WorkflowCompilerError(fileName, (WorkflowMarkupSerializationException)error));
                                }
                                else
                                {
                                    results.Errors.Add(new WorkflowCompilerError(fileName, -1, -1, ErrorNumbers.Error_SerializationError.ToString(CultureInfo.InvariantCulture), error.ToString()));
                                }
                            }
                        }
                    }
                }
                catch (WorkflowMarkupSerializationException xomlSerializationException)
                {
                    results.Errors.Add(new WorkflowCompilerError(fileName, xomlSerializationException));
                    continue;
                }
                catch (Exception e)
                {
                    results.Errors.Add(new WorkflowCompilerError(fileName, -1, -1, ErrorNumbers.Error_SerializationError.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_CompilationFailed, e.Message)));
                    continue;
                }

                if (rootActivity == null)
                {
                    results.Errors.Add(new WorkflowCompilerError(fileName, 1, 1, ErrorNumbers.Error_SerializationError.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_RootActivityTypeInvalid)));
                    continue;
                }

                bool createNewClass = (!string.IsNullOrEmpty(rootActivity.GetValue(WorkflowMarkupSerializer.XClassProperty) as string));
                if (!createNewClass)
                {
                    results.Errors.Add(new WorkflowCompilerError(fileName, 1, 1, ErrorNumbers.Error_SerializationError.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_CannotCompile_No_XClass)));
                    continue;
                }

                //NOTE: CompileWithNoCode is meaningless now. It means no x:Code in a XOML file. It exists until the FP migration is done
                //Ideally FP should just use XOML files w/o X:Class and run them w/o ever compiling them
                if ((parameters.CompileWithNoCode) && XomlCompilerHelper.HasCodeWithin(rootActivity))
                {
                    ValidationError error = new ValidationError(SR.GetString(SR.Error_CodeWithinNotAllowed), ErrorNumbers.Error_CodeWithinNotAllowed);
                    error.UserData[typeof(Activity)] = rootActivity;
                    results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(error, parameters));
                }

                ValidationErrorCollection errors = new ValidationErrorCollection();

                errors = ValidateIdentifiers(context.ServiceProvider, rootActivity);
                foreach (ValidationError error in errors)
                {
                    results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(error, parameters));
                }

                if (results.Errors.HasErrors)
                {
                    continue;
                }

                codeCompileUnit.Namespaces.AddRange(WorkflowMarkupSerializationHelpers.GenerateCodeFromXomlDocument(rootActivity, fileName, context.RootNamespace, CompilerHelpers.GetSupportedLanguage(context.Language), context.ServiceProvider));
            }

            WorkflowMarkupSerializationHelpers.FixStandardNamespacesAndRootNamespace(codeCompileUnit.Namespaces, context.RootNamespace, CompilerHelpers.GetSupportedLanguage(context.Language));
            return(codeCompileUnit);
        }
示例#34
0
        private Assembly GenerateLocalAssembly(string[] files, string[] codeFiles, WorkflowCompilerParameters parameters, WorkflowCompilerResults results, out TempFileCollection tempFiles2, out string localAssemblyPath)
        {
            localAssemblyPath = string.Empty;
            tempFiles2        = null;

            // Generate code for the markup files.
            CodeCompileUnit markupCompileUnit = GenerateCodeFromFileBatch(files, parameters, results);

            if (results.Errors.HasErrors)
            {
                return(null);
            }

            SupportedLanguages language = CompilerHelpers.GetSupportedLanguage(parameters.LanguageToUse);

            // Convert all compile units to source files.
            CodeDomProvider codeDomProvider = CompilerHelpers.GetCodeDomProvider(language, parameters.CompilerVersion);

            // Clone the parameters.
            CompilerParameters clonedParams = XomlCompilerHelper.CloneCompilerParameters(parameters);

            clonedParams.TempFiles.KeepFiles = true;
            tempFiles2 = clonedParams.TempFiles;

            clonedParams.GenerateInMemory = true;

            if (string.IsNullOrEmpty(parameters.OutputAssembly))
            {
                localAssemblyPath = clonedParams.OutputAssembly = clonedParams.TempFiles.AddExtension("dll");
            }
            else
            {
                string tempAssemblyDirectory = clonedParams.TempFiles.BasePath;
                int    postfix = 0;
                while (true)
                {
                    try
                    {
                        Directory.CreateDirectory(tempAssemblyDirectory);
                        break;
                    }
                    catch
                    {
                        tempAssemblyDirectory = clonedParams.TempFiles.BasePath + postfix++;
                    }
                }
                localAssemblyPath = clonedParams.OutputAssembly = tempAssemblyDirectory + "\\" + Path.GetFileName(clonedParams.OutputAssembly);
                clonedParams.TempFiles.AddFile(localAssemblyPath, true);
            }

            // Explictily ignore warnings (in case the user set this property in the project options).
            clonedParams.TreatWarningsAsErrors = false;

            if (clonedParams.CompilerOptions != null && clonedParams.CompilerOptions.Length > 0)
            {
                // Need to remove /delaysign option together with the /keyfile or /keycontainer
                // the temp assembly should not be signed or we'll have problems loading it.

                // Custom splitting: need to take strings like '"one two"' into account
                // even though it has a space inside, it should not be split.

                string    source       = clonedParams.CompilerOptions;
                ArrayList optionsList  = new ArrayList();
                int       begin        = 0;
                int       end          = 0;
                bool      insideString = false;
                while (end < source.Length)
                {
                    int currentLength = end - begin;
                    if (source[end] == '"')
                    {
                        insideString = !insideString;
                    }
                    else if (source[end] == ' ' && !insideString)
                    {
                        // Split only if not inside string like in "inside some string".
                        // Split here. Ignore multiple spaces.
                        if (begin == end)
                        {
                            begin++; // end will get incremented in the end of the loop.
                        }
                        else
                        {
                            string substring = source.Substring(begin, end - begin);
                            optionsList.Add(substring);
                            begin = end + 1; // end will get incremented in the end of the loop
                        }
                    }

                    end++;
                }

                // The remaining sub-string.
                if (begin != end)
                {
                    string substring = source.Substring(begin, end - begin);
                    optionsList.Add(substring);
                }

                string[] options = optionsList.ToArray(typeof(string)) as string[];

                clonedParams.CompilerOptions = string.Empty;
                foreach (string option in options)
                {
                    if (option.Length > 0 &&
                        !option.StartsWith("/delaysign", StringComparison.OrdinalIgnoreCase) &&
                        !option.StartsWith("/keyfile", StringComparison.OrdinalIgnoreCase) &&
                        !option.StartsWith("/keycontainer", StringComparison.OrdinalIgnoreCase))
                    {
                        clonedParams.CompilerOptions += " " + option;
                    }
                }
            }

            // Disable compiler optimizations, but include debug information.
            clonedParams.CompilerOptions         = (clonedParams.CompilerOptions == null) ? "/optimize-" : clonedParams.CompilerOptions + " /optimize-";
            clonedParams.IncludeDebugInformation = true;

            if (language == SupportedLanguages.CSharp)
            {
                clonedParams.CompilerOptions += " /unsafe";
            }

            // Add files.
            ArrayList ccus = new ArrayList((ICollection)parameters.UserCodeCompileUnits);

            ccus.Add(markupCompileUnit);
            ArrayList userCodeFiles = new ArrayList();

            userCodeFiles.AddRange(codeFiles);
            userCodeFiles.AddRange(XomlCompilerHelper.GenerateFiles(codeDomProvider, clonedParams, (CodeCompileUnit[])ccus.ToArray(typeof(CodeCompileUnit))));

            // Generate the temporary assembly.
            CompilerResults results2 = codeDomProvider.CompileAssemblyFromFile(clonedParams, (string[])userCodeFiles.ToArray(typeof(string)));

            if (results2.Errors.HasErrors)
            {
                results.AddCompilerErrorsFromCompilerResults(results2);
                return(null);
            }


            return(results2.CompiledAssembly);
        }
示例#35
0
        internal static string ProcessKernelFile(string filename, string kernelFileContents, bool embedSource = true, string outputPath = null)
        {
            var kernelFilename = Path.GetFileNameWithoutExtension(filename);

            var codeUnit = new CodeCompileUnit();
            var ns       = new CodeNamespace(kernelFilename);

            codeUnit.Namespaces.Add(ns);


            var match2 = _findUsing.Match(kernelFileContents);

            while (match2.Success)
            {
                ns.Imports.Add(new CodeNamespaceImport(match2.Groups[1].Captures[0].Value));
                match2 = match2.NextMatch();
            }

            // Strip comments
            StripComments(ref kernelFileContents);

            // Ensure that kernel signatures do not have line breaks
            StripKernelSignatureLinebreaks(ref kernelFileContents);

            var lines = kernelFileContents.Split(new[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var line in lines)
            {
                var match = _kernelParser.Match(line);
                if (match.Success)
                {
                    var kernelName = match.Groups[KernelName].Value;
                    var kernel     = new CodeTypeDeclaration(kernelName);
                    ns.Types.Add(kernel);
                    ns.Imports.Add(new CodeNamespaceImport("System.IO"));
                    ns.Imports.Add(new CodeNamespaceImport("NOpenCL"));
                    ns.Imports.Add(new CodeNamespaceImport("NOpenCL.Types"));
                    ns.Imports.Add(new CodeNamespaceImport("NOpenCL.Extensions"));
                    ns.Imports.Add(new CodeNamespaceImport("UIntPtr = System.UIntPtr"));
                    ns.Imports.Add(new CodeNamespaceImport("IntPtr = System.IntPtr"));

                    kernel.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                    kernel.BaseTypes.Add(typeof(KernelWrapperBase));

                    var kernelPathProperty = new CodeMemberProperty
                    {
                        Attributes = MemberAttributes.Override | MemberAttributes.Family,
                        Name       = "KernelPath",
                        Type       = new CodeTypeReference(typeof(string), CodeTypeReferenceOptions.GlobalReference),
                        HasGet     = true,
                        HasSet     = false
                    };
                    kernelPathProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(Path)), "Combine",
                                                                                                                      new CodeSnippetExpression("System.AppDomain.CurrentDomain.BaseDirectory"),
                                                                                                                      new CodePrimitiveExpression(outputPath))));
                    kernel.Members.Add(kernelPathProperty);

                    var originalKernelPath = new CodeMemberProperty
                    {
                        Attributes = MemberAttributes.Override | MemberAttributes.Family,
                        Name       = "OriginalKernelPath",
                        Type       = new CodeTypeReference(typeof(string), CodeTypeReferenceOptions.GlobalReference),
                        HasGet     = true,
                        HasSet     = false
                    };
                    originalKernelPath.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(filename)));
                    kernel.Members.Add(originalKernelPath);

                    var kernelSource = new CodeMemberProperty
                    {
                        Attributes = MemberAttributes.Override | MemberAttributes.Family,
                        Name       = "KernelSource",
                        Type       = new CodeTypeReference(typeof(string), CodeTypeReferenceOptions.GlobalReference),
                        HasGet     = true,
                        HasSet     = false
                    };
                    kernelSource.GetStatements.Add(new CodeMethodReturnStatement(
                                                       embedSource ?
                                                       (CodeExpression) new CodePrimitiveExpression(kernelFileContents) :
                                                       new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(Path)), "Combine",
                                                                                      new CodeSnippetExpression("System.AppDomain.CurrentDomain.BaseDirectory"),
                                                                                      new CodePrimitiveExpression(outputPath))));
                    kernel.Members.Add(kernelSource);

                    var kernelNameProperty = new CodeMemberProperty
                    {
                        Attributes = MemberAttributes.Override | MemberAttributes.Family,
                        Name       = "KernelName",
                        Type       = new CodeTypeReference(typeof(string), CodeTypeReferenceOptions.GlobalReference),
                        HasGet     = true,
                        HasSet     = false
                    };
                    kernelNameProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(kernelName)));
                    kernel.Members.Add(kernelNameProperty);

                    var constructor = new CodeConstructor();
                    kernel.Members.Add(constructor);

                    var constructorParams = new CodeParameterDeclarationExpression(typeof(Context), "context");
                    constructor.Parameters.Add(constructorParams);
                    constructor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("context"));
                    constructor.Attributes = MemberAttributes.Public;

                    var executePrivateMethod = new CodeMemberMethod
                    {
                        Name       = "run",
                        Attributes = MemberAttributes.Private | MemberAttributes.Final,
                        ReturnType = new CodeTypeReference(typeof(Event))
                    };
                    var run1D = new CodeMemberMethod
                    {
                        Name       = "Run",
                        Attributes = MemberAttributes.Public | MemberAttributes.Final,
                    };
                    var enqueueRun1D = new CodeMemberMethod
                    {
                        Name       = "EnqueueRun",
                        Attributes = MemberAttributes.Public | MemberAttributes.Final,
                        ReturnType = new CodeTypeReference(typeof(Event))
                    };

                    var run2D = new CodeMemberMethod
                    {
                        Name       = "Run",
                        Attributes = MemberAttributes.Public | MemberAttributes.Final,
                    };
                    var enqueueRun2D = new CodeMemberMethod
                    {
                        Name       = "EnqueueRun",
                        Attributes = MemberAttributes.Public | MemberAttributes.Final,
                        ReturnType = new CodeTypeReference(typeof(Event))
                    };

                    var run3D = new CodeMemberMethod
                    {
                        Name       = "Run",
                        Attributes = MemberAttributes.Public | MemberAttributes.Final,
                    };
                    var enqueueRun3D = new CodeMemberMethod
                    {
                        Name       = "EnqueueRun",
                        Attributes = MemberAttributes.Public | MemberAttributes.Final,
                        ReturnType = new CodeTypeReference(typeof(Event))
                    };

                    var commandQueueParameter = new CodeParameterDeclarationExpression(typeof(CommandQueue), "commandQueue");
                    executePrivateMethod.Parameters.Add(commandQueueParameter);

                    run1D.Parameters.Add(commandQueueParameter);
                    enqueueRun1D.Parameters.Add(commandQueueParameter);

                    run2D.Parameters.Add(commandQueueParameter);
                    enqueueRun2D.Parameters.Add(commandQueueParameter);

                    run3D.Parameters.Add(commandQueueParameter);
                    enqueueRun3D.Parameters.Add(commandQueueParameter);

                    var callPrivateExecute1D = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "run"));
                    var callPrivateExecute2D = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "run"));
                    var callPrivateExecute3D = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "run"));
                    callPrivateExecute1D.Parameters.Add(new CodeArgumentReferenceExpression("commandQueue"));
                    callPrivateExecute2D.Parameters.Add(new CodeArgumentReferenceExpression("commandQueue"));
                    callPrivateExecute3D.Parameters.Add(new CodeArgumentReferenceExpression("commandQueue"));

                    run1D.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(Event)), "ev", callPrivateExecute1D));
                    run1D.Statements.Add(new CodeSnippetExpression("Event.WaitAll(ev)"));
                    enqueueRun1D.Statements.Add(new CodeMethodReturnStatement(callPrivateExecute1D));

                    run2D.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(Event)), "ev", callPrivateExecute2D));
                    run2D.Statements.Add(new CodeSnippetExpression("Event.WaitAll(ev)"));
                    enqueueRun2D.Statements.Add(new CodeMethodReturnStatement(callPrivateExecute2D));

                    run3D.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(Event)), "ev", callPrivateExecute3D));
                    run3D.Statements.Add(new CodeSnippetExpression("Event.WaitAll(ev)"));
                    enqueueRun3D.Statements.Add(new CodeMethodReturnStatement(callPrivateExecute3D));

                    kernel.Members.Add(executePrivateMethod);
                    kernel.Members.Add(run1D);
                    kernel.Members.Add(enqueueRun1D);
                    kernel.Members.Add(run2D);
                    kernel.Members.Add(enqueueRun2D);
                    kernel.Members.Add(run3D);
                    kernel.Members.Add(enqueueRun3D);

                    for (int i = 0; i < match.Groups[Identifier].Captures.Count; i++)
                    {
                        bool isPointer   = !string.IsNullOrEmpty(match.Groups[Pointer].Captures[i].Value);
                        var  rawDatatype = match.Groups[Datatype].Captures[i].Value;
                        var  name        = match.Groups[Identifier].Captures[i].Value;
                        int  vectorWidth = 0;
                        if (match.Groups[VectorWidth].Captures.Count >= 1)
                        {
                            vectorWidth = match.Groups[VectorWidth].Captures[i].Value == string.Empty
                                ? 0
                                : int.Parse(match.Groups[VectorWidth].Captures[i].Value);
                        }
                        var qualifier = match.Groups[Qualifier].Captures[i].Value.Trim();
                        var needs_len = false;

                        CodeParameterDeclarationExpression parameter = null;
                        switch (qualifier)
                        {
                        case "global":
                            parameter = new CodeParameterDeclarationExpression(string.Format("NOpenCL.Buffer", TranslateType(rawDatatype, vectorWidth)), name);
                            break;

                        case "local":
                            name      = name + "_length";
                            parameter = new CodeParameterDeclarationExpression(typeof(int), name);
                            break;

                        case "read_only":
                        case "write_only":
                        case "":
                            needs_len = true;
                            parameter = new CodeParameterDeclarationExpression(TranslateType(rawDatatype, vectorWidth), name);
                            break;
                        }
                        if (parameter != null)
                        {
                            executePrivateMethod.Parameters.Add(parameter);
                            run1D.Parameters.Add(parameter);
                            enqueueRun1D.Parameters.Add(parameter);
                            run2D.Parameters.Add(parameter);
                            enqueueRun2D.Parameters.Add(parameter);
                            run3D.Parameters.Add(parameter);
                            enqueueRun3D.Parameters.Add(parameter);

                            callPrivateExecute1D.Parameters.Add(new CodeArgumentReferenceExpression(name));
                            callPrivateExecute2D.Parameters.Add(new CodeArgumentReferenceExpression(name));
                            callPrivateExecute3D.Parameters.Add(new CodeArgumentReferenceExpression(name));
                        }

                        CodeMethodInvokeExpression setArgument;
                        if (needs_len)
                        {
                            setArgument = new CodeMethodInvokeExpression(
                                new CodeSnippetExpression("this.Kernel.Arguments[" + i.ToString() + "]"), "SetValue",
                                new CodeArgumentReferenceExpression("new UIntPtr((uint)System.Runtime.InteropServices.Marshal.SizeOf(" + name + "))"),
                                new CodeArgumentReferenceExpression("new IntPtr(&" + name + ")"));
                        }
                        else
                        {
                            setArgument = new CodeMethodInvokeExpression(
                                new CodeSnippetExpression("this.Kernel.Arguments[" + i.ToString() + "]"), "SetValue",
                                new CodeArgumentReferenceExpression(name));
                        }
                        executePrivateMethod.Statements.Add(setArgument);
                    }

                    executePrivateMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "globalWorkSize0"));
                    executePrivateMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "globalWorkSize1 = 0"));
                    executePrivateMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "globalWorkSize2 = 0"));

                    executePrivateMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "localWorkSize0 = 0"));
                    executePrivateMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "localWorkSize1 = 0"));
                    executePrivateMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "localWorkSize2 = 0"));

                    var eventWaitListParam = new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(Event[])), "waitFor");
                    eventWaitListParam.CustomAttributes.Add(new CodeAttributeDeclaration("System.ParamArrayAttribute"));
                    executePrivateMethod.Parameters.Add(eventWaitListParam);
                    executePrivateMethod.Statements.Add(new CodeVariableDeclarationStatement(typeof(Event), "ev"));
                    executePrivateMethod.Statements.Add(new CodeAssignStatement(
                                                            new CodeVariableReferenceExpression("ev"),
                                                            // =
                                                            new CodeMethodInvokeExpression(new CodeSnippetExpression("commandQueue"), "EnqueueNDRangeKernel",
                                                                                           new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Kernel"),
                                                                                           new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), "GetWorkSizes",
                                                                                                                          new CodeArgumentReferenceExpression("globalWorkSize0"),
                                                                                                                          new CodeArgumentReferenceExpression("globalWorkSize1"),
                                                                                                                          new CodeArgumentReferenceExpression("globalWorkSize2")),
                                                                                           new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), "GetWorkSizes",
                                                                                                                          new CodeArgumentReferenceExpression("localWorkSize0"),
                                                                                                                          new CodeArgumentReferenceExpression("localWorkSize1"),
                                                                                                                          new CodeArgumentReferenceExpression("localWorkSize2")),
                                                                                           new CodeArgumentReferenceExpression("waitFor"))));
                    executePrivateMethod.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("ev")));

                    run1D.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "globalWorkSize"));
                    enqueueRun1D.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "globalWorkSize"));
                    run1D.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "localWorkSize = 0"));
                    enqueueRun1D.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "localWorkSize = 0"));
                    run1D.Parameters.Add(eventWaitListParam);
                    enqueueRun1D.Parameters.Add(eventWaitListParam);
                    callPrivateExecute1D.Parameters.Add(new CodeArgumentReferenceExpression("globalWorkSize0: globalWorkSize"));
                    callPrivateExecute1D.Parameters.Add(new CodeArgumentReferenceExpression("localWorkSize0: localWorkSize"));
                    callPrivateExecute1D.Parameters.Add(new CodeArgumentReferenceExpression("waitFor: waitFor"));

                    run2D.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "globalWorkSize0"));
                    enqueueRun2D.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "globalWorkSize0"));
                    run2D.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "globalWorkSize1"));
                    enqueueRun2D.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "globalWorkSize1"));
                    run2D.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "localWorkSize0 = 0"));
                    enqueueRun2D.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "localWorkSize0 = 0"));
                    run2D.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "localWorkSize1 = 0"));
                    enqueueRun2D.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "localWorkSize1 = 0"));
                    run2D.Parameters.Add(eventWaitListParam);
                    enqueueRun2D.Parameters.Add(eventWaitListParam);

                    callPrivateExecute2D.Parameters.Add(new CodeArgumentReferenceExpression("globalWorkSize0: globalWorkSize0"));
                    callPrivateExecute2D.Parameters.Add(new CodeArgumentReferenceExpression("globalWorkSize1: globalWorkSize1"));
                    callPrivateExecute2D.Parameters.Add(new CodeArgumentReferenceExpression("localWorkSize0: localWorkSize0"));
                    callPrivateExecute2D.Parameters.Add(new CodeArgumentReferenceExpression("localWorkSize1: localWorkSize1"));
                    callPrivateExecute2D.Parameters.Add(new CodeArgumentReferenceExpression("waitFor: waitFor"));

                    run3D.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "globalWorkSize0"));
                    enqueueRun3D.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "globalWorkSize0"));
                    run3D.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "globalWorkSize1"));
                    enqueueRun3D.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "globalWorkSize1"));
                    run3D.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "globalWorkSize2"));
                    enqueueRun3D.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "globalWorkSize2"));
                    run3D.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "localWorkSize0 = 0"));
                    enqueueRun3D.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "localWorkSize0 = 0"));
                    run3D.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "localWorkSize1 = 0"));
                    enqueueRun3D.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "localWorkSize1 = 0"));
                    run3D.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "localWorkSize2 = 0"));
                    enqueueRun3D.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(uint)), "localWorkSize2 = 0"));
                    run3D.Parameters.Add(eventWaitListParam);
                    enqueueRun3D.Parameters.Add(eventWaitListParam);
                    callPrivateExecute3D.Parameters.Add(new CodeArgumentReferenceExpression("globalWorkSize0: globalWorkSize0"));
                    callPrivateExecute3D.Parameters.Add(new CodeArgumentReferenceExpression("globalWorkSize1: globalWorkSize1"));
                    callPrivateExecute3D.Parameters.Add(new CodeArgumentReferenceExpression("globalWorkSize2: globalWorkSize2"));
                    callPrivateExecute3D.Parameters.Add(new CodeArgumentReferenceExpression("localWorkSize0: localWorkSize0"));
                    callPrivateExecute3D.Parameters.Add(new CodeArgumentReferenceExpression("localWorkSize1: localWorkSize1"));
                    callPrivateExecute3D.Parameters.Add(new CodeArgumentReferenceExpression("localWorkSize2: localWorkSize2"));
                    callPrivateExecute3D.Parameters.Add(new CodeArgumentReferenceExpression("waitFor: waitFor"));
                }
            }

            return(GenerateCSharpCode(codeUnit).Replace("private NOpenCL.Event run(", "private unsafe NOpenCL.Event run("));
        }
示例#36
0
        public void ProviderSupports()
        {
            CodeDomProvider provider = GetProvider();

            CodeCompileUnit cu = new CodeCompileUnit();
            CodeNamespace nspace = new CodeNamespace("NSPC");
            nspace.Imports.Add(new CodeNamespaceImport("System"));
            nspace.Imports.Add(new CodeNamespaceImport("System.Drawing"));
            nspace.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
            nspace.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
            cu.Namespaces.Add(nspace);

            CodeTypeDeclaration cd = new CodeTypeDeclaration("TEST");
            cd.IsClass = true;
            nspace.Types.Add(cd);

            // Arrays of Arrays
            CodeMemberMethod cmm = new CodeMemberMethod();
            cmm.Name = "ArraysOfArrays";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public;
            if (provider.Supports(GeneratorSupport.ArraysOfArrays))
            {
                cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(int[][])),
                    "arrayOfArrays", new CodeArrayCreateExpression(typeof(int[][]),
                    new CodeArrayCreateExpression(typeof(int[]), new CodePrimitiveExpression(3), new CodePrimitiveExpression(4)),
                    new CodeArrayCreateExpression(typeof(int[]), new CodeExpression[] { new CodePrimitiveExpression(1) }))));
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeArrayIndexerExpression(
                    new CodeArrayIndexerExpression(new CodeVariableReferenceExpression("arrayOfArrays"), new CodePrimitiveExpression(0))
                    , new CodePrimitiveExpression(1))));
            }
            else
            {
                throw new Exception("not supported");
            }
            cd.Members.Add(cmm);

            // assembly attributes
            if (provider.Supports(GeneratorSupport.AssemblyAttributes))
            {
                CodeAttributeDeclarationCollection attrs = cu.AssemblyCustomAttributes;
                attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyTitle", new
                    CodeAttributeArgument(new CodePrimitiveExpression("MyAssembly"))));
                attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyVersion", new
                    CodeAttributeArgument(new CodePrimitiveExpression("1.0.6.2"))));
            }

            CodeTypeDeclaration class1 = new CodeTypeDeclaration();
            if (provider.Supports(GeneratorSupport.ChainedConstructorArguments))
            {
                class1.Name = "Test2";
                class1.IsClass = true;
                nspace.Types.Add(class1);

                class1.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(String)), "stringField"));
                CodeMemberProperty prop = new CodeMemberProperty();
                prop.Name = "accessStringField";
                prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                prop.Type = new CodeTypeReference(typeof(String));
                prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
                    "stringField")));
                prop.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new
                    CodeThisReferenceExpression(), "stringField"),
                    new CodePropertySetValueReferenceExpression()));
                class1.Members.Add(prop);

                CodeConstructor cctor = new CodeConstructor();
                cctor.Attributes = MemberAttributes.Public;
                cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression("testingString"));
                cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression(null));
                cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression(null));
                class1.Members.Add(cctor);

                CodeConstructor cc = new CodeConstructor();
                cc.Attributes = MemberAttributes.Public | MemberAttributes.Overloaded;
                cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p1"));
                cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p2"));
                cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p3"));
                cc.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression()
                    , "stringField"), new CodeVariableReferenceExpression("p1")));
                class1.Members.Add(cc);
                // verify chained constructors work
                cmm = new CodeMemberMethod();
                cmm.Name = "ChainedConstructorUse";
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                cmm.ReturnType = new CodeTypeReference(typeof(String));
                // utilize constructor
                cmm.Statements.Add(new CodeVariableDeclarationStatement("Test2", "t", new CodeObjectCreateExpression("Test2")));
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression(
                    new CodeVariableReferenceExpression("t"), "accessStringField")));
                cd.Members.Add(cmm);
            }

            // complex expressions
            if (provider.Supports(GeneratorSupport.ComplexExpressions))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "ComplexExpressions";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public;
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
                cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("i"),
                    new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Multiply,
                    new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add,
                    new CodePrimitiveExpression(3)))));
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("i")));
                cd.Members.Add(cmm);
            }

            if (provider.Supports(GeneratorSupport.DeclareEnums))
            {
                CodeTypeDeclaration ce = new CodeTypeDeclaration("DecimalEnum");
                ce.IsEnum = true;
                nspace.Types.Add(ce);

                // things to enumerate
                for (int k = 0; k < 5; k++)
                {
                    CodeMemberField Field = new CodeMemberField("System.Int32", "Num" + (k).ToString());
                    Field.InitExpression = new CodePrimitiveExpression(k);
                    ce.Members.Add(Field);
                }
                cmm = new CodeMemberMethod();
                cmm.Name = "OutputDecimalEnumVal";
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i");
                cmm.Parameters.Add(param);
                CodeBinaryOperatorExpression eq = new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality,
                    new CodePrimitiveExpression(3));
                CodeMethodReturnStatement truestmt = new CodeMethodReturnStatement(
                    new CodeCastExpression(typeof(int),
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num3")));
                CodeConditionStatement condstmt = new CodeConditionStatement(eq, truestmt);
                cmm.Statements.Add(condstmt);

                eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
                    CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(4));
                truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num4")));
                condstmt = new CodeConditionStatement(eq, truestmt);
                cmm.Statements.Add(condstmt);
                eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
                    CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(2));
                truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num2")));
                condstmt = new CodeConditionStatement(eq, truestmt);
                cmm.Statements.Add(condstmt);

                eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
                    CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(1));
                truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num1")));
                condstmt = new CodeConditionStatement(eq, truestmt);
                cmm.Statements.Add(condstmt);

                eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
                    CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(0));
                truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num0")));
                condstmt = new CodeConditionStatement(eq, truestmt);
                cmm.Statements.Add(condstmt);

                cmm.ReturnType = new CodeTypeReference("System.int32");

                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(10))));
                cd.Members.Add(cmm);
            }

            if (provider.Supports(GeneratorSupport.DeclareInterfaces))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "TestSingleInterface";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i"));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                cmm.Statements.Add(new CodeVariableDeclarationStatement("TestSingleInterfaceImp", "t", new CodeObjectCreateExpression("TestSingleInterfaceImp")));
                CodeMethodInvokeExpression methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t")
                    , "InterfaceMethod");
                methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i"));
                cmm.Statements.Add(new CodeMethodReturnStatement(methodinvoke));
                cd.Members.Add(cmm);

                class1 = new CodeTypeDeclaration("InterfaceA");
                class1.IsInterface = true;
                nspace.Types.Add(class1);
                cmm = new CodeMemberMethod();
                cmm.Attributes = MemberAttributes.Public;
                cmm.Name = "InterfaceMethod";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
                class1.Members.Add(cmm);

                if (provider.Supports(GeneratorSupport.MultipleInterfaceMembers))
                {
                    CodeTypeDeclaration classDecl = new CodeTypeDeclaration("InterfaceB");
                    classDecl.IsInterface = true;
                    nspace.Types.Add(classDecl);
                    cmm = new CodeMemberMethod();
                    cmm.Name = "InterfaceMethod";
                    cmm.Attributes = MemberAttributes.Public;
                    cmm.ReturnType = new CodeTypeReference(typeof(int));
                    cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
                    classDecl.Members.Add(cmm);

                    CodeTypeDeclaration class2 = new CodeTypeDeclaration("TestMultipleInterfaceImp");
                    class2.BaseTypes.Add(new CodeTypeReference("System.Object"));
                    class2.BaseTypes.Add(new CodeTypeReference("InterfaceB"));
                    class2.BaseTypes.Add(new CodeTypeReference("InterfaceA"));
                    class2.IsClass = true;
                    nspace.Types.Add(class2);
                    cmm = new CodeMemberMethod();
                    cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceA"));
                    cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceB"));
                    cmm.Name = "InterfaceMethod";
                    cmm.ReturnType = new CodeTypeReference(typeof(int));
                    cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
                    cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                    cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
                    class2.Members.Add(cmm);

                    cmm = new CodeMemberMethod();
                    cmm.Name = "TestMultipleInterfaces";
                    cmm.ReturnType = new CodeTypeReference(typeof(int));
                    cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i"));
                    cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                    cmm.Statements.Add(new CodeVariableDeclarationStatement("TestMultipleInterfaceImp", "t", new CodeObjectCreateExpression("TestMultipleInterfaceImp")));
                    cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceA", "interfaceAobject", new CodeCastExpression("InterfaceA",
                        new CodeVariableReferenceExpression("t"))));
                    cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceB", "interfaceBobject", new CodeCastExpression("InterfaceB",
                        new CodeVariableReferenceExpression("t"))));
                    methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceAobject")
                        , "InterfaceMethod");
                    methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i"));
                    CodeMethodInvokeExpression methodinvoke2 = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceBobject")
                        , "InterfaceMethod");
                    methodinvoke2.Parameters.Add(new CodeVariableReferenceExpression("i"));
                    cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(
                        methodinvoke,
                        CodeBinaryOperatorType.Subtract, methodinvoke2)));
                    cd.Members.Add(cmm);
                }

                class1 = new CodeTypeDeclaration("TestSingleInterfaceImp");
                class1.BaseTypes.Add(new CodeTypeReference("System.Object"));
                class1.BaseTypes.Add(new CodeTypeReference("InterfaceA"));
                class1.IsClass = true;
                nspace.Types.Add(class1);
                cmm = new CodeMemberMethod();
                cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceA"));
                cmm.Name = "InterfaceMethod";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
                cmm.Attributes = MemberAttributes.Public;
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
                class1.Members.Add(cmm);
            }

            if (provider.Supports(GeneratorSupport.DeclareValueTypes))
            {
                CodeTypeDeclaration structA = new CodeTypeDeclaration("structA");
                structA.IsStruct = true;

                CodeTypeDeclaration structB = new CodeTypeDeclaration("structB");
                structB.Attributes = MemberAttributes.Public;
                structB.IsStruct = true;

                CodeMemberField firstInt = new CodeMemberField(typeof(int), "int1");
                firstInt.Attributes = MemberAttributes.Public;
                structB.Members.Add(firstInt);

                CodeMemberField innerStruct = new CodeMemberField("structB", "innerStruct");
                innerStruct.Attributes = MemberAttributes.Public;

                structA.Members.Add(structB);
                structA.Members.Add(innerStruct);
                nspace.Types.Add(structA);

                CodeMemberMethod nestedStructMethod = new CodeMemberMethod();
                nestedStructMethod.Name = "NestedStructMethod";
                nestedStructMethod.ReturnType = new CodeTypeReference(typeof(int));
                nestedStructMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                CodeVariableDeclarationStatement varStructA = new CodeVariableDeclarationStatement("structA", "varStructA");
                nestedStructMethod.Statements.Add(varStructA);
                nestedStructMethod.Statements.Add
                    (
                    new CodeAssignStatement
                    (
                    /* Expression1 */ new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructA"), "innerStruct"), "int1"),
                    /* Expression1 */ new CodePrimitiveExpression(3)
                    )
                    );
                nestedStructMethod.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructA"), "innerStruct"), "int1")));
                cd.Members.Add(nestedStructMethod);
            }

            if (provider.Supports(GeneratorSupport.EntryPointMethod))
            {
                CodeEntryPointMethod cep = new CodeEntryPointMethod();
                cd.Members.Add(cep);
            }

            // goto statements
            if (provider.Supports(GeneratorSupport.GotoStatements))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "GoToMethod";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i");
                cmm.Parameters.Add(param);
                CodeConditionStatement condstmt = new CodeConditionStatement(new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(1)),
                    new CodeGotoStatement("comehere"));
                cmm.Statements.Add(condstmt);
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(6)));
                cmm.Statements.Add(new CodeLabeledStatement("comehere",
                    new CodeMethodReturnStatement(new CodePrimitiveExpression(7))));
                cd.Members.Add(cmm);
            }

            if (provider.Supports(GeneratorSupport.NestedTypes))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "CallingPublicNestedScenario";
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i"));
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference
                    ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"), "t",
                    new CodeObjectCreateExpression(new CodeTypeReference
                    ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"))));
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"),
                    "publicNestedClassesMethod",
                    new CodeVariableReferenceExpression("i"))));
                cd.Members.Add(cmm);

                class1 = new CodeTypeDeclaration("PublicNestedClassA");
                class1.IsClass = true;
                nspace.Types.Add(class1);
                CodeTypeDeclaration nestedClass = new CodeTypeDeclaration("PublicNestedClassB1");
                nestedClass.IsClass = true;
                nestedClass.TypeAttributes = TypeAttributes.NestedPublic;
                class1.Members.Add(nestedClass);
                nestedClass = new CodeTypeDeclaration("PublicNestedClassB2");
                nestedClass.TypeAttributes = TypeAttributes.NestedPublic;
                nestedClass.IsClass = true;
                class1.Members.Add(nestedClass);
                CodeTypeDeclaration innerNestedClass = new CodeTypeDeclaration("PublicNestedClassC");
                innerNestedClass.TypeAttributes = TypeAttributes.NestedPublic;
                innerNestedClass.IsClass = true;
                nestedClass.Members.Add(innerNestedClass);
                cmm = new CodeMemberMethod();
                cmm.Name = "publicNestedClassesMethod";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
                innerNestedClass.Members.Add(cmm);
            }

            // Parameter Attributes
            if (provider.Supports(GeneratorSupport.ParameterAttributes))
            {
                CodeMemberMethod method1 = new CodeMemberMethod();
                method1.Name = "MyMethod";
                method1.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                CodeParameterDeclarationExpression param1 = new CodeParameterDeclarationExpression(typeof(string), "blah");
                param1.CustomAttributes.Add(
                    new CodeAttributeDeclaration(
                    "System.Xml.Serialization.XmlElementAttribute",
                    new CodeAttributeArgument(
                    "Form",
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
                    new CodeAttributeArgument(
                    "IsNullable",
                    new CodePrimitiveExpression(false))));
                method1.Parameters.Add(param1);
                cd.Members.Add(method1);
            }

            // public static members
            if (provider.Supports(GeneratorSupport.PublicStaticMembers))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "PublicStaticMethod";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(16)));
                cd.Members.Add(cmm);
            }

            // reference parameters
            if (provider.Supports(GeneratorSupport.ReferenceParameters))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "Work";
                cmm.ReturnType = new CodeTypeReference("System.void");
                cmm.Attributes = MemberAttributes.Static;
                // add parameter with ref direction
                CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i");
                param.Direction = FieldDirection.Ref;
                cmm.Parameters.Add(param);
                // add parameter with out direction
                param = new CodeParameterDeclarationExpression(typeof(int), "j");
                param.Direction = FieldDirection.Out;
                cmm.Parameters.Add(param);
                cmm.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("i"),
                    new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression("i"),
                    CodeBinaryOperatorType.Add, new CodePrimitiveExpression(4))));
                cmm.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("j"),
                    new CodePrimitiveExpression(5)));
                cd.Members.Add(cmm);

                cmm = new CodeMemberMethod();
                cmm.Name = "CallingWork";
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                CodeParameterDeclarationExpression parames = new CodeParameterDeclarationExpression(typeof(int), "a");
                cmm.Parameters.Add(parames);
                cmm.ReturnType = new CodeTypeReference("System.int32");
                cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"),
                    new CodePrimitiveExpression(10)));
                cmm.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "b"));
                // invoke the method called "work"
                CodeMethodInvokeExpression methodinvoked = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression
                    (new CodeTypeReferenceExpression("TEST"), "Work"));
                // add parameter with ref direction
                CodeDirectionExpression parameter = new CodeDirectionExpression(FieldDirection.Ref,
                    new CodeVariableReferenceExpression("a"));
                methodinvoked.Parameters.Add(parameter);
                // add parameter with out direction
                parameter = new CodeDirectionExpression(FieldDirection.Out, new CodeVariableReferenceExpression("b"));
                methodinvoked.Parameters.Add(parameter);
                cmm.Statements.Add(methodinvoked);
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression
                    (new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression("b"))));
                cd.Members.Add(cmm);
            }

            if (provider.Supports(GeneratorSupport.ReturnTypeAttributes))
            {
                CodeMemberMethod function1 = new CodeMemberMethod();
                function1.Name = "MyFunction";
                function1.ReturnType = new CodeTypeReference(typeof(string));
                function1.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                function1.ReturnTypeCustomAttributes.Add(new
                    CodeAttributeDeclaration("System.Xml.Serialization.XmlIgnoreAttribute"));
                function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlRootAttribute", new
                    CodeAttributeArgument("Namespace", new CodePrimitiveExpression("Namespace Value")), new
                    CodeAttributeArgument("ElementName", new CodePrimitiveExpression("Root, hehehe"))));
                function1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Return")));
                cd.Members.Add(function1);
            }

            if (provider.Supports(GeneratorSupport.StaticConstructors))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "TestStaticConstructor";
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "a");
                cmm.Parameters.Add(param);
                // utilize constructor
                cmm.Statements.Add(new CodeVariableDeclarationStatement("Test4", "t", new CodeObjectCreateExpression("Test4")));
                // set then get number
                cmm.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("t"), "i")
                    , new CodeVariableReferenceExpression("a")));
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression(
                    new CodeVariableReferenceExpression("t"), "i")));
                cd.Members.Add(cmm);

                class1 = new CodeTypeDeclaration();
                class1.Name = "Test4";
                class1.IsClass = true;
                nspace.Types.Add(class1);

                class1.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(int)), "number"));
                CodeMemberProperty prop = new CodeMemberProperty();
                prop.Name = "i";
                prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                prop.Type = new CodeTypeReference(typeof(int));
                prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("number")));
                prop.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("number"),
                    new CodePropertySetValueReferenceExpression()));
                class1.Members.Add(prop);
                CodeTypeConstructor ctc = new CodeTypeConstructor();
                class1.Members.Add(ctc);
            }

            if (provider.Supports(GeneratorSupport.TryCatchStatements))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "TryCatchMethod";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "a");
                cmm.Parameters.Add(param);

                CodeTryCatchFinallyStatement tcfstmt = new CodeTryCatchFinallyStatement();
                tcfstmt.FinallyStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"), new
                    CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add,
                    new CodePrimitiveExpression(5))));
                cmm.Statements.Add(tcfstmt);
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
                cd.Members.Add(cmm);
            }

            if (provider.Supports(GeneratorSupport.DeclareEvents))
            {
                CodeNamespace ns = new CodeNamespace();
                ns.Name = "MyNamespace";
                ns.Imports.Add(new CodeNamespaceImport("System"));
                ns.Imports.Add(new CodeNamespaceImport("System.Drawing"));
                ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
                ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
                cu.Namespaces.Add(ns);
                class1 = new CodeTypeDeclaration("Test");
                class1.IsClass = true;
                class1.BaseTypes.Add(new CodeTypeReference("Form"));
                ns.Types.Add(class1);

                CodeMemberField mfield = new CodeMemberField(new CodeTypeReference("Button"), "b");
                mfield.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference("Button"));
                class1.Members.Add(mfield);

                CodeConstructor ctor = new CodeConstructor();
                ctor.Attributes = MemberAttributes.Public;
                ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
                    "Size"), new CodeObjectCreateExpression(new CodeTypeReference("Size"),
                    new CodePrimitiveExpression(600), new CodePrimitiveExpression(600))));
                ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
                    "Text"), new CodePrimitiveExpression("Test")));
                ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
                    "TabIndex"), new CodePrimitiveExpression(0)));
                ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
                    "Location"), new CodeObjectCreateExpression(new CodeTypeReference("Point"),
                    new CodePrimitiveExpression(400), new CodePrimitiveExpression(525))));
                ctor.Statements.Add(new CodeAttachEventStatement(new CodeEventReferenceExpression(new
                    CodeThisReferenceExpression(), "MyEvent"), new CodeDelegateCreateExpression(new CodeTypeReference("EventHandler")
                    , new CodeThisReferenceExpression(), "b_Click")));
                class1.Members.Add(ctor);

                CodeMemberEvent evt = new CodeMemberEvent();
                evt.Name = "MyEvent";
                evt.Type = new CodeTypeReference("System.EventHandler");
                evt.Attributes = MemberAttributes.Public;
                class1.Members.Add(evt);

                cmm = new CodeMemberMethod();
                cmm.Name = "b_Click";
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender"));
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(EventArgs), "e"));
                class1.Members.Add(cmm);
            }

            AssertEqual(cu,
                @"'------------------------------------------------------------------------------
                  ' <auto-generated>
                  '     This code was generated by a tool.
                  '     Runtime Version:4.0.30319.42000
                  '
                  '     Changes to this file may cause incorrect behavior and will be lost if
                  '     the code is regenerated.
                  ' </auto-generated>
                  '------------------------------------------------------------------------------

                  Option Strict Off
                  Option Explicit On

                  Imports System
                  Imports System.ComponentModel
                  Imports System.Drawing
                  Imports System.Windows.Forms
                  <Assembly: System.Reflection.AssemblyTitle(""MyAssembly""),  _
                   Assembly: System.Reflection.AssemblyVersion(""1.0.6.2"")>

                  Namespace NSPC

                      Public Class TEST

                          Public Function ArraysOfArrays() As Integer
                              Dim arrayOfArrays()() As Integer = New Integer()() {New Integer() {3, 4}, New Integer() {1}}
                              Return arrayOfArrays(0)(1)
                          End Function

                          Public Shared Function ChainedConstructorUse() As String
                              Dim t As Test2 = New Test2()
                              Return t.accessStringField
                          End Function

                          Public Function ComplexExpressions(ByVal i As Integer) As Integer
                              i = (i  _
                                          * (i + 3))
                              Return i
                          End Function

                          Public Shared Function OutputDecimalEnumVal(ByVal i As Integer) As Integer
                              If (i = 3) Then
                                  Return CType(DecimalEnum.Num3,Integer)
                              End If
                              If (i = 4) Then
                                  Return CType(DecimalEnum.Num4,Integer)
                              End If
                              If (i = 2) Then
                                  Return CType(DecimalEnum.Num2,Integer)
                              End If
                              If (i = 1) Then
                                  Return CType(DecimalEnum.Num1,Integer)
                              End If
                              If (i = 0) Then
                                  Return CType(DecimalEnum.Num0,Integer)
                              End If
                              Return (i + 10)
                          End Function

                          Public Shared Function TestSingleInterface(ByVal i As Integer) As Integer
                              Dim t As TestSingleInterfaceImp = New TestSingleInterfaceImp()
                              Return t.InterfaceMethod(i)
                          End Function

                          Public Shared Function TestMultipleInterfaces(ByVal i As Integer) As Integer
                              Dim t As TestMultipleInterfaceImp = New TestMultipleInterfaceImp()
                              Dim interfaceAobject As InterfaceA = CType(t,InterfaceA)
                              Dim interfaceBobject As InterfaceB = CType(t,InterfaceB)
                              Return (interfaceAobject.InterfaceMethod(i) - interfaceBobject.InterfaceMethod(i))
                          End Function

                          Public Shared Function NestedStructMethod() As Integer
                              Dim varStructA As structA
                              varStructA.innerStruct.int1 = 3
                              Return varStructA.innerStruct.int1
                          End Function

                          Public Shared Sub Main()
                          End Sub

                          Public Function GoToMethod(ByVal i As Integer) As Integer
                              If (i < 1) Then
                                  goto comehere
                              End If
                              Return 6
                          comehere:
                              Return 7
                          End Function

                          Public Shared Function CallingPublicNestedScenario(ByVal i As Integer) As Integer
                              Dim t As PublicNestedClassA.PublicNestedClassB2.PublicNestedClassC = New PublicNestedClassA.PublicNestedClassB2.PublicNestedClassC()
                              Return t.publicNestedClassesMethod(i)
                          End Function

                          Public Sub MyMethod(<System.Xml.Serialization.XmlElementAttribute(Form:=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable:=false)> ByVal blah As String)
                          End Sub

                          Public Shared Function PublicStaticMethod() As Integer
                              Return 16
                          End Function

                          Shared Sub Work(ByRef i As Integer, ByRef j As Integer)
                              i = (i + 4)
                              j = 5
                          End Sub

                          Public Shared Function CallingWork(ByVal a As Integer) As Integer
                              a = 10
                              Dim b As Integer
                              TEST.Work(a, b)
                              Return (a + b)
                          End Function

                          Public Function MyFunction() As <System.Xml.Serialization.XmlIgnoreAttribute(), System.Xml.Serialization.XmlRootAttribute([Namespace]:=""Namespace Value"", ElementName:=""Root, hehehe"")> String
                              Return ""Return""
                          End Function

                          Public Shared Function TestStaticConstructor(ByVal a As Integer) As Integer
                              Dim t As Test4 = New Test4()
                              t.i = a
                              Return t.i
                          End Function

                          Public Shared Function TryCatchMethod(ByVal a As Integer) As Integer
                              Try
                              Finally
                                  a = (a + 5)
                              End Try
                              Return a
                          End Function
                      End Class

                      Public Class Test2

                          Private stringField As String

                          Public Sub New()
                              Me.New(""testingString"", Nothing, Nothing)
                          End Sub

                          Public Sub New(ByVal p1 As String, ByVal p2 As String, ByVal p3 As String)
                              MyBase.New
                              Me.stringField = p1
                          End Sub

                          Public Property accessStringField() As String
                              Get
                                  Return Me.stringField
                              End Get
                              Set
                                  Me.stringField = value
                              End Set
                          End Property
                      End Class

                      Public Enum DecimalEnum

                          Num0 = 0

                          Num1 = 1

                          Num2 = 2

                          Num3 = 3

                          Num4 = 4
                      End Enum

                      Public Interface InterfaceA

                          Function InterfaceMethod(ByVal a As Integer) As Integer
                      End Interface

                      Public Interface InterfaceB

                          Function InterfaceMethod(ByVal a As Integer) As Integer
                      End Interface

                      Public Class TestMultipleInterfaceImp
                          Inherits Object
                          Implements InterfaceB, InterfaceA

                          Public Function InterfaceMethod(ByVal a As Integer) As Integer Implements InterfaceA.InterfaceMethod , InterfaceB.InterfaceMethod
                              Return a
                          End Function
                      End Class

                      Public Class TestSingleInterfaceImp
                          Inherits Object
                          Implements InterfaceA

                          Public Overridable Function InterfaceMethod(ByVal a As Integer) As Integer Implements InterfaceA.InterfaceMethod
                              Return a
                          End Function
                      End Class

                      Public Structure structA

                          Public innerStruct As structB

                          Public Structure structB

                              Public int1 As Integer
                          End Structure
                      End Structure

                      Public Class PublicNestedClassA

                          Public Class PublicNestedClassB1
                          End Class

                          Public Class PublicNestedClassB2

                              Public Class PublicNestedClassC

                                  Public Function publicNestedClassesMethod(ByVal a As Integer) As Integer
                                      Return a
                                  End Function
                              End Class
                          End Class
                      End Class

                      Public Class Test4

                          Private number As Integer

                          Shared Sub New()
                          End Sub

                          Public Property i() As Integer
                              Get
                                  Return number
                              End Get
                              Set
                                  number = value
                              End Set
                          End Property
                      End Class
                  End Namespace

                  Namespace MyNamespace

                      Public Class Test
                          Inherits Form

                          Private b As Button = New Button()

                          Public Sub New()
                              MyBase.New
                              Me.Size = New Size(600, 600)
                              b.Text = ""Test""
                              b.TabIndex = 0
                              b.Location = New Point(400, 525)
                              AddHandler MyEvent, AddressOf Me.b_Click
                          End Sub

                          Public Event MyEvent As System.EventHandler

                          Private Sub b_Click(ByVal sender As Object, ByVal e As System.EventArgs)
                          End Sub
                      End Class
                  End Namespace");
        }
 public virtual void GenerateCodeFromCompileUnit(CodeCompileUnit compileUnit,
         TextWriter writer, CodeGeneratorOptions options)
 {
     ICodeGenerator cg = CreateGenerator();
     if (cg == null)
         throw GetNotImplemented();
     cg.GenerateCodeFromCompileUnit(compileUnit, writer, options);
 }
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {

        CodeNamespace nspace = new CodeNamespace ("NSPC");
        nspace.Imports.Add (new CodeNamespaceImport ("System"));
        cu.Namespaces.Add (nspace);

        CodeTypeDeclaration cd = new CodeTypeDeclaration ("TestingStructs");
        cd.IsClass = true;
        nspace.Types.Add (cd);
        if (Supports (provider, GeneratorSupport.DeclareValueTypes)) {
            // GENERATES (C#):
            //        public int CallingStructMethod(int i) {
            //            StructImplementation o = new StructImplementation ();
            //            return o.StructMethod(i);
            //        }
            AddScenario ("CheckCallingStructMethod");
            CodeMemberMethod cmm = new CodeMemberMethod ();
            cmm.Name = "CallingStructMethod";
            cmm.ReturnType = new CodeTypeReference (typeof (int));
            cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i"));
            cmm.Statements.Add (new CodeVariableDeclarationStatement (new CodeTypeReference ("StructImplementation"), "o", new
                CodeObjectCreateExpression (new CodeTypeReference ("StructImplementation"))));
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodeMethodInvokeExpression (new CodeMethodReferenceExpression (
                new CodeVariableReferenceExpression ("o"),
                "StructMethod"), new CodeArgumentReferenceExpression ("i"))));
            cd.Members.Add (cmm);

            // GENERATES (C#):
            //        public int UsingValueStruct(int i) {
            //            ValueStruct StructObject = new ValueStruct();
            //            StructObject.x = i;
            //            return StructObject.x;
            //        }
            AddScenario ("CheckUsingValueStruct");
            cmm = new CodeMemberMethod ();
            cmm.Name = "UsingValueStruct";
            cmm.ReturnType = new CodeTypeReference (typeof (int));
            cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i"));
            cmm.Statements.Add (new CodeVariableDeclarationStatement ("ValueStruct", "StructObject", new
                CodeObjectCreateExpression ("ValueStruct")));
            cmm.Statements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new CodeVariableReferenceExpression ("StructObject"), "x"),
                new CodeArgumentReferenceExpression ("i")));
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (new
                CodeVariableReferenceExpression ("StructObject"), "x")));
            cd.Members.Add (cmm);

            // GENERATES (C#):
            //        public int UsingStructProperty(int i) {
            //            StructImplementation StructObject = new StructImplementation();
            //            StructObject.UseIField = i;
            //            return StructObject.UseIField;
            //        }
            AddScenario ("CheckUsingStructProperty");
            cmm = new CodeMemberMethod ();
            cmm.Name = "UsingStructProperty";
            cmm.ReturnType = new CodeTypeReference (typeof (int));
            cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i"));
            cmm.Statements.Add (new CodeVariableDeclarationStatement ("StructImplementation", "StructObject", new
                CodeObjectCreateExpression ("StructImplementation")));
            cmm.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (
                new CodeVariableReferenceExpression ("StructObject"), "UseIField"),
                new CodeArgumentReferenceExpression ("i")));
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression (new
                CodeVariableReferenceExpression ("StructObject"), "UseIField")));
            cd.Members.Add (cmm);

            // GENERATES (C#):
            //        public int UsingInterfaceStruct(int i) {
            //            ImplementInterfaceStruct IStructObject = new ImplementInterfaceStruct();
            //            return IStructObject.InterfaceMethod(i);
            //        }
            if (Supports (provider, GeneratorSupport.DeclareInterfaces)) {
                AddScenario ("CheckUsingInterfaceStruct");
                // method to test struct implementing interfaces
                cmm = new CodeMemberMethod ();
                cmm.Name = "UsingInterfaceStruct";
                cmm.ReturnType = new CodeTypeReference (typeof (int));
                cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
                cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i"));
                cmm.Statements.Add (new CodeVariableDeclarationStatement ("ImplementInterfaceStruct", "IStructObject", new
                    CodeObjectCreateExpression ("ImplementInterfaceStruct")));
                cmm.Statements.Add (new CodeMethodReturnStatement (new CodeMethodInvokeExpression (
                    new CodeVariableReferenceExpression ("IStructObject"), "InterfaceMethod",
                    new CodeArgumentReferenceExpression ("i"))));
                cd.Members.Add (cmm);
            }

            // GENERATES (C#):
            //    public struct StructImplementation { 
            //        int i;
            //        public int UseIField {
            //            get {
            //                return i;
            //            }
            //            set {
            //                i = value;
            //            }
            //        }
            //        public int StructMethod(int i) {
            //            return (5 + i);
            //        }
            //    }
            cd = new CodeTypeDeclaration ("StructImplementation");
            cd.IsStruct = true;
            nspace.Types.Add (cd);

            // declare an integer field
            CodeMemberField field = new CodeMemberField (new CodeTypeReference (typeof (int)), "i");
            field.Attributes = MemberAttributes.Public;
            cd.Members.Add (field);

            CodeMemberProperty prop = new CodeMemberProperty ();
            prop.Name = "UseIField";
            prop.Type = new CodeTypeReference (typeof (int));
            prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            CodeFieldReferenceExpression fref = new CodeFieldReferenceExpression ();
            fref.FieldName = "i";
            prop.GetStatements.Add (new CodeMethodReturnStatement (fref));
            prop.SetStatements.Add (new CodeAssignStatement (fref,
                new CodePropertySetValueReferenceExpression ()));

            cd.Members.Add (prop);

            cmm = new CodeMemberMethod ();
            cmm.Name = "StructMethod";
            cmm.ReturnType = new CodeTypeReference (typeof (int));
            cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i"));
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (
                new CodePrimitiveExpression (5), CodeBinaryOperatorType.Add, new CodeArgumentReferenceExpression ("i"))));
            cd.Members.Add (cmm);

            // GENERATES (C#):
            //    public struct ValueStruct {   
            //        public int x;
            //    }
            cd = new CodeTypeDeclaration ("ValueStruct");
            cd.IsStruct = true;
            nspace.Types.Add (cd);

            // declare an integer field
            field = new CodeMemberField (new CodeTypeReference (typeof (int)), "x");
            field.Attributes = MemberAttributes.Public;
            cd.Members.Add (field);

            if (Supports (provider, GeneratorSupport.DeclareInterfaces)) {
                // interface to be implemented    
                // GENERATES (C#):
                //    public interface InterfaceStruct {   
                //        int InterfaceMethod(int i);
                //    }
                cd = new CodeTypeDeclaration ("InterfaceStruct");
                cd.IsInterface = true;
                nspace.Types.Add (cd);

                // method in the interface
                cmm = new CodeMemberMethod ();
                cmm.Name = "InterfaceMethod";
                cmm.ReturnType = new CodeTypeReference (typeof (int));
                cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i"));
                cd.Members.Add (cmm);

                // struct to implement an interface
                // GENERATES (C#):
                //    public struct ImplementInterfaceStruct : InterfaceStruct {
                //        public int InterfaceMethod(int i) {
                //            return (8 + i);
                //        }
                //    }
                cd = new CodeTypeDeclaration ("ImplementInterfaceStruct");
                cd.BaseTypes.Add (new CodeTypeReference ("InterfaceStruct"));
                cd.IsStruct = true;
                nspace.Types.Add (cd);

                field = new CodeMemberField (new CodeTypeReference (typeof (int)), "i");
                field.Attributes = MemberAttributes.Public;
                cd.Members.Add (field);
                // implement interface method
                cmm = new CodeMemberMethod ();
                cmm.Name = "InterfaceMethod";
                cmm.ImplementationTypes.Add (new CodeTypeReference ("InterfaceStruct"));
                cmm.ReturnType = new CodeTypeReference (typeof (int));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new CodePrimitiveExpression (8),
                    CodeBinaryOperatorType.Add,
                    new CodeArgumentReferenceExpression ("i"))));
                cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i"));
                cd.Members.Add (cmm);
            }
        }
    }
示例#39
0
        private static CodeCompileUnit GenerateContextFile(string prefix, string nameSpace, DbSyncScopeDescription desc,
                                                           string serviceUri)
        {
            var contextCC = new CodeCompileUnit();

            var ctxScopeNs = new CodeNamespace(nameSpace);

            // Generate the outer most entity
            var wrapperEntity = new CodeTypeDeclaration(
                string.Format(Constants.ClientContextClassNameFormat,
                              string.IsNullOrEmpty(prefix) ? desc.ScopeName : prefix)
                );

            wrapperEntity.BaseTypes.Add(Constants.ClientContextBaseType);

            #region Generate the GetSchema method

            var getSchemaMethod = new CodeMemberMethod();
            getSchemaMethod.Name       = Constants.ClientIsolatedStoreGetSchemaMethodName;
            getSchemaMethod.Attributes = MemberAttributes.Private | MemberAttributes.Final | MemberAttributes.Static;
            getSchemaMethod.ReturnType = new CodeTypeReference(Constants.ClientSchemaBaseType);

            // Add the line 'IsolatedStoreSchema schema = new IsolatedStoreSchema()'
            var initSchemaStmt = new CodeVariableDeclarationStatement(Constants.ClientSchemaBaseType, "schema");
            initSchemaStmt.InitExpression = new CodeObjectCreateExpression(Constants.ClientSchemaBaseType);
            getSchemaMethod.Statements.Add(initSchemaStmt);

            #endregion

            // Generate the entities
            foreach (var table in desc.Tables)
            {
                var tableName      = CodeDomUtility.SanitizeName(table.UnquotedGlobalName);
                var icollReference = new CodeTypeReference(typeof(IEnumerable <>));

                // Generate the private field
                var entityReference = new CodeTypeReference(tableName);
                icollReference.TypeArguments.Clear();
                icollReference.TypeArguments.Add(entityReference);

                #region Generate the AddXXX method.

                // Define the method signature as 'public void Add[Entity]([Entity] entity)'
                var addMethod = new CodeMemberMethod();
                addMethod.Name = string.Format(Constants.ClientContextAddMethodFormat, tableName);
                addMethod.Parameters.Add(new CodeParameterDeclarationExpression(tableName, "entity"));
                addMethod.ReturnType = new CodeTypeReference(typeof(void));
                addMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;

                //Generate the base.Add method
                var baseAddExpr = new CodeMethodInvokeExpression();
                baseAddExpr.Method = new CodeMethodReferenceExpression();
                baseAddExpr.Method.TargetObject = new CodeBaseReferenceExpression();
                baseAddExpr.Method.MethodName   = Constants.ClientAddMethodBodyFormat;
                baseAddExpr.Method.TypeArguments.Add(tableName);
                baseAddExpr.Parameters.Add(new CodeSnippetExpression(Constants.ClientEntityVariableName));
                addMethod.Statements.Add(baseAddExpr);

                #endregion

                wrapperEntity.Members.Add(addMethod);

                #region Generate the DeleteXXX method.

                // Define the method signature as 'public void Add[Entity]([Entity] entity)'
                var delMethod = new CodeMemberMethod();
                delMethod.Name = string.Format(Constants.ClientContextDeleteMethodFormat, tableName);
                delMethod.Parameters.Add(new CodeParameterDeclarationExpression(tableName,
                                                                                Constants.ClientEntityVariableName));
                delMethod.ReturnType = new CodeTypeReference(typeof(void));
                delMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;

                //Generate the base.Add method
                var baseDelExpr = new CodeMethodInvokeExpression();
                baseDelExpr.Method = new CodeMethodReferenceExpression();
                baseDelExpr.Method.TargetObject = new CodeBaseReferenceExpression();
                baseDelExpr.Method.MethodName   = Constants.ClientDeleteMethodBodyFormat;
                baseDelExpr.Method.TypeArguments.Add(tableName);
                baseDelExpr.Parameters.Add(new CodeSnippetExpression(Constants.ClientEntityVariableName));
                delMethod.Statements.Add(baseDelExpr);

                #endregion

                wrapperEntity.Members.Add(delMethod);

                #region Generate the [Entities] property

                var getCollectionExpr = new CodeMethodInvokeExpression();
                getCollectionExpr.Method = new CodeMethodReferenceExpression();
                getCollectionExpr.Method.TargetObject = new CodeBaseReferenceExpression();
                getCollectionExpr.Method.MethodName   = Constants.ClientGetCollectionMethodBodyFormat;
                getCollectionExpr.Method.TypeArguments.Add(tableName);

                var getProperty = new CodeMemberProperty();
                getProperty.Name       = string.Format(Constants.EntityGetCollectionFormat, tableName);
                getProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                getProperty.Type       = icollReference;
                getProperty.GetStatements.Add(new CodeMethodReturnStatement(getCollectionExpr));

                #endregion

                wrapperEntity.Members.Add(getProperty);

                #region Add this entity to the GetSchema method

                var expr = new CodeMethodInvokeExpression();
                expr.Method = new CodeMethodReferenceExpression();
                expr.Method.TargetObject = new CodeVariableReferenceExpression("schema");
                expr.Method.MethodName   = "AddCollection";
                expr.Method.TypeArguments.Add(tableName);
                getSchemaMethod.Statements.Add(expr);

                #endregion
            }

            #region Add a const for the scopeName and default URL

            var scopeField = new CodeMemberField(typeof(string), "SyncScopeName");
            scopeField.Attributes     = MemberAttributes.Const | MemberAttributes.Private;
            scopeField.InitExpression = new CodePrimitiveExpression(desc.ScopeName);
            wrapperEntity.Members.Add(scopeField);

            if (serviceUri != null)
            {
                var urlField = new CodeMemberField(typeof(Uri), "SyncScopeUri");
                urlField.Attributes     = MemberAttributes.Static | MemberAttributes.Private;
                urlField.InitExpression = new CodeObjectCreateExpression(typeof(Uri),
                                                                         new CodePrimitiveExpression(serviceUri));
                wrapperEntity.Members.Add(urlField);
            }

            #endregion

            #region Add Constructor

            if (serviceUri != null)
            {
                // If serviceUri is present then add constructors with just the cachePath and
                // cachePath with encryption algorithm specified

                // Add the constructor with just the cachepath
                var ctor1 = new CodeConstructor();
                ctor1.Attributes = MemberAttributes.Public;
                ctor1.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string),
                                                                            Constants.ClientCachePathArgName));
                ctor1.ChainedConstructorArgs.Add(new CodeSnippetExpression(Constants.ClientIsolatedStoreCallCtorWithUri));
                wrapperEntity.Members.Add(ctor1);


                // Add the constructor with just cache path and encryption overload
                var eCtor1 = new CodeConstructor();
                eCtor1.Attributes = MemberAttributes.Public;
                eCtor1.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string),
                                                                             Constants.ClientCachePathArgName));
                eCtor1.Parameters.Add(
                    new CodeParameterDeclarationExpression(Type.GetType(Constants.SymmetricAlgorithmTypeName),
                                                           Constants.ClientSymmetricAlgorithmArgName));
                eCtor1.ChainedConstructorArgs.Add(
                    new CodeSnippetExpression(Constants.ClientIsolatedStoreCallEncryptedCtorWithUri));
                wrapperEntity.Members.Add(eCtor1);
            }

            // Add the constructor with no encryption
            var ctor = new CodeConstructor();
            ctor.Attributes = MemberAttributes.Public;
            ctor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), Constants.ClientCachePathArgName));
            ctor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Uri), Constants.ClientServiceUriArgName));
            ctor.BaseConstructorArgs.Add(
                new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(
                        new CodeSnippetExpression(wrapperEntity.Name), Constants.ClientIsolatedStoreGetSchemaMethodName)));
            ctor.BaseConstructorArgs.Add(new CodeSnippetExpression(Constants.ClientIsolatedStoreBaseCtor));
            wrapperEntity.Members.Add(ctor);

            // Add the constructor with encryption overload
            var eCtor = new CodeConstructor();
            eCtor.Attributes = MemberAttributes.Public;
            eCtor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string),
                                                                        Constants.ClientCachePathArgName));
            eCtor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Uri), Constants.ClientServiceUriArgName));
            eCtor.Parameters.Add(
                new CodeParameterDeclarationExpression(Type.GetType(Constants.SymmetricAlgorithmTypeName),
                                                       Constants.ClientSymmetricAlgorithmArgName));
            eCtor.BaseConstructorArgs.Add(
                new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(
                        new CodeSnippetExpression(wrapperEntity.Name), Constants.ClientIsolatedStoreGetSchemaMethodName)));
            eCtor.BaseConstructorArgs.Add(new CodeSnippetExpression(Constants.ClientIsolatedStoreEncryptedBaseCtor));
            wrapperEntity.Members.Add(eCtor);

            #endregion

            getSchemaMethod.Statements.Add(new CodeMethodReturnStatement(new CodeSnippetExpression("schema")));
            wrapperEntity.Members.Add(getSchemaMethod);

            ctxScopeNs.Types.Add(wrapperEntity);
            contextCC.Namespaces.Add(ctxScopeNs);

            return(contextCC);
        }
示例#40
0
        static string GenerateSteticCodeStructure(DotNetProject project, Stetic.ProjectItemInfo item, Stetic.Component component, Stetic.ComponentNameEventArgs args, bool saveToFile, bool overwrite)
        {
            // Generate a class which contains fields for all bound widgets of the component

            string name     = item != null ? item.Name : component.Name;
            string fileName = GetBuildCodeFileName(project, name);

            string ns = "";
            int    i  = name.LastIndexOf('.');

            if (i != -1)
            {
                ns   = name.Substring(0, i);
                name = name.Substring(i + 1);
            }

            if (saveToFile && !overwrite && File.Exists(fileName))
            {
                return(fileName);
            }

            if (item != null)
            {
                component = item.Component;
            }

            CodeCompileUnit cu = new CodeCompileUnit();

            if (project.UsePartialTypes)
            {
                CodeNamespace cns = new CodeNamespace(ns);
                cu.Namespaces.Add(cns);

                CodeTypeDeclaration type = new CodeTypeDeclaration(name);
                type.IsPartial      = true;
                type.Attributes     = MemberAttributes.Public;
                type.TypeAttributes = System.Reflection.TypeAttributes.Public;
                cns.Types.Add(type);

                foreach (Stetic.ObjectBindInfo binfo in component.GetObjectBindInfo())
                {
                    // When a component is being renamed, we have to generate the
                    // corresponding field using the old name, since it will be renamed
                    // later using refactory
                    string nname = args != null && args.NewName == binfo.Name ? args.OldName : binfo.Name;
                    type.Members.Add(
                        new CodeMemberField(
                            binfo.TypeName,
                            nname
                            )
                        );
                }
            }
            else
            {
                if (!saveToFile)
                {
                    return(fileName);
                }
                CodeNamespace cns = new CodeNamespace();
                cns.Comments.Add(new CodeCommentStatement("Generated code for component " + component.Name));
                cu.Namespaces.Add(cns);
            }

            CodeDomProvider provider = project.LanguageBinding.GetCodeDomProvider();

            if (provider == null)
            {
                throw new UserException("Code generation not supported for language: " + project.LanguageName);
            }

            string text;
            var    pol = project.Policies.Get <TextStylePolicy> ();

            using (var fileStream = new StringWriter()) {
                var options = new CodeGeneratorOptions()
                {
                    IndentString             = pol.TabsToSpaces? new string (' ', pol.TabWidth) : "\t",
                    BlankLinesBetweenMembers = true,
                };
                provider.GenerateCodeFromCompileUnit(cu, fileStream, options);
                text = fileStream.ToString();
                text = FormatGeneratedFile(fileName, text, project, provider);
            }

            if (saveToFile)
            {
                File.WriteAllText(fileName, text);
            }
            TypeSystemService.ParseFile(project, fileName);
//
//			if (ProjectDomService.HasDom (project)) {
//				// Only update the parser database if the project is actually loaded in the IDE.
//				ProjectDomService.Parse (project, fileName, text);
//				if (saveToFile)
//					FileService.NotifyFileChanged (fileName);
//			}

            return(fileName);
        }
示例#41
0
 public static void DoSomeCodeDOMStuff()
 {
     CodeCompileUnit cu = new CodeCompileUnit();
 }
示例#42
0
 /// <summary>
 /// Generate code from provided compile unit, outputting on provided code writer
 /// </summary>
 /// <param name="compileUnit"></param>
 /// <param name="codeWriter"></param>
 /// <param name="contextExtras">Items that will be added to context's user data; must be all of different types</param>
 public abstract void Generate(CodeCompileUnit compileUnit, ICodeWriter codeWriter, params object[] contextExtras);
示例#43
0
 private static void GenerateProxy(Action <object, Type> del)
 {
     if (null == del)
     {
         throw new ArgumentNullException("del");
     }
     try
     {
         if (null == HttpContext.Current)
         {
             return;
         }
         var proxy = HttpContext.Current.Cache[CACHE_KEY];
         if (null == proxy)
         {
             var spUrl = HttpContext.Current.Request.QueryString["SPHostUrl"];
             if (string.IsNullOrEmpty(spUrl))
             {
                 spUrl = HttpContext.Current.Request.Form["SPHostUrl"];
             }
             if (string.IsNullOrEmpty(spUrl))
             {
                 return;
             }
             var wsUrl   = string.Format("{0}/_vti_bin/Diagnostics.asmx?wsdl", spUrl);
             var request = (HttpWebRequest)WebRequest.Create(wsUrl);
             request.Credentials = CredentialCache.DefaultCredentials;
             var response = (HttpWebResponse)request.GetResponse();
             using (var stream = response.GetResponseStream())
             {
                 // Get a WSDL file describing a service.
                 var serviceDescription = ServiceDescription.Read(stream);
                 // Initialize a service description importer.
                 var importer = new ServiceDescriptionImporter();
                 importer.ProtocolName = "Soap12";  // Use SOAP 1.2.
                 importer.AddServiceDescription(serviceDescription, null, null);
                 // Report on the service descriptions.
                 Debug.WriteLine("Importing {0} service descriptions with {1} associated schemas.",
                                 importer.ServiceDescriptions.Count, importer.Schemas.Count);
                 // Generate a proxy client.
                 importer.Style = ServiceDescriptionImportStyle.Client;
                 // Generate properties to represent primitive values.
                 importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
                 // Initialize a Code-DOM tree into which we will import the service.
                 var nmspace = new CodeNamespace();
                 var unit1   = new CodeCompileUnit();
                 unit1.Namespaces.Add(nmspace);
                 // Import the service into the Code-DOM tree. This creates proxy code
                 // that uses the service.
                 var warning = importer.Import(nmspace, unit1);
                 if (0 == warning)
                 {
                     // Generate and print the proxy code in C#.
                     var provider1 = CodeDomProvider.CreateProvider("CSharp");
                     // Compile the assembly with the appropriate references
                     string[] assemblyReferences = new string[] { "System.Web.Services.dll", "System.Xml.dll", "System.dll" };
                     var      parms   = new CompilerParameters(assemblyReferences);
                     var      results = provider1.CompileAssemblyFromDom(parms, unit1);
                     foreach (CompilerError oops in results.Errors)
                     {
                         Debug.WriteLine("======== Compiler error ============");
                         Debug.WriteLine(oops.ErrorText);
                     }
                     //Invoke the web service method
                     proxy = results.CompiledAssembly.CreateInstance("SharePointDiagnostics");
                     if (null == proxy)
                     {
                         throw new Exception("Failed to instantiate web service proxy");
                     }
                     // Add proxy to cache.
                     HttpContext.Current.Cache.Insert(CACHE_KEY, proxy, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration);
                 }
                 else
                 {
                     Debug.WriteLine("Warning: " + warning);
                 }
             }
         }
         del(proxy, proxy.GetType());
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex.ToString());
     }
 }
示例#44
0
 /// <summary>
 /// Generate code from provided compile unit, outputting on provided stream writer
 /// </summary>
 /// <param name="compileUnit"></param>
 /// <param name="textWriter"></param>
 /// <param name="contextExtras">Items that will be added to context's user data; must be all of different types</param>
 public void Generate(CodeCompileUnit compileUnit, TextWriter textWriter, params object[] contextExtras)
 {
     Generate(compileUnit, new TextWriterAdapter(textWriter), contextExtras);
 }
示例#45
0
        public void GenerateClasses()
        {
            if (namesp == null)
            {
                namesp = "Schemas";
            }
            if (uri == null)
            {
                uri = "";
            }
            string targetFile = "";

            XmlSchemas schemas = new XmlSchemas();

            foreach (string fileName in schemaNames)
            {
                StreamReader sr = new StreamReader(fileName);
                schemas.Add(XmlSchema.Read(sr, new ValidationEventHandler(HandleValidationError)));
                sr.Close();

                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"));

            // Locate elements to generate

            ArrayList qnames = new ArrayList();

            if (elements.Count > 0)
            {
                foreach (string name in elements)
                {
                    qnames.Add(new XmlQualifiedName(name, uri));
                }
            }
            else
            {
                foreach (XmlSchema schema in schemas)
                {
                    if (!schema.IsCompiled)
                    {
                        schema.Compile(new ValidationEventHandler(HandleValidationError));
                    }
                    foreach (XmlSchemaElement el in schema.Elements.Values)
                    {
                        if (!qnames.Contains(el.QualifiedName))
                        {
                            qnames.Add(el.QualifiedName);
                        }
                    }
                }
            }

            // Import schemas and generate the class model

            XmlSchemaImporter importer = new XmlSchemaImporter(schemas);
            XmlCodeExporter   sx       = new XmlCodeExporter(codeNamespace, cunit);

            ArrayList maps = new ArrayList();

            foreach (XmlQualifiedName qname in qnames)
            {
                XmlTypeMapping tm = importer.ImportTypeMapping(qname);
                if (tm != null)
                {
                    maps.Add(tm);
                }
            }

            foreach (XmlTypeMapping tm in maps)
            {
                sx.ExportTypeMapping(tm);
            }

            // Generate the code

            ICodeGenerator gen = provider.CreateGenerator();

            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);
        }
示例#46
0
        private CompilerResults CompileAssemblyFromDomWithRetry(CompilerParameters options, CodeCompileUnit compilationUnit)
        {
            options.TempFiles.KeepFiles = true;
            CompilerResults    compilerResults = base.CompileAssemblyFromDom(options, compilationUnit);
            TempFileCollection tempFiles       = compilerResults.TempFiles;

            try
            {
                if (compilerResults.Errors.HasErrors)
                {
                    options.TempFiles = new TempFileCollection();
                    return(RetryCompile(options, compilerResults.Errors) ?? compilerResults);
                }
                return(compilerResults);
            }
            finally
            {
                foreach (object item in tempFiles)
                {
                    string text = item as string;
                    if (text != null)
                    {
                        try
                        {
                            File.Delete(text);
                        }
                        catch
                        {
                        }
                    }
                }
            }
        }
        static void GenerateXObjects(
            XmlSchemaSet set, string csFileName, string configFileName, string assemblyName, bool xmlSerializable, bool nameMangler2)
        {
            LinqToXsdSettings configSettings = new LinqToXsdSettings(nameMangler2);

            if (configFileName != null)
            {
                configSettings.Load(configFileName);
            }
            configSettings.EnableServiceReference = xmlSerializable;
            XsdToTypesConverter xsdConverter = new XsdToTypesConverter(configSettings);
            ClrMappingInfo      mapping      = xsdConverter.GenerateMapping(set);

            CodeDomTypesGenerator codeGenerator = new CodeDomTypesGenerator(configSettings);
            CodeCompileUnit       ccu           = new CodeCompileUnit();

            //   if (mapping != null)                            //DC
            foreach (CodeNamespace codeNs in codeGenerator.GenerateTypes(mapping))
            {
                ccu.Namespaces.Add(codeNs);
            }
            //Write to file
            CSharpCodeProvider provider = new CSharpCodeProvider();

            if (csFileName != string.Empty)
            {
                /*
                 * StreamWriter sw = new StreamWriter(csFileName);
                 * provider.GenerateCodeFromCompileUnit(ccu, sw, new CodeGeneratorOptions());
                 * sw.Flush();
                 * sw.Close();
                 * */
                using (var update =
                           new Update(csFileName, System.Text.Encoding.UTF8))
                {
                    provider.GenerateCodeFromCompileUnit(
                        ccu, update.Writer, new CodeGeneratorOptions());
                }
                PrintMessage(csFileName);
            }
            if (assemblyName != string.Empty)
            {
                CompilerParameters options = new CompilerParameters();
                options.OutputAssembly          = assemblyName;
                options.IncludeDebugInformation = true;
                options.TreatWarningsAsErrors   = true;
                options.ReferencedAssemblies.Add("System.dll");
                options.ReferencedAssemblies.Add("System.Core.dll");
                options.ReferencedAssemblies.Add("System.Xml.dll");
                options.ReferencedAssemblies.Add("System.Xml.Linq.dll");
                options.ReferencedAssemblies.Add("O2_Misc_Microsoft_MPL_Libs.dll");
                CompilerResults results = provider.CompileAssemblyFromDom(options, ccu);
                if (results.Errors.Count > 0)
                {
                    PrintErrorMessage("compilation error(s): ");
                    for (int i = 0; i < results.Errors.Count; i++)
                    {
                        PrintErrorMessage(results.Errors[i].ToString());
                    }
                }
                else
                {
                    PrintMessage("Generated Assembly: " + results.CompiledAssembly.ToString());
                }
            }
            ;
        }
示例#48
0
        public virtual List <ExplorerItem> BuildAssembly(IConnectionInfo cxInfo, AssemblyName assemblyToBuild, ref string nameSpace, ref string typeName)
        {
            var unit       = new CodeCompileUnit();
            var namespace2 = new CodeNamespace(nameSpace);

            namespace2.Imports.Add(new CodeNamespaceImport("System"));
            namespace2.Imports.Add(new CodeNamespaceImport("System.Linq"));
            namespace2.Imports.Add(new CodeNamespaceImport("Sitecore.ContentSearch"));
            namespace2.Imports.Add(new CodeNamespaceImport("Sitecore.ContentSearch.SearchTypes"));

            var settings = new SitecoreConnectionSettings();
            var mapper   = new DriverDataCxSettingsMapper();

            mapper.Read(cxInfo, settings);

            var selectedType = settings.SearchResultType.GetSelectedType();

            namespace2.Imports.Add(new CodeNamespaceImport(selectedType.Namespace));
            var declaration = new CodeTypeDeclaration(typeName)
            {
                IsClass        = true,
                TypeAttributes = TypeAttributes.Public
            };

            namespace2.Types.Add(declaration);
            unit.Namespaces.Add(namespace2);
            var constructor = new CodeConstructor
            {
                Attributes = MemberAttributes.Public
            };

            this.AddConstructorCode(constructor, settings);
            declaration.Members.Add(constructor);
            var indexNames = this.GetIndexNames(cxInfo);
            var list       = new List <ExplorerItem>();

            foreach (var str in indexNames)
            {
                this.AddIndexAsProperty(str, selectedType, declaration);
                var item = new ExplorerItem(str, ExplorerItemKind.QueryableObject, ExplorerIcon.Table)
                {
                    IsEnumerable = false
                };
                item.DragText = this.GetDragText(item, settings);
                list.Add(item);
            }
            var provider = new CSharpCodeProvider();
            var options  = new CompilerParameters();
            var assemblyFilesToReference = this.GetAssemblyFilesToReference(settings);

            foreach (var str2 in assemblyFilesToReference)
            {
                options.ReferencedAssemblies.Add(str2);
            }
            options.GenerateInMemory = true;
            options.OutputAssembly   = assemblyToBuild.CodeBase;
            var results = provider.CompileAssemblyFromDom(options, new CodeCompileUnit[] { unit });

            if (results.Errors.Count > 0)
            {
                throw new Exception(string.Concat(new object[] { "Cannot compile typed context: ", results.Errors[0].ErrorText, " (line ", results.Errors[0].Line, ")" }));
            }
            return(list);
        }
        private void WriteFile(string file, CodeTypeDeclaration resources, string language, bool isFSharp, bool isCSharp)
        {
            CodeDomProvider provider =
                isFSharp ? new FSharp.Compiler.CodeDom.FSharpCodeProvider() :
                CodeDomProvider.CreateProvider(language);

            string code = null;

            using (var o = new StringWriter()) {
                var options = new CodeGeneratorOptions()
                {
                    BracingStyle = "C",
                    IndentString = "\t",
                };

                var ns = string.IsNullOrEmpty(Namespace)
                                        ? new CodeNamespace()
                                        : new CodeNamespace(Namespace);

                if (resources != null)
                {
                    ns.Types.Add(resources);
                }

                var unit = new CodeCompileUnit();
                unit.Namespaces.Add(ns);

                var resgenatt = new CodeAttributeDeclaration(new CodeTypeReference("Android.Runtime.ResourceDesignerAttribute", CodeTypeReferenceOptions.GlobalReference));
                resgenatt.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(Namespace.Length > 0 ? Namespace + ".Resource" : "Resource")));
                resgenatt.Arguments.Add(new CodeAttributeArgument("IsApplication", new CodePrimitiveExpression(IsApplication)));
                unit.AssemblyCustomAttributes.Add(resgenatt);

                // Add Pragma to disable warnings about no Xml documentation
                if (isCSharp)
                {
                    provider.GenerateCodeFromCompileUnit(new CodeSnippetCompileUnit("#pragma warning disable 1591"), o, options);
                }

                provider.CreateGenerator(o).GenerateCodeFromCompileUnit(unit, o, options);

                // Add Pragma to re-enable warnings about no Xml documentation
                if (isCSharp)
                {
                    provider.GenerateCodeFromCompileUnit(new CodeSnippetCompileUnit("#pragma warning restore 1591"), o, options);
                }

                code = o.ToString();

                // post-processing for F#
                if (isFSharp)
                {
                    code = code.Replace("\r\n", "\n");
                    while (true)
                    {
                        int skipLen = " = class".Length;
                        int idx     = code.IndexOf(" = class");
                        if (idx < 0)
                        {
                            break;
                        }
                        int    end  = code.IndexOf("        end");
                        string head = code.Substring(0, idx);
                        string mid  = end < 0 ? code.Substring(idx) : code.Substring(idx + skipLen, end - idx - skipLen);
                        string last = end < 0 ? null : code.Substring(end + "        end".Length);
                        code = head + @" () =
            static do Android.Runtime.ResourceIdManager.UpdateIdValues()" + mid + "\n" + last;
                    }
                }
            }

            var temp_o = Path.Combine(Path.GetDirectoryName(file), "__" + Path.GetFileName(file) + ".new");

            using (TextWriter o = File.CreateText(temp_o))
                o.Write(code);
            MonoAndroidHelper.CopyIfChanged(temp_o, file);
            try { File.Delete(temp_o); } catch (Exception) { }
        }
示例#50
0
        internal static void GenerateCode(string rootType, string rootNs, CodeTypeReference baseType,
                                          IDictionary <string, CodeTypeReference> namesAndTypes, string xamlFile, string outFile)
        {
            if (rootType == null)
            {
                File.WriteAllText(outFile, "");
                return;
            }

            var ccu    = new CodeCompileUnit();
            var declNs = new CodeNamespace(rootNs);

            ccu.Namespaces.Add(declNs);

            var declType = new CodeTypeDeclaration(rootType)
            {
                IsPartial        = true,
                CustomAttributes =
                {
                    new CodeAttributeDeclaration(new CodeTypeReference($"global::{typeof(XamlFilePathAttribute).FullName}"),
                                                 new CodeAttributeArgument(new CodePrimitiveExpression(xamlFile)))
                }
            };

            declType.BaseTypes.Add(baseType);

            declNs.Types.Add(declType);

            var initcomp = new CodeMemberMethod {
                Name             = "InitializeComponent",
                CustomAttributes = { GeneratedCodeAttrDecl }
            };

            declType.Members.Add(initcomp);

            initcomp.Statements.Add(new CodeMethodInvokeExpression(
                                        new CodeTypeReferenceExpression(new CodeTypeReference($"global::{typeof(Extensions).FullName}")),
                                        "LoadFromXaml", new CodeThisReferenceExpression(), new CodeTypeOfExpression(declType.Name)));

            foreach (var entry in namesAndTypes)
            {
                string name = entry.Key;
                var    type = entry.Value;

                var field = new CodeMemberField
                {
                    Name             = name,
                    Type             = type,
                    CustomAttributes = { GeneratedCodeAttrDecl }
                };

                declType.Members.Add(field);

                var find_invoke = new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(
                        new CodeTypeReferenceExpression(new CodeTypeReference($"global::{typeof(NameScopeExtensions).FullName}")),
                        "FindByName", type),
                    new CodeThisReferenceExpression(), new CodePrimitiveExpression(name));

                CodeAssignStatement assign = new CodeAssignStatement(
                    new CodeVariableReferenceExpression(name), find_invoke);

                initcomp.Statements.Add(assign);
            }

            using (var writer = new StreamWriter(outFile))
                Provider.GenerateCodeFromCompileUnit(ccu, writer, new CodeGeneratorOptions());
        }
示例#51
0
    void GenerateCode()
    {
        Directory.CreateDirectory (OutputDir);

        Provider = new CSharpCodeProvider ();
        CodeGenOptions = new CodeGeneratorOptions { BlankLinesBetweenMembers = false };

        CodeTypeDeclaration libDecl = null;

        // Generate Libs class
        {
            var cu = new CodeCompileUnit ();
            var ns = new CodeNamespace (Namespace);
            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("Mono.VisualC.Interop"));
            cu.Namespaces.Add (ns);

            var decl = new CodeTypeDeclaration ("Libs");

            var field = new CodeMemberField (new CodeTypeReference ("CppLibrary"), LibBaseName);
            field.Attributes = MemberAttributes.Public|MemberAttributes.Static;
            field.InitExpression = new CodeObjectCreateExpression (new CodeTypeReference ("CppLibrary"), new CodeExpression [] { new CodePrimitiveExpression (LibBaseName) });
            decl.Members.Add (field);

            ns.Types.Add (decl);

            libDecl = decl;

            //Provider.GenerateCodeFromCompileUnit(cu, Console.Out, CodeGenOptions);
            using (TextWriter w = File.CreateText (Path.Combine (OutputDir, "Libs.cs"))) {
                Provider.GenerateCodeFromCompileUnit(cu, w, CodeGenOptions);
            }
        }

        // Generate user classes
        foreach (Class klass in Classes) {
            if (klass.Disable)
                continue;

            var cu = new CodeCompileUnit ();
            var ns = new CodeNamespace (Namespace);
            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("Mono.VisualC.Interop"));
            cu.Namespaces.Add (ns);

            ns.Types.Add (klass.GenerateClass (this, libDecl, LibBaseName));

            //Provider.GenerateCodeFromCompileUnit(cu, Console.Out, CodeGenOptions);
            using (TextWriter w = File.CreateText (Path.Combine (OutputDir, klass.Name + ".cs"))) {
                // These are reported for the fields of the native layout structures
                Provider.GenerateCodeFromCompileUnit (new CodeSnippetCompileUnit("#pragma warning disable 0414, 0169"), w, CodeGenOptions);
                Provider.GenerateCodeFromCompileUnit(cu, w, CodeGenOptions);
            }
        }
    }
示例#52
0
 /// <include file='doc\XmlCodeExporter.uex' path='docs/doc[@for="XmlCodeExporter.XmlCodeExporter1"]/*' />
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 public XmlCodeExporter(CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit) : base(codeNamespace, codeCompileUnit, null, CodeGenerationOptions.GenerateProperties, null)
 {
 }
示例#53
0
        public void RegionsSnippetsAndLinePragmas()
        {
            CodeCompileUnit cu = new CodeCompileUnit();
            CodeNamespace ns = new CodeNamespace("Namespace1");

            cu.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Compile Unit Region"));
            cu.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            cu.Namespaces.Add(ns);

            CodeTypeDeclaration cd = new CodeTypeDeclaration("Class1");
            ns.Types.Add(cd);

            cd.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Outer Type Region"));
            cd.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            cd.Comments.Add(new CodeCommentStatement("Outer Type Comment"));

            CodeMemberField field1 = new CodeMemberField(typeof(String), "field1");
            CodeMemberField field2 = new CodeMemberField(typeof(String), "field2");
            field1.Comments.Add(new CodeCommentStatement("Field 1 Comment"));
            field2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Field Region"));
            field2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            CodeMemberEvent evt1 = new CodeMemberEvent();
            evt1.Name = "Event1";
            evt1.Type = new CodeTypeReference(typeof(System.EventHandler));
            evt1.Attributes = (evt1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;

            CodeMemberEvent evt2 = new CodeMemberEvent();
            evt2.Name = "Event2";
            evt2.Type = new CodeTypeReference(typeof(System.EventHandler));
            evt2.Attributes = (evt2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;

            evt2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Event Region"));
            evt2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            CodeMemberMethod method1 = new CodeMemberMethod();
            method1.Name = "Method1";
            method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            method1.Statements.Add(
                new CodeDelegateInvokeExpression(
                    new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "Event1"),
                    new CodeExpression[] {
                        new CodeThisReferenceExpression(),
                        new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.EventArgs"), "Empty")
                    }));

            CodeMemberMethod method2 = new CodeMemberMethod();
            method2.Name = "Method2";
            method2.Attributes = (method2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            method2.Statements.Add(
                new CodeDelegateInvokeExpression(
                    new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "Event2"),
                    new CodeExpression[] {
                    new CodeThisReferenceExpression(),
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.EventArgs"), "Empty")
                    }));
            method2.LinePragma = new CodeLinePragma("MethodLinePragma.txt", 500);
            method2.Comments.Add(new CodeCommentStatement("Method 2 Comment"));

            method2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Method Region"));
            method2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            CodeMemberProperty property1 = new CodeMemberProperty();
            property1.Name = "Property1";
            property1.Type = new CodeTypeReference(typeof(string));
            property1.Attributes = (property1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            property1.GetStatements.Add(
                new CodeMethodReturnStatement(
                    new CodeFieldReferenceExpression(
                        new CodeThisReferenceExpression(),
                        "field1")));

            CodeMemberProperty property2 = new CodeMemberProperty();
            property2.Name = "Property2";
            property2.Type = new CodeTypeReference(typeof(string));
            property2.Attributes = (property2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            property2.GetStatements.Add(
                new CodeMethodReturnStatement(
                    new CodeFieldReferenceExpression(
                        new CodeThisReferenceExpression(),
                        "field2")));

            property2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Property Region"));
            property2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            CodeConstructor constructor1 = new CodeConstructor();
            constructor1.Attributes = (constructor1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            CodeStatement conState1 = new CodeAssignStatement(
                                        new CodeFieldReferenceExpression(
                                            new CodeThisReferenceExpression(),
                                            "field1"),
                                        new CodePrimitiveExpression("value1"));
            conState1.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Statements Region"));
            constructor1.Statements.Add(conState1);
            CodeStatement conState2 = new CodeAssignStatement(
                                        new CodeFieldReferenceExpression(
                                            new CodeThisReferenceExpression(),
                                            "field2"),
                                        new CodePrimitiveExpression("value2"));
            conState2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
            constructor1.Statements.Add(conState2);

            constructor1.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Constructor Region"));
            constructor1.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            CodeConstructor constructor2 = new CodeConstructor();
            constructor2.Attributes = (constructor2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            constructor2.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "value1"));
            constructor2.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "value2"));

            CodeTypeConstructor typeConstructor2 = new CodeTypeConstructor();

            typeConstructor2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Type Constructor Region"));
            typeConstructor2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            CodeEntryPointMethod methodMain = new CodeEntryPointMethod();

            CodeTypeDeclaration nestedClass1 = new CodeTypeDeclaration("NestedClass1");
            CodeTypeDeclaration nestedClass2 = new CodeTypeDeclaration("NestedClass2");
            nestedClass2.LinePragma = new CodeLinePragma("NestedTypeLinePragma.txt", 400);
            nestedClass2.Comments.Add(new CodeCommentStatement("Nested Type Comment"));

            nestedClass2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Nested Type Region"));
            nestedClass2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            CodeTypeDelegate delegate1 = new CodeTypeDelegate();
            delegate1.Name = "nestedDelegate1";
            delegate1.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.Object"), "sender"));
            delegate1.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.EventArgs"), "e"));

            CodeTypeDelegate delegate2 = new CodeTypeDelegate();
            delegate2.Name = "nestedDelegate2";
            delegate2.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.Object"), "sender"));
            delegate2.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.EventArgs"), "e"));

            delegate2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Delegate Region"));
            delegate2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            var snippet1 = new CodeSnippetTypeMember();
            var snippet2 = new CodeSnippetTypeMember();

            CodeRegionDirective regionStart = new CodeRegionDirective(CodeRegionMode.End, "");
            regionStart.RegionText = "Snippet Region";
            regionStart.RegionMode = CodeRegionMode.Start;
            snippet2.StartDirectives.Add(regionStart);
            snippet2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            cd.Members.Add(field1);
            cd.Members.Add(method1);
            cd.Members.Add(constructor1);
            cd.Members.Add(property1);
            cd.Members.Add(methodMain);

            cd.Members.Add(evt1);
            cd.Members.Add(nestedClass1);
            cd.Members.Add(delegate1);

            cd.Members.Add(snippet1);

            cd.Members.Add(field2);
            cd.Members.Add(method2);
            cd.Members.Add(constructor2);
            cd.Members.Add(property2);

            cd.Members.Add(typeConstructor2);
            cd.Members.Add(evt2);
            cd.Members.Add(nestedClass2);
            cd.Members.Add(delegate2);
            cd.Members.Add(snippet2);

            AssertEqual(cu,
                @"#Region ""Compile Unit Region""
                  '------------------------------------------------------------------------------
                  ' <auto-generated>
                  '     This code was generated by a tool.
                  '     Runtime Version:4.0.30319.42000
                  '
                  '     Changes to this file may cause incorrect behavior and will be lost if
                  '     the code is regenerated.
                  ' </auto-generated>
                  '------------------------------------------------------------------------------
                  Option Strict Off
                  Option Explicit On
                  Namespace Namespace1
                      #Region ""Outer Type Region""
                      'Outer Type Comment
                      Public Class Class1
                          'Field 1 Comment
                          Private field1 As String
                          #Region ""Field Region""
                          Private field2 As String
                          #End Region
                          #Region ""Snippet Region""
                          #End Region
                          #Region ""Type Constructor Region""
                          Shared Sub New()
                          End Sub
                          #End Region
                          #Region ""Constructor Region""
                          Public Sub New()
                              MyBase.New
                              Me.field1 = ""value1""
                              Me.field2 = ""value2""
                          End Sub
                          #End Region
                          Public Sub New(ByVal value1 As String, ByVal value2 As String)
                              MyBase.New
                          End Sub
                          Public ReadOnly Property Property1() As String
                              Get
                                  Return Me.field1
                              End Get
                          End Property
                          #Region ""Property Region""
                          Public ReadOnly Property Property2() As String
                              Get
                                  Return Me.field2
                              End Get
                          End Property
                          #End Region
                          Public Event Event1 As System.EventHandler
                          #Region ""Event Region""
                          Public Event Event2 As System.EventHandler
                          #End Region
                          Public Sub Method1()
                              RaiseEvent Event1(Me, System.EventArgs.Empty)
                          End Sub
                          Public Shared Sub Main()
                          End Sub
                          #Region ""Method Region""
                          'Method 2 Comment
                          #ExternalSource(""MethodLinePragma.txt"",500)
                          Public Sub Method2()
                              RaiseEvent Event2(Me, System.EventArgs.Empty)
                          End Sub
                          #End ExternalSource
                          #End Region
                          Public Class NestedClass1
                          End Class
                          Public Delegate Sub nestedDelegate1(ByVal sender As Object, ByVal e As System.EventArgs)
                          #Region ""Nested Type Region""
                          'Nested Type Comment
                          #ExternalSource(""NestedTypeLinePragma.txt"",400)
                          Public Class NestedClass2
                          End Class
                          #End ExternalSource
                          #End Region
                          #Region ""Delegate Region""
                          Public Delegate Sub nestedDelegate2(ByVal sender As Object, ByVal e As System.EventArgs)
                          #End Region
                      End Class
                      #End Region
                  End Namespace
                  #End Region");
        }
示例#54
0
 /// <include file='doc\XmlCodeExporter.uex' path='docs/doc[@for="XmlCodeExporter.XmlCodeExporter2"]/*' />
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 public XmlCodeExporter(CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit, CodeGenerationOptions options)
     : base(codeNamespace, codeCompileUnit, null, options, null)
 {
 }
示例#55
0
        public void MetadataAttributes()
        {
            var cu = new CodeCompileUnit();

            var ns = new CodeNamespace();
            ns.Name = "MyNamespace";
            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("System.Drawing"));
            ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
            ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
            cu.Namespaces.Add(ns);

            var attrs = cu.AssemblyCustomAttributes;
            attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyTitle", new CodeAttributeArgument(new CodePrimitiveExpression("MyAssembly"))));
            attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyVersion", new CodeAttributeArgument(new CodePrimitiveExpression("1.0.6.2"))));
            attrs.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false))));

            var class1 = new CodeTypeDeclaration() { Name = "MyClass" };
            class1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable"));
            class1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Class"))));
            ns.Types.Add(class1);

            var nestedClass = new CodeTypeDeclaration("NestedClass") { IsClass = true, TypeAttributes = TypeAttributes.NestedPublic };
            nestedClass.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable"));
            class1.Members.Add(nestedClass);

            var method1 = new CodeMemberMethod() { Name = "MyMethod" };
            method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Method"))));
            method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.ComponentModel.Editor", new CodeAttributeArgument(new CodePrimitiveExpression("This")), new CodeAttributeArgument(new CodePrimitiveExpression("That"))));
            var param1 = new CodeParameterDeclarationExpression(typeof(string), "blah");
            param1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute",
                            new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
                            new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(false))));
            method1.Parameters.Add(param1);
            var param2 = new CodeParameterDeclarationExpression(typeof(int[]), "arrayit");
            param2.CustomAttributes.Add(
                        new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute",
                            new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
                            new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(false))));
            method1.Parameters.Add(param2);
            class1.Members.Add(method1);

            var function1 = new CodeMemberMethod();
            function1.Name = "MyFunction";
            function1.ReturnType = new CodeTypeReference(typeof(string));
            function1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function"))));
            function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlIgnoreAttribute"));
            function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlRootAttribute", new
                CodeAttributeArgument("Namespace", new CodePrimitiveExpression("Namespace Value")), new
                CodeAttributeArgument("ElementName", new CodePrimitiveExpression("Root, hehehe"))));
            function1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Return")));
            class1.Members.Add(function1);

            CodeMemberMethod function2 = new CodeMemberMethod();
            function2.Name = "GlobalKeywordFunction";
            function2.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(ObsoleteAttribute), CodeTypeReferenceOptions.GlobalReference), new
                CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function"))));
            CodeTypeReference typeRef = new CodeTypeReference("System.Xml.Serialization.XmlIgnoreAttribute", CodeTypeReferenceOptions.GlobalReference);
            CodeAttributeDeclaration codeAttrib = new CodeAttributeDeclaration(typeRef);
            function2.ReturnTypeCustomAttributes.Add(codeAttrib);
            class1.Members.Add(function2);

            CodeMemberField field1 = new CodeMemberField();
            field1.Name = "myField";
            field1.Type = new CodeTypeReference(typeof(string));
            field1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute"));
            field1.InitExpression = new CodePrimitiveExpression("hi!");
            class1.Members.Add(field1);

            CodeMemberProperty prop1 = new CodeMemberProperty();
            prop1.Name = "MyProperty";
            prop1.Type = new CodeTypeReference(typeof(string));
            prop1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Property"))));
            prop1.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "myField")));
            class1.Members.Add(prop1);

            CodeConstructor const1 = new CodeConstructor();
            const1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Constructor"))));
            class1.Members.Add(const1);

            class1 = new CodeTypeDeclaration("Test");
            class1.IsClass = true;
            class1.BaseTypes.Add(new CodeTypeReference("Form"));
            ns.Types.Add(class1);

            CodeMemberField mfield = new CodeMemberField(new CodeTypeReference("Button"), "b");
            mfield.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference("Button"));
            class1.Members.Add(mfield);

            CodeConstructor ctor = new CodeConstructor();
            ctor.Attributes = MemberAttributes.Public;
            ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
                                "Size"), new CodeObjectCreateExpression(new CodeTypeReference("Size"),
                                new CodePrimitiveExpression(600), new CodePrimitiveExpression(600))));
            ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
                                "Text"), new CodePrimitiveExpression("Test")));
            ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
                                "TabIndex"), new CodePrimitiveExpression(0)));
            ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
                                "Location"), new CodeObjectCreateExpression(new CodeTypeReference("Point"),
                                new CodePrimitiveExpression(400), new CodePrimitiveExpression(525))));
            ctor.Statements.Add(new CodeAttachEventStatement(new CodeEventReferenceExpression(new
                CodeThisReferenceExpression(), "MyEvent"), new CodeDelegateCreateExpression(new CodeTypeReference("EventHandler")
                , new CodeThisReferenceExpression(), "b_Click")));
            class1.Members.Add(ctor);

            CodeMemberEvent evt = new CodeMemberEvent();
            evt.Name = "MyEvent";
            evt.Type = new CodeTypeReference("System.EventHandler");
            evt.Attributes = MemberAttributes.Public;
            evt.CustomAttributes.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false))));
            class1.Members.Add(evt);

            CodeMemberMethod cmm = new CodeMemberMethod();
            cmm.Name = "b_Click";
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender"));
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(EventArgs), "e"));
            class1.Members.Add(cmm);

            AssertEqual(cu,
                @"'------------------------------------------------------------------------------
                  ' <auto-generated>
                  '     This code was generated by a tool.
                  '     Runtime Version:4.0.30319.42000
                  '
                  '     Changes to this file may cause incorrect behavior and will be lost if
                  '     the code is regenerated.
                  ' </auto-generated>
                  '------------------------------------------------------------------------------

                  Option Strict Off
                  Option Explicit On

                  Imports System
                  Imports System.ComponentModel
                  Imports System.Drawing
                  Imports System.Windows.Forms
                  <Assembly: System.Reflection.AssemblyTitle(""MyAssembly""),  _
                   Assembly: System.Reflection.AssemblyVersion(""1.0.6.2""),  _
                   Assembly: System.CLSCompliantAttribute(false)>

                  Namespace MyNamespace

                      <System.Serializable(),  _
                       System.Obsolete(""Don't use this Class"")>  _
                      Public Class [MyClass]

                          <System.Xml.Serialization.XmlElementAttribute()>  _
                          Private myField As String = ""hi!""

                          <System.Obsolete(""Don't use this Constructor"")>  _
                          Private Sub New()
                              MyBase.New
                          End Sub

                          <System.Obsolete(""Don't use this Property"")>  _
                          Private ReadOnly Property MyProperty() As String
                              Get
                                  Return Me.myField
                              End Get
                          End Property

                          <System.Obsolete(""Don't use this Method""),  _
                           System.ComponentModel.Editor(""This"", ""That"")>  _
                          Private Sub MyMethod(<System.Xml.Serialization.XmlElementAttribute(Form:=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable:=false)> ByVal blah As String, <System.Xml.Serialization.XmlElementAttribute(Form:=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable:=false)> ByVal arrayit() As Integer)
                          End Sub

                          <System.Obsolete(""Don't use this Function"")>  _
                          Private Function MyFunction() As <System.Xml.Serialization.XmlIgnoreAttribute(), System.Xml.Serialization.XmlRootAttribute([Namespace]:=""Namespace Value"", ElementName:=""Root, hehehe"")> String
                              Return ""Return""
                          End Function

                          <Global.System.ObsoleteAttribute(""Don't use this Function"")>  _
                          Private Sub GlobalKeywordFunction()
                          End Sub

                          <System.Serializable()>  _
                          Public Class NestedClass
                          End Class
                      End Class

                      Public Class Test
                          Inherits Form

                          Private b As Button = New Button()

                          Public Sub New()
                              MyBase.New
                              Me.Size = New Size(600, 600)
                              b.Text = ""Test""
                              b.TabIndex = 0
                              b.Location = New Point(400, 525)
                              AddHandler MyEvent, AddressOf Me.b_Click
                          End Sub

                          <System.CLSCompliantAttribute(false)>  _
                          Public Event MyEvent As System.EventHandler

                          Private Sub b_Click(ByVal sender As Object, ByVal e As System.EventArgs)
                          End Sub
                      End Class
                  End Namespace");
        }
示例#56
0
 /// <include file='doc\XmlCodeExporter.uex' path='docs/doc[@for="XmlCodeExporter.XmlCodeExporter4"]/*' />
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 public XmlCodeExporter(CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit, CodeDomProvider codeProvider, CodeGenerationOptions options, Hashtable mappings)
     : base(codeNamespace, codeCompileUnit, codeProvider, options, mappings)
 {
 }
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {

        CodeNamespace nspace = new CodeNamespace("NSPC");
        nspace.Imports.Add(new CodeNamespaceImport("System"));
        cu.Namespaces.Add(nspace);

        CodeTypeDeclaration cd = new CodeTypeDeclaration("TestFields");
        cd.IsClass = true;
        nspace.Types.Add(cd);

        // GENERATES (C#):
        //        public static int UseStaticPublicField(int i) {
        //            ClassWithFields.StaticPublicField = i;
        //            return ClassWithFields.StaticPublicField;
        //
        CodeMemberMethod cmm;
        if (Supports(provider, GeneratorSupport.PublicStaticMembers))
        {
          AddScenario("CheckUseStaticPublicField");
          cmm = new CodeMemberMethod();
          cmm.Name = "UseStaticPublicField";
          cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
          cmm.ReturnType = new CodeTypeReference(typeof(int));
          cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
          cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(
              new CodeTypeReferenceExpression("ClassWithFields"), "StaticPublicField"),
              new CodeArgumentReferenceExpression("i")));
          cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new
              CodeTypeReferenceExpression("ClassWithFields"), "StaticPublicField")));
          cd.Members.Add(cmm);
        }

        // GENERATES (C#):
        //        public static int UseNonStaticPublicField(int i) {
        //            ClassWithFields variable = new ClassWithFields();
        //            variable.NonStaticPublicField = i;
        //            return variable.NonStaticPublicField;
        //        }
        AddScenario("CheckUseNonStaticPublicField");
        cmm = new CodeMemberMethod();
        cmm.Name = "UseNonStaticPublicField";
        cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
        cmm.ReturnType = new CodeTypeReference(typeof(int));
        cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
        cmm.Statements.Add(new CodeVariableDeclarationStatement("ClassWithFields", "variable", new CodeObjectCreateExpression("ClassWithFields")));
        cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(
            new CodeVariableReferenceExpression("variable"), "NonStaticPublicField"),
            new CodeArgumentReferenceExpression("i")));
        cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new
            CodeVariableReferenceExpression("variable"), "NonStaticPublicField")));
        cd.Members.Add(cmm);

        // GENERATES (C#):
        //        public static int UseNonStaticInternalField(int i) {
        //            ClassWithFields variable = new ClassWithFields();
        //            variable.NonStaticInternalField = i;
        //            return variable.NonStaticInternalField;
        //        }          

        if (!(provider is JScriptCodeProvider) && !(provider is VBCodeProvider))
        {
          cmm = new CodeMemberMethod();
          AddScenario("CheckUseNonStaticInternalField");
          cmm.Name = "UseNonStaticInternalField";
          cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
          cmm.ReturnType = new CodeTypeReference(typeof(int));
          cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
          cmm.Statements.Add(new CodeVariableDeclarationStatement("ClassWithFields", "variable", new CodeObjectCreateExpression("ClassWithFields")));
          cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(
              new CodeVariableReferenceExpression("variable"), "NonStaticInternalField"),
              new CodeArgumentReferenceExpression("i")));
          cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new
              CodeVariableReferenceExpression("variable"), "NonStaticInternalField")));
          cd.Members.Add(cmm);
        }

        // GENERATES (C#):
        //        public static int UseInternalField(int i) {
        //            ClassWithFields.InternalField = i;
        //            return ClassWithFields.InternalField;
        //        }
        if (!(provider is JScriptCodeProvider) && !(provider is VBCodeProvider))
        {
          AddScenario("CheckUseInternalField");
          cmm = new CodeMemberMethod();
          cmm.Name = "UseInternalField";
          cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
          cmm.ReturnType = new CodeTypeReference(typeof(int));
          cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
          cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new
              CodeTypeReferenceExpression("ClassWithFields"), "InternalField"),
              new CodeArgumentReferenceExpression("i")));
          cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new
              CodeTypeReferenceExpression("ClassWithFields"), "InternalField")));
          cd.Members.Add(cmm);
        }

        // GENERATES (C#):
        //       public static int UseConstantField(int i) {
        //            return ClassWithFields.ConstantField;
        //        }
        AddScenario("CheckUseConstantField");
        cmm = new CodeMemberMethod();
        cmm.Name = "UseConstantField";
        cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
        cmm.ReturnType = new CodeTypeReference(typeof(int));
        cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
        cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new
            CodeTypeReferenceExpression("ClassWithFields"), "ConstantField")));
        cd.Members.Add(cmm);

        // code a new class to test that the protected field can be accessed by classes that inherit it
        // GENERATES (C#):
        //    public class TestProtectedField : ClassWithFields {
        //        public static int UseProtectedField(int i) {
        //            ProtectedField = i;
        //            return ProtectedField;
        //        }
        //    }
        cd = new CodeTypeDeclaration("TestProtectedField");
        cd.BaseTypes.Add(new CodeTypeReference("ClassWithFields"));
        cd.IsClass = true;
        nspace.Types.Add(cd);

        cmm = new CodeMemberMethod();
        AddScenario("CheckUseProtectedField");
        cmm.Name = "UseProtectedField";
        cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
        cmm.ReturnType = new CodeTypeReference(typeof(int));
        cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
        CodeFieldReferenceExpression reference = new CodeFieldReferenceExpression();
        reference.FieldName = "ProtectedField";
        reference.TargetObject = new CodeTypeReferenceExpression("ClassWithFields");
        cmm.Statements.Add(new CodeAssignStatement(reference,
            new CodeArgumentReferenceExpression("i")));
        cmm.Statements.Add(new CodeMethodReturnStatement(reference));
        cd.Members.Add(cmm);


        // declare class with fields
        //  GENERATES (C#):
        //            public class ClassWithFields {
        //                public static int StaticPublicField = 5;
        //                /*FamANDAssem*/ internal static int InternalField = 0;
        //                public const int ConstantField = 0;
        //                protected static int ProtectedField = 0;
        //                private static int PrivateField = 5;
        //                public int NonStaticPublicField = 5;
        //                /*FamANDAssem*/ internal int NonStaticInternalField = 0;
        //                public static int UsePrivateField(int i) {
        //                    PrivateField = i;
        //                    return PrivateField;
        //                }
        //            }
        cd = new CodeTypeDeclaration ("ClassWithFields");
        cd.IsClass = true;
        nspace.Types.Add (cd);

        CodeMemberField field;
        if (Supports (provider, GeneratorSupport.PublicStaticMembers)) {
            field = new CodeMemberField ();
            field.Name = "StaticPublicField";
            field.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            field.Type = new CodeTypeReference (typeof (int));
            field.InitExpression = new CodePrimitiveExpression (5);
            cd.Members.Add (field);
        }

        if (!(provider is JScriptCodeProvider) && !(provider is VBCodeProvider)) {
            field = new CodeMemberField ();
            field.Name = "InternalField";
            field.Attributes = MemberAttributes.FamilyOrAssembly | MemberAttributes.Static;
            field.Type = new CodeTypeReference (typeof (int));
            field.InitExpression = new CodePrimitiveExpression (0);
            cd.Members.Add (field);
        }

        field = new CodeMemberField ();
        field.Name = "ConstantField";
        field.Attributes = MemberAttributes.Public | MemberAttributes.Const;
        field.Type = new CodeTypeReference (typeof (int));
        field.InitExpression = new CodePrimitiveExpression (0);
        cd.Members.Add (field);

        field = new CodeMemberField ();
        field.Name = "ProtectedField";
        field.Attributes = MemberAttributes.Family | MemberAttributes.Static;
        field.Type = new CodeTypeReference (typeof (int));
        field.InitExpression = new CodePrimitiveExpression (0);
        cd.Members.Add (field);

        field = new CodeMemberField ();
        field.Name = "PrivateField";
        field.Attributes = MemberAttributes.Private | MemberAttributes.Static;
        field.Type = new CodeTypeReference (typeof (int));
        field.InitExpression = new CodePrimitiveExpression (5);
        cd.Members.Add (field);

        field = new CodeMemberField ();
        field.Name = "NonStaticPublicField";
        field.Attributes = MemberAttributes.Public | MemberAttributes.Final;
        field.Type = new CodeTypeReference (typeof (int));
        field.InitExpression = new CodePrimitiveExpression (5);
        cd.Members.Add (field);

        if (!(provider is JScriptCodeProvider) && !(provider is VBCodeProvider)) {
            field = new CodeMemberField ();
            field.Name = "NonStaticInternalField";
            field.Attributes = MemberAttributes.FamilyOrAssembly | MemberAttributes.Final;
            field.Type = new CodeTypeReference (typeof (int));
            field.InitExpression = new CodePrimitiveExpression (0);
            cd.Members.Add (field);
        }

        // create a method to test access to private field
        AddScenario ("CheckUsePrivateField");
        cmm = new CodeMemberMethod ();
        cmm.Name = "UsePrivateField";
        cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
        cmm.ReturnType = new CodeTypeReference (typeof (int));
        cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i"));
        CodeFieldReferenceExpression fieldref = new CodeFieldReferenceExpression ();
        fieldref.TargetObject = new CodeTypeReferenceExpression("ClassWithFields");
        fieldref.FieldName = "PrivateField";
        cmm.Statements.Add (new CodeAssignStatement (fieldref, new CodeArgumentReferenceExpression ("i")));
        cmm.Statements.Add (new CodeMethodReturnStatement (fieldref));
        cd.Members.Add (cmm);
    }
        public static void WriteClass(TextWriter writer, string ns)
        {
            var buildDataTable     = EditorRuntimeAssetDataCollector.BuildDataTable();
            var allAssetDataGroups = buildDataTable.AllAssetDataGroups;

            var assetBundleInfos = new List <AssetBundleInfo>();

            allAssetDataGroups.ForEach(assetDataGroup =>
            {
                var assetDatas = assetDataGroup.AssetBundleDatas;

                assetDatas.ForEach(abUnit =>
                {
                    assetBundleInfos.Add(new AssetBundleInfo(abUnit.abName)
                    {
                        assets = assetDataGroup.AssetDatas
                                 .Where(assetData => assetData.OwnerBundleName == abUnit.abName)
                                 .Select(assetData => assetData.AssetName)
                                 .ToArray()
                    });
                });
            });

            var compileUnit   = new CodeCompileUnit();
            var codeNamespace = new CodeNamespace(ns);

            compileUnit.Namespaces.Add(codeNamespace);

            foreach (var assetBundleInfo in assetBundleInfos)
            {
                var className  = assetBundleInfo.Name;
                var bundleName = className.Substring(0, 1).ToLower() + className.Substring(1);
                int firstNumber;
                if (int.TryParse(bundleName[0].ToString(), out firstNumber))
                {
                    continue;
                }

                className = className.Substring(0, 1).ToUpper() +
                            className.Substring(1).Replace("/", "_").Replace("@", "_").Replace("!", "_");

                var codeType = new CodeTypeDeclaration(className);
                codeNamespace.Types.Add(codeType);

                var bundleNameField = new CodeMemberField
                {
                    Attributes = MemberAttributes.Public | MemberAttributes.Const,
                    Name       = "BundleName",
                    Type       = new CodeTypeReference(typeof(System.String))
                };
                codeType.Members.Add(bundleNameField);
                bundleNameField.InitExpression = new CodePrimitiveExpression(bundleName.ToLowerInvariant());

                var checkRepeatDict = new Dictionary <string, string>();
                foreach (var asset in assetBundleInfo.assets)
                {
                    var assetField = new CodeMemberField {
                        Attributes = MemberAttributes.Public | MemberAttributes.Const
                    };

                    var content = Path.GetFileNameWithoutExtension(asset);
                    assetField.Name = content.ToUpperInvariant().Replace("@", "_").Replace("!", "_");
                    assetField.Type = new CodeTypeReference(typeof(System.String));
                    if (!assetField.Name.StartsWith("[") && !assetField.Name.StartsWith(" [") &&
                        !checkRepeatDict.ContainsKey(assetField.Name))
                    {
                        checkRepeatDict.Add(assetField.Name, asset);
                        codeType.Members.Add(assetField);
                    }

                    assetField.InitExpression = new CodePrimitiveExpression(content);
                }

                checkRepeatDict.Clear();
            }

            var provider = new CSharpCodeProvider();
            var options  = new CodeGeneratorOptions
            {
                BlankLinesBetweenMembers = false,
                BracingStyle             = "C"
            };

            provider.GenerateCodeFromCompileUnit(compileUnit, writer, options);
        }
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {
#if WHIDBEY
        if (!(provider is JScriptCodeProvider)) {
            // GENERATES (C#):
            //
            //  #region Compile Unit Region
            //  
            //  namespace Namespace1 {
            //      
            //      
            //      #region Outer Type Region
            //      // Outer Type Comment
            //      public class Class1 {
            //          
            //          // Field 1 Comment
            //          private string field1;
            //          
            //          public void Method1() {
            //              this.Event1(this, System.EventArgs.Empty);
            //          }
            //          
            //          #region Constructor Region
            //          public Class1() {
            //              #region Statements Region
            //              this.field1 = "value1";
            //              this.field2 = "value2";
            //              #endregion
            //          }
            //          #endregion
            //          
            //          public string Property1 {
            //              get {
            //                  return this.field1;
            //              }
            //          }
            //          
            //          public static void Main() {
            //          }
            //          
            //          public event System.EventHandler Event1;
            //          
            //          public class NestedClass1 {
            //          }
            //          
            //          public delegate void nestedDelegate1(object sender, System.EventArgs e);
            //          
            //  
            //          
            //          #region Field Region
            //          private string field2;
            //          #endregion
            //          
            //          #region Method Region
            //          // Method 2 Comment
            //          
            //          #line 500 "MethodLinePragma.txt"
            //          public void Method2() {
            //              this.Event2(this, System.EventArgs.Empty);
            //          }
            //          
            //          #line default
            //          #line hidden
            //          #endregion
            //          
            //          public Class1(string value1, string value2) {
            //          }
            //          
            //          #region Property Region
            //          public string Property2 {
            //              get {
            //                  return this.field2;
            //              }
            //          }
            //          #endregion
            //          
            //          #region Type Constructor Region
            //          static Class1() {
            //          }
            //          #endregion
            //          
            //          #region Event Region
            //          public event System.EventHandler Event2;
            //          #endregion
            //          
            //          #region Nested Type Region
            //          // Nested Type Comment
            //          
            //          #line 400 "NestedTypeLinePragma.txt"
            //          public class NestedClass2 {
            //          }
            //          
            //          #line default
            //          #line hidden
            //          #endregion
            //          
            //          #region Delegate Region
            //          public delegate void nestedDelegate2(object sender, System.EventArgs e);
            //          #endregion
            //          
            //          #region Snippet Region
            //  
            //          #endregion
            //      }
            //      #endregion
            //  }
            //  #endregion

            CodeNamespace ns = new CodeNamespace ("Namespace1");

            cu.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Compile Unit Region"));
            cu.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty));

            cu.Namespaces.Add (ns);

            CodeTypeDeclaration cd = new CodeTypeDeclaration ("Class1");
            ns.Types.Add (cd);

            cd.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Outer Type Region"));
            cd.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty));

            cd.Comments.Add (new CodeCommentStatement ("Outer Type Comment"));

            CodeMemberField field1 = new CodeMemberField (typeof (String), "field1");
            CodeMemberField field2 = new CodeMemberField (typeof (String), "field2");
            field1.Comments.Add (new CodeCommentStatement ("Field 1 Comment"));
            field2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Field Region"));
            field2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty));

            CodeMemberEvent evt1 = new CodeMemberEvent ();
            evt1.Name = "Event1";
            evt1.Type = new CodeTypeReference (typeof (System.EventHandler));
            evt1.Attributes = (evt1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;

            CodeMemberEvent evt2 = new CodeMemberEvent ();
            evt2.Name = "Event2";
            evt2.Type = new CodeTypeReference (typeof (System.EventHandler));
            evt2.Attributes = (evt2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;

            evt2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Event Region"));
            evt2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty));


            CodeMemberMethod method1 = new CodeMemberMethod ();
            method1.Name = "Method1";
            method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            if (provider.Supports (GeneratorSupport.DeclareEvents)) {
                method1.Statements.Add (
                    new CodeDelegateInvokeExpression (
                        new CodeEventReferenceExpression (new CodeThisReferenceExpression (), "Event1"),
                        new CodeExpression[] {
                        new CodeThisReferenceExpression(),
                        new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.EventArgs"), "Empty")
                    }));
            }


            CodeMemberMethod method2 = new CodeMemberMethod ();
            method2.Name = "Method2";
            method2.Attributes = (method2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            if (provider.Supports (GeneratorSupport.DeclareEvents)) {
                method2.Statements.Add (
                    new CodeDelegateInvokeExpression (
                        new CodeEventReferenceExpression (new CodeThisReferenceExpression (), "Event2"),
                        new CodeExpression[] {
                        new CodeThisReferenceExpression(),
                        new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.EventArgs"), "Empty")
                    }));
            }
            method2.LinePragma = new CodeLinePragma ("MethodLinePragma.txt", 500);
            method2.Comments.Add (new CodeCommentStatement ("Method 2 Comment"));

            method2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Method Region"));
            method2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty));


            CodeMemberProperty property1 = new CodeMemberProperty ();
            property1.Name = "Property1";
            property1.Type = new CodeTypeReference (typeof (string));
            property1.Attributes = (property1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            property1.GetStatements.Add (
                new CodeMethodReturnStatement (
                    new CodeFieldReferenceExpression (
                        new CodeThisReferenceExpression (),
                        "field1")));

            CodeMemberProperty property2 = new CodeMemberProperty ();
            property2.Name = "Property2";
            property2.Type = new CodeTypeReference (typeof (string));
            property2.Attributes = (property2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            property2.GetStatements.Add (
                new CodeMethodReturnStatement (
                    new CodeFieldReferenceExpression (
                        new CodeThisReferenceExpression (),
                        "field2")));

            property2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Property Region"));
            property2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty));


            CodeConstructor constructor1 = new CodeConstructor ();
            constructor1.Attributes = (constructor1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            CodeStatement conState1 = new CodeAssignStatement (
                                        new CodeFieldReferenceExpression (
                                            new CodeThisReferenceExpression (),
                                            "field1"),
                                        new CodePrimitiveExpression ("value1"));
            conState1.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Statements Region"));
            constructor1.Statements.Add (conState1);
            CodeStatement conState2 = new CodeAssignStatement (
                                        new CodeFieldReferenceExpression (
                                            new CodeThisReferenceExpression (),
                                            "field2"),
                                        new CodePrimitiveExpression ("value2"));
            conState2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty));
            constructor1.Statements.Add (conState2);

            constructor1.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Constructor Region"));
            constructor1.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty));

            CodeConstructor constructor2 = new CodeConstructor ();
            constructor2.Attributes = (constructor2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            constructor2.Parameters.Add (new CodeParameterDeclarationExpression (typeof (string), "value1"));
            constructor2.Parameters.Add (new CodeParameterDeclarationExpression (typeof (string), "value2"));

            CodeTypeConstructor typeConstructor2 = new CodeTypeConstructor ();

            typeConstructor2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Type Constructor Region"));
            typeConstructor2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty));


            CodeEntryPointMethod methodMain = new CodeEntryPointMethod ();

            CodeTypeDeclaration nestedClass1 = new CodeTypeDeclaration ("NestedClass1");
            CodeTypeDeclaration nestedClass2 = new CodeTypeDeclaration ("NestedClass2");
            nestedClass2.LinePragma = new CodeLinePragma ("NestedTypeLinePragma.txt", 400);
            nestedClass2.Comments.Add (new CodeCommentStatement ("Nested Type Comment"));

            nestedClass2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Nested Type Region"));
            nestedClass2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty));



            CodeTypeDelegate delegate1 = new CodeTypeDelegate ();
            delegate1.Name = "nestedDelegate1";
            delegate1.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference ("System.Object"), "sender"));
            delegate1.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference ("System.EventArgs"), "e"));

            CodeTypeDelegate delegate2 = new CodeTypeDelegate ();
            delegate2.Name = "nestedDelegate2";
            delegate2.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference ("System.Object"), "sender"));
            delegate2.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference ("System.EventArgs"), "e"));

            delegate2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Delegate Region"));
            delegate2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty));


            CodeSnippetTypeMember snippet1 = new CodeSnippetTypeMember ();
            CodeSnippetTypeMember snippet2 = new CodeSnippetTypeMember ();

            CodeRegionDirective regionStart = new CodeRegionDirective (CodeRegionMode.End, "");
            regionStart.RegionText = "Snippet Region";
            regionStart.RegionMode = CodeRegionMode.Start;
            snippet2.StartDirectives.Add (regionStart);
            snippet2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty));


            cd.Members.Add (field1);
            cd.Members.Add (method1);
            cd.Members.Add (constructor1);
            cd.Members.Add (property1);
            cd.Members.Add (methodMain);

            if (Supports (provider, GeneratorSupport.DeclareEvents)) {
                cd.Members.Add (evt1);
            }

            if (Supports (provider, GeneratorSupport.NestedTypes)) {
                cd.Members.Add (nestedClass1);
                if (Supports (provider, GeneratorSupport.DeclareDelegates)) {
                    cd.Members.Add (delegate1);
                }
            }

            cd.Members.Add (snippet1);

            cd.Members.Add (field2);
            cd.Members.Add (method2);
            cd.Members.Add (constructor2);
            cd.Members.Add (property2);


            if (Supports (provider, GeneratorSupport.StaticConstructors)) {
                cd.Members.Add (typeConstructor2);
            }

            if (Supports (provider, GeneratorSupport.DeclareEvents)) {
                cd.Members.Add (evt2);
            }
            if (Supports (provider, GeneratorSupport.NestedTypes)) {
                cd.Members.Add (nestedClass2);
                if (Supports (provider, GeneratorSupport.DeclareDelegates)) {
                    cd.Members.Add (delegate2);
                }
            }
            cd.Members.Add (snippet2);
        }
#endif
    }
示例#60
0
        void GenerateCode(string outFilePath)
        {
            //Create the target directory if required
            Directory.CreateDirectory(System.IO.Path.GetDirectoryName(outFilePath));

            var ccu = new CodeCompileUnit();

            ccu.AssemblyCustomAttributes.Add(
                new CodeAttributeDeclaration(new CodeTypeReference($"global::{typeof(XamlResourceIdAttribute).FullName}"),
                                             new CodeAttributeArgument(new CodePrimitiveExpression(ResourceId)),
                                             new CodeAttributeArgument(new CodePrimitiveExpression(TargetPath.Replace('\\', '/'))), //use forward slashes, paths are uris-like
                                             new CodeAttributeArgument(RootType == null ? (CodeExpression) new CodePrimitiveExpression(null) : new CodeTypeOfExpression($"global::{RootClrNamespace}.{RootType}"))
                                             ));
            if (XamlResourceIdOnly)
            {
                goto writeAndExit;
            }

            if (RootType == null)
            {
                throw new Exception("Something went wrong while executing XamlG");
            }

            var declNs = new CodeNamespace(RootClrNamespace);

            ccu.Namespaces.Add(declNs);

            var declType = new CodeTypeDeclaration(RootType)
            {
                IsPartial        = true,
                TypeAttributes   = GetTypeAttributes(classModifier),
                CustomAttributes =
                {
                    new CodeAttributeDeclaration(new CodeTypeReference(XamlCTask.xamlNameSpace + ".XamlFilePathAttribute"),
                                                 new CodeAttributeArgument(new CodePrimitiveExpression(XamlFile))),
                }
            };

            if (AddXamlCompilationAttribute)
            {
                declType.CustomAttributes.Add(
                    new CodeAttributeDeclaration(new CodeTypeReference(XamlCTask.xamlNameSpace + ".XamlCompilationAttribute"),
                                                 new CodeAttributeArgument(new CodeSnippetExpression($"global::{typeof(XamlCompilationOptions).FullName}.Compile"))));
            }
            if (HideFromIntellisense)
            {
                declType.CustomAttributes.Add(
                    new CodeAttributeDeclaration(new CodeTypeReference($"global::{typeof(System.ComponentModel.EditorBrowsableAttribute).FullName}"),
                                                 new CodeAttributeArgument(new CodeSnippetExpression($"global::{typeof(System.ComponentModel.EditorBrowsableState).FullName}.{nameof(System.ComponentModel.EditorBrowsableState.Never)}"))));
            }

            declType.BaseTypes.Add(BaseType);

            declNs.Types.Add(declType);

            //Create a default ctor calling InitializeComponent
            if (GenerateDefaultCtor)
            {
                var ctor = new CodeConstructor {
                    Attributes       = MemberAttributes.Public,
                    CustomAttributes = { GeneratedCodeAttrDecl },
                    Statements       =
                    {
                        new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "InitializeComponent")
                    }
                };

                declType.Members.Add(ctor);
            }

            //Create InitializeComponent()
            var initcomp = new CodeMemberMethod {
                Name             = "InitializeComponent",
                CustomAttributes = { GeneratedCodeAttrDecl }
            };

            declType.Members.Add(initcomp);

            //Create and initialize fields

            if (0 == XamlOptimization)
            {
                initcomp.Statements.Add(new CodeMethodInvokeExpression(
                                            new CodeTypeReferenceExpression(new CodeTypeReference($"global::{typeof(Extensions).FullName}")),
                                            "LoadFromXaml", new CodeThisReferenceExpression(), new CodeTypeOfExpression(declType.Name)));

                var exitXamlComp = new CodeMemberMethod()
                {
                    Name             = "ExitXaml",
                    CustomAttributes = { GeneratedCodeAttrDecl },
                    Attributes       = MemberAttributes.Assembly | MemberAttributes.Final
                };
                declType.Members.Add(exitXamlComp);
            }
            else
            {
                var loadExaml_invoke = new CodeMethodInvokeExpression(
                    new CodeTypeReferenceExpression(new CodeTypeReference($"global::Tizen.NUI.EXaml.EXamlExtensions")),
                    "LoadFromEXamlByRelativePath", new CodeThisReferenceExpression(),
                    new CodeMethodInvokeExpression()
                {
                    Method = new CodeMethodReferenceExpression()
                    {
                        MethodName = "GetEXamlPath"
                    }
                });

                CodeAssignStatement assignEXamlObject = new CodeAssignStatement(
                    new CodeVariableReferenceExpression("eXamlData"), loadExaml_invoke);

                initcomp.Statements.Add(assignEXamlObject);
            }

            foreach (var namedField in NamedFields)
            {
                if (namedField.Type.BaseType.Contains("-"))
                {
                    namedField.Type.BaseType = namedField.Type.BaseType.Replace("-", ".");
                }
                declType.Members.Add(namedField);

                var find_invoke = new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(
                        new CodeTypeReferenceExpression(new CodeTypeReference($"global::Tizen.NUI.Binding.NameScopeExtensions")),
                        "FindByName", namedField.Type),
                    new CodeThisReferenceExpression(), new CodePrimitiveExpression(namedField.Name));

                CodeAssignStatement assign = new CodeAssignStatement(
                    new CodeVariableReferenceExpression(namedField.Name), find_invoke);

                initcomp.Statements.Add(assign);
            }

            if (0 != XamlOptimization)
            {
                declType.Members.Add(new CodeMemberField
                {
                    Name             = "eXamlData",
                    Type             = new CodeTypeReference("System.Object"),
                    Attributes       = MemberAttributes.Private,
                    CustomAttributes = { GeneratedCodeAttrDecl }
                });

                var getEXamlPathcomp = new CodeMemberMethod()
                {
                    Name             = "GetEXamlPath",
                    ReturnType       = new CodeTypeReference(typeof(string)),
                    CustomAttributes = { GeneratedCodeAttrDecl }
                };

                getEXamlPathcomp.Statements.Add(new CodeMethodReturnStatement(new CodeDefaultValueExpression(new CodeTypeReference(typeof(string)))));

                declType.Members.Add(getEXamlPathcomp);

                GenerateMethodExitXaml(declType);
            }
writeAndExit:
            //write the result
            using (var writer = new StreamWriter(outFilePath))
                Provider.GenerateCodeFromCompileUnit(ccu, writer, new CodeGeneratorOptions());
        }