Exemplo n.º 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);
    }
Exemplo n.º 4
0
    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
    }
Exemplo n.º 6
0
		private static CodeNamespace CreateNamespace(Type t, Dictionary<string, List<string>> influences)
		{
			var nsp = new CodeNamespace("__autonotifypropertychanged");
			var decl = new CodeTypeDeclaration();
			decl.Name = GetNameForDerivedClass(t);
			decl.TypeAttributes = TypeAttributes.NotPublic;
			decl.Attributes = MemberAttributes.Private;
			decl.BaseTypes.Add(t);
			if (!t.GetInterfaces().Any(I => I == typeof(INotifyPropertyChanged)))
			{
				ImplementINotifyPropertyChanged(decl);
			}
			foreach (var ci in t.GetConstructors())
			{
				if (ci.IsPublic && ci.GetParameters().Length > 0)
				{
					AddDerivedConstructor(decl, ci);
				}
			}
			foreach (PropertyInfo pi in t.GetProperties().Where(p => p.IsVirtual()))
			{
				// make sense only to override properties having setter and getter
				if (pi.CanWrite && pi.CanRead)
				{
					List<string> additional = new List<string>();
					if (influences.ContainsKey(pi.Name))
						additional = influences[pi.Name];
					decl.Members.Add(CreatePropertyOverride(pi, additional));
				}
			}
			nsp.Types.Add(decl);
			return nsp;
		}
    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);
    }
    public static StringBuilder GenerateCode(CodeNamespace ns)
    {
        var codeProvider = new CSharpCodeProvider();
        var builder = new StringBuilder();
        var writer = new StringWriter(builder);

        codeProvider.GenerateCodeFromNamespace(ns, writer, new CodeGeneratorOptions());
        writer.Flush();
        return builder;
    }
Exemplo n.º 9
0
        protected override void VisitNamespace(CodeNamespace codeNamespace)
        {
            this.ShowName(codeNamespace, "NameSpace");

            _level++;

            base.VisitNamespace(codeNamespace);

            _level--;
        }
    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;
    }
Exemplo n.º 11
0
 public NamespaceTraverser(CodeNamespace ns, Action<CodeClass> withCodeClass)
 {
     if (ns == null)
         throw new ArgumentNullException("ns");
     
     if (withCodeClass == null)
         throw new ArgumentNullException("withCodeClass");
     
     WithCodeClass = withCodeClass;
     
     if (ns.Members != null)
         Traverse(ns.Members);
 }
Exemplo n.º 12
0
    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);
    }
Exemplo n.º 13
0
	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);
	}
    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);
    }
Exemplo n.º 15
0
 private static string GenerateCode(string expression)
 {
     var source = new StringBuilder();
     var sw = new StringWriter(source);
     var options = new CodeGeneratorOptions();
     var myNamespace = new CodeNamespace("ExpressionEvaluator");
     myNamespace.Imports.Add(new CodeNamespaceImport("System"));
     var classDeclaration = new CodeTypeDeclaration { IsClass = true, Name = "Calculator", Attributes = MemberAttributes.Public };
     var myMethod = new CodeMemberMethod { Name = "Calculate", ReturnType = new CodeTypeReference(typeof(double)), Attributes = MemberAttributes.Public };
     myMethod.Statements.Add(new CodeMethodReturnStatement(new CodeSnippetExpression(expression)));
     classDeclaration.Members.Add(myMethod);
     myNamespace.Types.Add(classDeclaration);
     provider.GenerateCodeFromNamespace(myNamespace, sw, options);
     sw.Flush();
     sw.Close();
     return source.ToString();
 }
Exemplo n.º 16
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);
            }
        }
Exemplo n.º 17
0
        public static BuildResult GenerateCodeBehind(
            AspNetAppProject project,
            string filename,
            WebFormsParsedDocument document,
            out CodeCompileUnit ccu)
        {
            ccu = null;
            var    result    = new BuildResult();
            string className = document.Info.InheritedClass;

            AddErrorsToResult(result, filename, document.Errors);
            if (result.ErrorCount > 0)
            {
                return(result);
            }

            if (string.IsNullOrEmpty(className))
            {
                return(result);
            }

            var refman = new WebFormsTypeContext {
                Project = project, Doc = document
            };
            var memberList = new WebFormsMemberListBuilder(refman, document.XDocument);

            memberList.Build();

            AddErrorsToResult(result, filename, memberList.Errors);
            if (result.ErrorCount > 0)
            {
                return(result);
            }

            //initialise the generated type
            ccu = new CodeCompileUnit();
            var namespac = new CodeNamespace();

            ccu.Namespaces.Add(namespac);
            var typeDecl = new CodeTypeDeclaration {
                IsClass   = true,
                IsPartial = true,
            };

            namespac.Types.Add(typeDecl);

            //name the class and namespace
            int namespaceSplit = className.LastIndexOf('.');

            if (namespaceSplit > -1)
            {
                namespac.Name = project.StripImplicitNamespace(className.Substring(0, namespaceSplit));
                typeDecl.Name = className.Substring(namespaceSplit + 1);
            }
            else
            {
                typeDecl.Name = className;
            }

            string masterTypeName = null;

            if (!String.IsNullOrEmpty(document.Info.MasterPageTypeName))
            {
                masterTypeName = document.Info.MasterPageTypeName;
            }
            else if (!String.IsNullOrEmpty(document.Info.MasterPageTypeVPath))
            {
                try {
                    ProjectFile            resolvedMaster       = project.ResolveVirtualPath(document.Info.MasterPageTypeVPath, document.FileName);
                    WebFormsParsedDocument masterParsedDocument = null;
                    if (resolvedMaster != null)
                    {
                        masterParsedDocument = TypeSystemService.ParseFile(project, resolvedMaster.FilePath) as WebFormsParsedDocument;
                    }
                    if (masterParsedDocument != null && !String.IsNullOrEmpty(masterParsedDocument.Info.InheritedClass))
                    {
                        masterTypeName = masterParsedDocument.Info.InheritedClass;
                    }
                } catch (Exception ex) {
                    LoggingService.LogWarning("Error resolving master page type", ex);
                }
                if (string.IsNullOrEmpty(masterTypeName))
                {
                    var msg = string.Format("Could not find type for master '{0}'", document.Info.MasterPageTypeVPath);
                    result.AddError(filename, msg);
                    return(result);
                }
            }

            if (masterTypeName != null)
            {
                var masterProp = new CodeMemberProperty {
                    Name       = "Master",
                    Type       = new CodeTypeReference(masterTypeName),
                    HasGet     = true,
                    HasSet     = false,
                    Attributes = MemberAttributes.Public | MemberAttributes.New | MemberAttributes.Final,
                };
                masterProp.GetStatements.Add(new CodeMethodReturnStatement(
                                                 new CodeCastExpression(masterTypeName,
                                                                        new CodePropertyReferenceExpression(
                                                                            new CodeBaseReferenceExpression(), "Master"))));
                typeDecl.Members.Add(masterProp);
            }

            //shortcut building the existing members type map
            if (memberList.Members.Count == 0)
            {
                return(result);
            }

            var dom     = refman.Compilation;
            var cls     = ReflectionHelper.ParseReflectionName(className).Resolve(dom);
            var members = GetDesignerMembers(memberList.Members.Values, cls, filename);

            //add fields for each control in the page

            foreach (var member in members)
            {
                var type = new CodeTypeReference(member.Type.FullName);
                typeDecl.Members.Add(new CodeMemberField(type, member.Name)
                {
                    Attributes = MemberAttributes.Family
                });
            }
            return(result);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Create TypeScript CodeDOM for POCO types.
        /// For an enum type, all members will be processed regardless of EnumMemberAttribute.
        /// </summary>
        /// <param name="types">POCO types.</param>
        public void CreateCodeDom(Type[] types, CherryPickingMethods methods)
        {
            if (types == null)
            {
                throw new ArgumentNullException("types", "types is not defined.");
            }

            this.pendingTypes.AddRange(types);
            var typeGroupedByNamespace = types
                                         .GroupBy(d => d.Namespace)
                                         .OrderBy(k => k.Key); // order by namespace
            var namespacesOfTypes = typeGroupedByNamespace.Select(d => d.Key).ToArray();

            foreach (var groupedTypes in typeGroupedByNamespace)
            {
                var clientNamespaceText = (groupedTypes.Key + ".Client").Replace('.', '_');
                var clientNamespace     = new CodeNamespace(clientNamespaceText);
                targetUnit.Namespaces.Add(clientNamespace);//namespace added to Dom

                Debug.WriteLine("Generating types in namespace: " + groupedTypes.Key + " ...");
                groupedTypes.OrderBy(t => t.Name).Select(type =>
                {
                    var tsName = type.Name;
                    Debug.WriteLine("tsClass: " + clientNamespace + "  " + tsName);

                    CodeTypeDeclaration typeDeclaration;
                    if (TypeHelper.IsClassOrStruct(type))
                    {
                        if (type.IsGenericType)
                        {
                            typeDeclaration = PodGenHelper.CreatePodClientGenericInterface(clientNamespace, type);
                        }
                        else
                        {
                            typeDeclaration = PodGenHelper.CreatePodClientInterface(clientNamespace, tsName);
                        }

                        if (!type.IsValueType)
                        {
                            if (namespacesOfTypes.Contains(type.BaseType.Namespace))
                            {
                                typeDeclaration.BaseTypes.Add(RefineCustomComplexTypeText(type.BaseType));
                            }
                            else
                            {
                                typeDeclaration.BaseTypes.Add(type.BaseType);
                            }
                        }

                        CreateTypeDocComment(type, typeDeclaration);

                        var typeProperties = type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public).OrderBy(p => p.Name).ToArray();
                        foreach (var propertyInfo in typeProperties)
                        {
                            var cherryType = CherryPicking.GetMemberCherryType(propertyInfo, methods);
                            if (cherryType == CherryType.None)
                            {
                                continue;
                            }
                            string tsPropertyName;


                            var isRequired = cherryType == CherryType.BigCherry;
                            var customName = CherryPicking.GetFieldCustomName(propertyInfo, methods);
                            if (String.IsNullOrEmpty(customName))
                            {
                                tsPropertyName = Fonlow.TypeScriptCodeDom.TsCodeGenerationOptions.Instance.CamelCase ? Fonlow.Text.StringExtensions.ToCamelCase(propertyInfo.Name) : propertyInfo.Name;
                            }
                            else
                            {
                                tsPropertyName = customName;
                            }

                            Debug.WriteLine(String.Format("{0} : {1}", tsPropertyName, propertyInfo.PropertyType.Name));
                            var clientField = new CodeMemberField()//Yes, clr property translated to ts field
                            {
                                Name = tsPropertyName + (isRequired ? String.Empty : "?"),
                                Type = TranslateToClientTypeReference(propertyInfo.PropertyType),
                                //                     Attributes = MemberAttributes.Public,
                            };

                            CreatePropertyDocComment(propertyInfo, clientField);

                            typeDeclaration.Members.Add(clientField);
                        }

                        var typeFields = type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public).OrderBy(f => f.Name).ToArray();
                        foreach (var fieldInfo in typeFields)
                        {
                            var cherryType = CherryPicking.GetMemberCherryType(fieldInfo, methods);
                            if (cherryType == CherryType.None)
                            {
                                continue;
                            }
                            string tsPropertyName;


                            var isRequired = (cherryType == CherryType.BigCherry) || !type.IsClass;//public fields in struct should all be value types, so required
                            var customName = CherryPicking.GetFieldCustomName(fieldInfo, methods);
                            if (String.IsNullOrEmpty(customName))
                            {
                                tsPropertyName = Fonlow.TypeScriptCodeDom.TsCodeGenerationOptions.Instance.CamelCase ? Fonlow.Text.StringExtensions.ToCamelCase(fieldInfo.Name) : fieldInfo.Name;
                            }
                            else
                            {
                                tsPropertyName = customName;
                            }

                            Debug.WriteLine(String.Format("{0} : {1}", tsPropertyName, fieldInfo.FieldType.Name));

                            var clientField = new CodeMemberField()
                            {
                                Name = tsPropertyName + (isRequired ? String.Empty : "?"),
                                Type = TranslateToClientTypeReference(fieldInfo.FieldType),
                            };

                            CreateFieldDocComment(fieldInfo, clientField);

                            typeDeclaration.Members.Add(clientField);
                        }
                    }
                    else if (type.IsEnum)
                    {
                        typeDeclaration = PodGenHelper.CreatePodClientEnum(clientNamespace, tsName);

                        CreateTypeDocComment(type, typeDeclaration);

                        int k = 0;
                        foreach (var fieldInfo in type.GetFields(BindingFlags.Public | BindingFlags.Static))
                        {
                            var name     = fieldInfo.Name;
                            var intValue = (int)Convert.ChangeType(fieldInfo.GetValue(null), typeof(int));
                            Debug.WriteLine(name + " -- " + intValue);
                            var isInitialized = intValue != k;

                            var clientField = new CodeMemberField()
                            {
                                Name           = name,
                                Type           = new CodeTypeReference(fieldInfo.FieldType),
                                InitExpression = isInitialized ? new CodePrimitiveExpression(intValue) : null,
                            };

                            CreateFieldDocComment(fieldInfo, clientField);

                            typeDeclaration.Members.Add(clientField);
                            k++;
                        }
                    }
                    else
                    {
                        Trace.TraceWarning("Not yet supported: " + type.Name);
                        typeDeclaration = null;
                    }

                    return(typeDeclaration);
                }
                                                         ).ToArray();//add classes into the namespace
            }
        }
Exemplo n.º 19
0
 public SoapCodeExporter(CodeNamespace codeNamespace) : this(codeNamespace, null)
 {
 }
Exemplo n.º 20
0
        /// <summary>
        /// Processes the schema.
        /// </summary>
        /// <param name="xsdFile">The full path to the WXS file to process.</param>
        /// <param name="targetNamespace">The namespace to put generated classes in.</param>
        /// <returns>The CodeDom tree generated from the schema.</returns>
        public static CodeNamespace Process(string xsdFile, string targetNamespace, CodeDomProvider Provider)
        {
            // Load the XmlSchema and its collection.
            //XmlSchema xsd;
            //using ( FileStream fs = new FileStream( xsdFile, FileMode.Open ) )
            //{
            //    xsd = XmlSchema.Read( fs,  VH1 );
            //    xsd.Compile( VH2  );
            //}
            XmlSchemaSet set = new XmlSchemaSet();
            XmlSchema    xsd = set.Add(null, xsdFile);

            set.Compile();

            XmlSchemas schemas = new XmlSchemas();

            schemas.Add(xsd);

            // Create the importer for these schemas.
            XmlSchemaImporter importer = new XmlSchemaImporter(schemas);

            // System.CodeDom namespace for the XmlCodeExporter to put classes in.
            CodeNamespace   ns       = new CodeNamespace(targetNamespace);
            XmlCodeExporter exporter = new XmlCodeExporter(ns);

            // Iterate schema top-level elements and export code for each.
            foreach (XmlSchemaElement element in set.GlobalElements.Values)
            {
                // Import the mapping first.
                XmlTypeMapping mapping = importer.ImportTypeMapping(
                    element.QualifiedName);
                // Export the code finally.
                exporter.ExportTypeMapping(mapping);
            }

            #region Execute extensions

            XPathNavigator nav;
            using (FileStream fs = new FileStream(xsdFile, FileMode.Open, FileAccess.Read)) {
                nav = new XPathDocument(fs).CreateNavigator();
            }

            XPathNodeIterator it = nav.Select(Extensions);
            while (it.MoveNext())
            {
                Dictionary <string, string> values = ParsePEValue(it.Current.Value);
                Type t = Type.GetType(values["extension-type"], true);
                // Is the type an ICodeExtension?
                Type iface = t.GetInterface(typeof(ICodeExtension).Name);
                if (iface == null)
                {
                    throw new ArgumentException(string.Format(Resources.ex_InvalidExtensionType, it.Current.Value));
                }

                ICodeExtension ext = (ICodeExtension)Activator.CreateInstance(t);
                ext.Initialize(values);
                // Run it!
                ext.Process(ns, xsd, Provider);
            }

            #endregion Execute extensions

            return(ns);
        }
Exemplo n.º 21
0
        public static Assembly CreateAssemblyCached(string wsdlUrl, ref string className)
        {
            string key = AddWSDL(wsdlUrl);

            lock (_lock)
            {
                // Query cache first.
                if (CacheAssembly.ContainsKey(key))
                {
                    if (CacheTimeouts.ContainsKey(key))
                    {
                        if ((DateTime.UtcNow - CacheTimeouts[key]).TotalMinutes <= CACHE_TIME_OUT)
                        {
                            if (false == string.IsNullOrEmpty(CacheServices[key]))
                            {
                                className = CacheServices[key];
                            }
                            return(CacheAssembly[key]);
                        }
                    }
                }

                try
                {
                    //获取WSDL
                    WebClient                  wc     = new WebClient();
                    Stream                     stream = wc.OpenRead(key);
                    ServiceDescription         sd     = ServiceDescription.Read(stream);
                    ServiceDescriptionImporter sdi    = new ServiceDescriptionImporter();
                    // set className according to service name
                    if (sd.Services.Count > 0)
                    {
                        className = sd.Services[0].Name;
                    }
                    sdi.AddServiceDescription(sd, "", "");
                    CodeNamespace cn = new CodeNamespace(@namespace);

                    //生成客户端代理类代码
                    CodeCompileUnit ccu = new CodeCompileUnit();
                    ccu.Namespaces.Add(cn);
                    sdi.Import(cn, ccu);
                    Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider();
                    // ICodeCompiler icc = csc.CreateCompiler();

                    //设定编译参数
                    CompilerParameters cplist = new CompilerParameters();
                    cplist.GenerateExecutable = false;
                    cplist.GenerateInMemory   = true;
                    cplist.ReferencedAssemblies.Add("System.dll");
                    cplist.ReferencedAssemblies.Add("System.XML.dll");
                    cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                    cplist.ReferencedAssemblies.Add("System.Data.dll");

                    //编译代理类
                    CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);
                    if (true == cr.Errors.HasErrors)
                    {
                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                        foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                        {
                            sb.Append(ce.ToString());
                            sb.Append(System.Environment.NewLine);
                        }
                        throw new Exception(sb.ToString());
                    }



                    //生成代理实例,并调用方法
                    System.Reflection.Assembly assembly = cr.CompiledAssembly;
                    // add to cache
                    CacheAssembly[key] = assembly;
                    CacheTimeouts[key] = DateTime.UtcNow;
                    CacheServices[key] = className;
                    return(assembly);
                }
                catch (Exception ex)
                {
                    if (null == ex.InnerException)
                    {
                        throw new Exception(ex.Message, new Exception(ex.StackTrace));
                    }
                    else
                    {
                        throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
                    }
                }
            }
        }
Exemplo n.º 22
0
        internal bool Import(ServiceDescriptionImporter descriptionImporter, CodeNamespace codeNamespace, ArrayList importInfo)
        {
            this.descriptionImporter = descriptionImporter;
            this.classNames          = new CodeIdentifiers();;
            this.codeNamespace       = codeNamespace;

            warnings = (ServiceDescriptionImportWarnings)0;

            bool found = false;

            ClasifySchemas(importInfo);

            BeginNamespace();

            foreach (ImportInfo info in importInfo)
            {
                foreach (Service service in info.ServiceDescription.Services)
                {
                    this.service = service;
                    int bindingCount = 0;
                    foreach (Port port in service.Ports)
                    {
                        binding = ServiceDescriptions.GetBinding(port.Binding);
                        if (IsBindingSupported())
                        {
                            bindingCount++;
                        }
                    }

                    foreach (Port port in service.Ports)
                    {
                        this.iinfo = info;
                        this.port  = port;
                        binding    = ServiceDescriptions.GetBinding(port.Binding);
                        if (!IsBindingSupported())
                        {
                            continue;
                        }

                        found = true;
                        ImportPortBinding(bindingCount > 1);
                    }
                }
            }

            if (!found)
            {
                // Looks like MS.NET generates classes for all bindings if
                // no services are present

                foreach (ImportInfo info in importInfo)
                {
                    this.iinfo = info;
                    foreach (Binding b in info.ServiceDescription.Bindings)
                    {
                        this.binding = b;
                        this.service = null;
                        this.port    = null;
                        if (!IsBindingSupported())
                        {
                            continue;
                        }
                        found = true;
                        ImportPortBinding(true);
                    }
                }
            }

            EndNamespace();

            if (!found)
            {
                warnings = ServiceDescriptionImportWarnings.NoCodeGenerated;
            }
            return(found);
        }
Exemplo n.º 23
0
        private static void CreateWidgetScript(string name)
        {
            var unit = new CodeCompileUnit();
            //add namespace
            var importsNamespace = new CodeNamespace
            {
                Imports =
                {
                    new CodeNamespaceImport("UnityEngine"),
                    new CodeNamespaceImport("UnityEngine.UI"),
                    new CodeNamespaceImport("System.Collections")
                }
            };
            var playflockNamespace = new CodeNamespace("Playflock.Log.Widget");

            unit.Namespaces.Add(importsNamespace);
            unit.Namespaces.Add(playflockNamespace);
            // add class
            var declarationClass = new CodeTypeDeclaration(name + "Widget");

            declarationClass.IsClass = true;
            //inherits from
            declarationClass.BaseTypes.Add("HUDWidget");

            //add member (ex: private bool = false)
            //UnityEngine.UI
            List <CodeMemberField> memberFields = new List <CodeMemberField>();

            foreach (var wm in _widgetMembers)
            {
                CodeMemberField activeField = null;
                switch (wm.NamespaceType)
                {
                case NamespaceType.System:
                    activeField = new CodeMemberField(_namespaceKV[wm.NamespaceType] + "." + wm.SystemTypeCode,
                                                      wm.Name);
                    break;

                case NamespaceType.UnityEngine:
                    activeField = new CodeMemberField(_namespaceKV[wm.NamespaceType] + "." + wm.UeTypeCode, wm.Name);
                    break;

                case NamespaceType.UnityEngineUI:
                    activeField = new CodeMemberField(_namespaceKV[wm.NamespaceType] + "." + wm.UeUiTypeCode,
                                                      wm.Name);
                    break;
                }
                activeField.Attributes = wm.Attribute;
                if (wm.IsSerialized)
                {
                    var customAttribute =
                        new CodeAttributeDeclaration(new CodeTypeReference(typeof(SerializeField)));
                    CodeAttributeDeclarationCollection declarationsCollection = new CodeAttributeDeclarationCollection();
                    declarationsCollection.Add(customAttribute);
                    activeField.CustomAttributes = new CodeAttributeDeclarationCollection(declarationsCollection);
                }
                memberFields.Add(activeField);
            }

            //Methods
            var initializeMethod = new CodeMemberMethod();

            initializeMethod.Name       = "Initialize";
            initializeMethod.Attributes = MemberAttributes.Override | MemberAttributes.Public;
            var drawMethod = new CodeMemberMethod();

            drawMethod.Name       = "Draw";
            drawMethod.Attributes = MemberAttributes.Override | MemberAttributes.Public;
            foreach (var mf in memberFields)
            {
                declarationClass.Members.Add(mf);
            }
            declarationClass.Members.Add(initializeMethod);
            declarationClass.Members.Add(drawMethod);

            //var attribute = new CodeAttributeDeclaration(
            //new CodeTypeReference(typeof(SerializableAttribute)));
            //unit.AssemblyCustomAttributes.Add(attribute);

            playflockNamespace.Types.Add(declarationClass);

            var provider   = (CSharpCodeProvider)CodeDomProvider.CreateProvider("csharp");
            var scriptPath = _rootPath + _widgetFolder + "/" + name + "Widget.cs";

            using (var sw = new StreamWriter(scriptPath, false))
            {
                var tw = new IndentedTextWriter(sw, "    ");
                //generate source code
                var options = new CodeGeneratorOptions();
                options.BracingStyle             = "C";
                options.BlankLinesBetweenMembers = true;
                provider.GenerateCodeFromCompileUnit(unit, tw, options);
                tw.Close();
                sw.Close();
            }
            //delete autogenerated summary (optional)
            using (var Reader = new StreamReader(scriptPath))
            {
                var fileContent = Reader.ReadToEnd();

                var sb = new StringBuilder(fileContent);
                sb.Remove(0, 420);
                Reader.Close();
                using (var streamWriter = new StreamWriter(scriptPath))
                {
                    streamWriter.Write(sb);
                    streamWriter.Close();
                }
            }
            //Debug.Log("HUD widget script generation completed");
        }
Exemplo n.º 24
0
        private static void CreateNodeScript(string name, Playflock.Log.NodeType nodeType)
        {
            var unit = new CodeCompileUnit();
            //add namespace
            var importsNamespace = new CodeNamespace
            {
                Imports =
                {
                    new CodeNamespaceImport("UnityEngine"),
                    new CodeNamespaceImport("UnityEngine.UI"),
                    new CodeNamespaceImport("System.Collections")
                }
            };
            var playflockNamespace = new CodeNamespace("Playflock.Log.Node");

            unit.Namespaces.Add(importsNamespace);
            unit.Namespaces.Add(playflockNamespace);
            // add class
            var declarationClass = new CodeTypeDeclaration(name + "Node");

            declarationClass.IsClass = true;
            //inherits from
            declarationClass.BaseTypes.Add("HUDNode");
            //Methods
            var baseMethod = new CodeMemberMethod();

            switch (nodeType)
            {
            case Playflock.Log.NodeType.Toggle:
                baseMethod.Name = "OnToggle";
                baseMethod.Parameters.Add(new CodeParameterDeclarationExpression("System.Boolean", "isOn"));
                baseMethod.Attributes = MemberAttributes.Override | MemberAttributes.Public;
                baseMethod.Statements.Add(new CodeSnippetStatement("\t\t\tbase.OnToggle( isOn );"));
                break;

            case Playflock.Log.NodeType.Button:
                baseMethod.Name       = "OnClick";
                baseMethod.Attributes = MemberAttributes.Override | MemberAttributes.Public;
                baseMethod.Statements.Add(new CodeSnippetStatement("\t\t\tbase.OnClick();"));
                break;
            }
            //Methods
            declarationClass.Members.Add(baseMethod);
            playflockNamespace.Types.Add(declarationClass);

            var provider   = (CSharpCodeProvider)CodeDomProvider.CreateProvider("csharp");
            var scriptPath = _rootPath + _nodeFolder + "/" + name + "Node.cs";

            using (var sw = new StreamWriter(scriptPath, false))
            {
                var tw = new IndentedTextWriter(sw, "    ");
                //generate source code
                var options = new CodeGeneratorOptions();
                options.BracingStyle             = "C";
                options.BlankLinesBetweenMembers = true;
                provider.GenerateCodeFromCompileUnit(unit, tw, options);
                tw.Close();
                sw.Close();
            }

            //delete autogenerated summary (optional)
            using (var Reader = new StreamReader(scriptPath))
            {
                var fileContent = Reader.ReadToEnd();

                var sb = new StringBuilder(fileContent);
                sb.Remove(0, 420);
                Reader.Close();
                using (var streamWriter = new StreamWriter(scriptPath))
                {
                    streamWriter.Write(sb);
                    streamWriter.Close();
                }
            }
            //Debug.Log("HUD node script generation completed");
        }
Exemplo n.º 25
0
 /// <devdoc>
 ///    <para>
 ///       Outputs the language specific representaion of the CodeDom tree
 ///       refered to by codeNamespace, into writer.
 ///    </para>
 /// </devdoc>
 public virtual void GenerateCodeFromNamespace(CodeNamespace codeNamespace, TextWriter writer, CodeGeneratorOptions options)
 {
     CreateGeneratorHelper().GenerateCodeFromNamespace(codeNamespace, writer, options);
 }
Exemplo n.º 26
0
        public static string Convert(string str)
        {
            CodeMemberField field = new CodeMemberField(typeof(string), "a");

            field.InitExpression = new CodePrimitiveExpression(str);

            CodeTypeDeclaration type = new CodeTypeDeclaration("C");

            type.Members.Add(field);

            CodeNamespace ns = new CodeNamespace();

            ns.Types.Add(type);

            CodeCompileUnit compileUnit = new CodeCompileUnit();

            compileUnit.Namespaces.Add(ns);

            MemoryStream ms = new MemoryStream();

            using (StreamWriter sourceWriter = new StreamWriter(ms))
            {
                CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
                provider.GenerateCodeFromCompileUnit(compileUnit, sourceWriter, new CodeGeneratorOptions());
            }

            string ostr = "";

            using (StreamReader sr = new StreamReader(new MemoryStream(ms.ToArray())))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    if (line.TrimStart().StartsWith("//"))
                    {
                        continue;
                    }

                    int beg = line.IndexOf('"');
                    int end = line.LastIndexOf('"');

                    if (beg >= 0)
                    {
                        if ((end < 0) || (beg >= end))
                        {
                            throw new Exception();
                        }

                        int beg2 = (ostr.Length == 0) ? beg : beg + 1;

                        ostr += line.Substring(beg2, end - beg2);
                    }
                }
            }

            if (ostr.Length == 0)
            {
                throw new Exception();
            }

            return(ostr + "\"");
        }
Exemplo n.º 27
0
        /// <summary>
        /// Generates the specified Source File in the received Project with the options
        /// provided and gets the Namespace ready to add code in it.
        /// </summary>
        /// <param name="targetProject">Project where the Source File is going to be placed.</param>
        /// <param name="targetProjectFolder">Project folder where the source file is going to be placed.
        /// Null indicates to place the source file as child of targetProject.</param>
        /// <param name="sourceFileName">Source File name to use.</param>
        /// <param name="sourceFileHeaderComment">Source File Header Comment (optional).</param>
        /// <param name="sourceNamespace">Namespace used in the Source File.</param>
        /// <param name="isServiceReady">Specifies if it is Service-Ready (serialization is going to be used).</param>
        /// <param name="sourceFileItem">(out parameter) Source File ProjectItem.</param>
        /// <returns></returns>
        public static CodeNamespace GenerateSourceAndGetNamespace(Project targetProject, ProjectItem targetProjectFolder,
                                                                  string sourceFileName, string sourceFileHeaderComment, string sourceNamespace,
                                                                  bool isServiceReady, out ProjectItem sourceFileItem)
        {
            // Validate source file name
            if (sourceFileName.EndsWith(Resources.CSharpFileExtension) == false)
            {
                sourceFileName += Resources.CSharpFileExtension;
            }

            // Validate source file header comment
            if (string.IsNullOrWhiteSpace(sourceFileHeaderComment) == false)
            {
                if (sourceFileHeaderComment.IndexOf("*/") >= 0)
                {
                    throw new ApplicationException(Resources.Error_HeaderCommentInvalidChars);
                }
            }

            // ProjectItems collection where to place the source file
            ProjectItems projectItems = targetProject.ProjectItems;

            if (targetProjectFolder != null)
            {
                // Place inside received project folder
                projectItems = targetProjectFolder.ProjectItems;
            }

            // Properties collection of the target
            EnvDTE.Properties targetProperties = targetProject.Properties;
            if (targetProjectFolder != null)
            {
                targetProperties = targetProjectFolder.Properties;
            }

            // Source file
            sourceFileItem = null;

            #region If source file exists in the target, clear it and get the reference
            foreach (ProjectItem projItem in projectItems)
            {
                string projItemFileName = projItem.Properties.Item(Resources.ProjectItem_FileName).Value.ToString();

                if (sourceFileName.ToLower() == projItemFileName.ToLower())
                {
                    // Source file already exists
                    sourceFileItem = projItem;

                    if (sourceFileItem.FileCodeModel.CodeElements != null &&
                        sourceFileItem.FileCodeModel.CodeElements.Count > 0)
                    {
                        // Clear source file

                        CodeElement firstElement = sourceFileItem.FileCodeModel.CodeElements.Item(1);

                        CodeElement lastElement = sourceFileItem.FileCodeModel.CodeElements.Item(
                            sourceFileItem.FileCodeModel.CodeElements.Count);

                        EditPoint startPoint = firstElement.StartPoint.CreateEditPoint();
                        EditPoint endPoint   = lastElement.EndPoint.CreateEditPoint();

                        while (startPoint.AtStartOfDocument != true)
                        {
                            startPoint.LineUp();
                        }

                        while (endPoint.AtEndOfDocument != true)
                        {
                            endPoint.LineDown();
                        }

                        startPoint.Delete(endPoint);
                    }

                    break;
                }
            }
            #endregion

            #region If source file NOT exists in the target, create it and get the reference
            if (sourceFileItem == null)
            {
                // New source file, get target path
                string targetPath = targetProperties.Item(Resources.Properties_LocalPath).Value.ToString();

                // Check if the new source file already exists in the file system (and it is not added to the solution)
                if (File.Exists(targetPath + sourceFileName))
                {
                    // Rename the existent source file
                    string backupSourceFileName = (sourceFileName + Resources.BackupFileExtension);
                    File.Move((targetPath + sourceFileName), (targetPath + backupSourceFileName));

                    // Add warning
                    VisualStudioHelper.AddToErrorList(TaskErrorCategory.Warning,
                                                      string.Format(Resources.Warning_SourceFileAlreadyExists, sourceFileName, backupSourceFileName),
                                                      targetProject, sourceFileName, null, null);
                }

                // Add source file to target
                sourceFileItem = projectItems.AddFromTemplate(TemplateClass.FilePath, sourceFileName);
            }
            #endregion

            #region Generate imports
            var importList = new List <SourceCodeImport>();
            importList.Add(new SourceCodeImport(Resources.NamespaceSystem));
            importList.Add(new SourceCodeImport(Resources.NamespaceSystemCollectionsGeneric));
            importList.Add(new SourceCodeImport(Resources.NamespaceSystemText));

            if (isServiceReady)
            {
                importList.Add(new SourceCodeImport(Resources.NamespaceSystemRuntimeSerialization));
            }

            importList = importList.OrderBy(d => d.ImportNamespace).ToList();
            #endregion Generate imports

            // Add imports to the source code
            VisualStudioHelper.AddImportsToSourceCode(ref sourceFileItem, importList);

            // Get Source file code start
            EditPoint objEditPoint = sourceFileItem.FileCodeModel.CodeElements.Item(1).StartPoint.CreateEditPoint();
            objEditPoint.StartOfDocument();

            // Add header comment
            if (string.IsNullOrWhiteSpace(sourceFileHeaderComment) == false)
            {
                sourceFileHeaderComment = (Environment.NewLine + sourceFileHeaderComment + Environment.NewLine);

                objEditPoint.Insert(
                    string.Format(Resources.CSharpCommentMultiline, sourceFileHeaderComment) +
                    Environment.NewLine);
            }

            // Add EntitiesToDTOs signature
            string timestamp = DateTime.Now.ToString("yyyy/MM/dd - HH:mm:ss");
            objEditPoint.Insert(string.Format(Resources.EntitiesToDTOsSignature, AssemblyHelper.Version, timestamp));
            objEditPoint.Insert(Environment.NewLine);

            // Add blank line before source file namespace
            objEditPoint.EndOfDocument();
            objEditPoint.Insert(Environment.NewLine);

            // Add namespace
            CodeNamespace objNamespace = sourceFileItem.FileCodeModel
                                         .AddNamespace(sourceNamespace, AppConstants.PLACE_AT_THE_END);

            return(objNamespace);
        }
 public virtual void GenerateCodeFromNamespace(CodeNamespace codeNamespace, TextWriter writer, CodeGeneratorOptions options)
 {
     ICodeGenerator cg = CreateGenerator();
     if (cg == null)
         throw GetNotImplemented();
     cg.GenerateCodeFromNamespace(codeNamespace, 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);
            }
        }
    }
 protected override void GenerateNamespaceEnd(CodeNamespace e)
 {
     Output.WriteLine("[CodeNamespaceEnd: {0}]", e.ToString());
 }
Exemplo n.º 31
0
        /// <summary>
        /// Splits the given code compile unit in multiple compile units to separate each type in its own compile unit
        /// </summary>
        /// <param name="unit">The code compile unit</param>
        /// <returns>A dictionary of full type names and code compile units that only contain this single type</returns>
        public static IDictionary <string, CodeCompileUnit> SplitCompileUnit(CodeCompileUnit unit)
        {
            var           dict            = new Dictionary <string, CodeCompileUnit>();
            string        baseNamespace   = unit.Namespaces.Cast <CodeNamespace>().Where(n => !string.IsNullOrEmpty(n.Name)).First().Name;
            CodeNamespace globalNamespace = null;

            foreach (CodeNamespace ns in unit.Namespaces)
            {
                if (string.IsNullOrEmpty(ns.Name))
                {
                    globalNamespace = ns;
                    continue;
                }
                if (ns.Name.StartsWith(baseNamespace))
                {
                    continue;
                }
                if (baseNamespace.StartsWith(ns.Name))
                {
                    baseNamespace = ns.Name;
                }
                else
                {
                    var commonLength = 0;
                    while (true)
                    {
                        var idx1 = baseNamespace.IndexOf('.', commonLength + 1);
                        var idx2 = ns.Name.IndexOf('.', commonLength + 1);
                        if (idx1 == -1 || idx2 == -1 || idx1 != idx2)
                        {
                            break;
                        }
                        idx1 -= commonLength;
                        if (baseNamespace.Substring(commonLength, idx1) != ns.Name.Substring(commonLength, idx1))
                        {
                            break;
                        }
                        commonLength = idx2;
                    }
                    baseNamespace = baseNamespace.Substring(0, commonLength);
                }
            }
            int offset = baseNamespace.Length;

            if (offset != 0)
            {
                offset++;
            }
            foreach (CodeNamespace ns in unit.Namespaces)
            {
                if (string.IsNullOrEmpty(ns.Name))
                {
                    continue;
                }
                foreach (CodeTypeDeclaration type in ns.Types)
                {
                    var newUnit = new CodeCompileUnit();
                    if (globalNamespace != null)
                    {
                        newUnit.Namespaces.Add(globalNamespace);
                    }
                    var newNamespace = new CodeNamespace();
                    newNamespace.Name = ns.Name;
                    for (int i = 0; i < ns.Imports.Count; i++)
                    {
                        newNamespace.Imports.Add(ns.Imports[i]);
                    }
                    newUnit.Namespaces.Add(newNamespace);
                    newNamespace.Types.Add(type);
                    string fileName = string.Empty;
                    if (ns.Name != baseNamespace)
                    {
                        fileName = ns.Name.Substring(offset).Replace('.', '\\') + "\\";
                    }
                    dict.Add(fileName + type.Name, newUnit);
                }
            }
            return(dict);
        }
Exemplo n.º 32
0
        /// <summary>
        /// 得到WSDL信息,生成本地代理类并编译为DLL
        /// </summary>
        private void CreateServiceAssembly()
        {
            if (this.checkCache())
            {
                this.initTypeName();
                return;
            }
            if (string.IsNullOrEmpty(this._wsdlUrl))
            {
                return;
            }
            try
            {
                //使用WebClient下载WSDL信息
                WebClient web = new WebClient();

                Stream                     stream      = web.OpenRead(this._wsdlUrl);
                ServiceDescription         description = ServiceDescription.Read(stream);  //创建和格式化WSDL文档
                ServiceDescriptionImporter importer    = new ServiceDescriptionImporter(); //创建客户端代理代理类
                importer.ProtocolName          = "Soap";
                importer.Style                 = ServiceDescriptionImportStyle.Client;     //生成客户端代理
                importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;
                importer.AddServiceDescription(description, null, null);                   //添加WSDL文档
                                                                                           //使用CodeDom编译客户端代理类


                //  MISLog.GetInstance().Write(MISLog.MSG_LEVEL.FLUSH, "CodeNamespace");



                CodeNamespace   nmspace = new CodeNamespace(_assName);  //为代理类添加命名空间
                CodeCompileUnit unit    = new CodeCompileUnit();
                unit.Namespaces.Add(nmspace);
                this.checkForImports(this._wsdlUrl, importer);
                ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);
                CodeDomProvider    provider  = CodeDomProvider.CreateProvider("CSharp");
                CompilerParameters parameter = new CompilerParameters();
                parameter.ReferencedAssemblies.Add("System.dll");
                parameter.ReferencedAssemblies.Add("System.XML.dll");
                parameter.ReferencedAssemblies.Add("System.Web.Services.dll");
                parameter.ReferencedAssemblies.Add("System.Data.dll");
                parameter.GenerateExecutable      = false;
                parameter.GenerateInMemory        = false;
                parameter.IncludeDebugInformation = false;
                CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit);
                provider.Dispose();
                if (result.Errors.HasErrors)
                {
                    string errors = string.Format(@"编译错误:{0}错误!", result.Errors.Count);
                    foreach (CompilerError error in result.Errors)
                    {
                        errors += error.ErrorText;
                    }


                    //  MISLog.GetInstance().Write(MISLog.MSG_LEVEL.FLUSH, errors);
                }
                this.copyTempAssembly(result.PathToAssembly);
                this.initTypeName();
            }
            catch (Exception e)
            {
                //  MISLog.GetInstance().Write(MISLog.MSG_LEVEL.FLUSH, e.ToString());
            }
        }
Exemplo n.º 33
0
 public SoapMapCodeGenerator(CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit)
     : base(codeNamespace, codeCompileUnit)
 {
     includeArrayTypes = true;
 }
Exemplo n.º 34
0
        public void MaskingVariables()
        {
            CodeNamespace ns = new CodeNamespace("ns");
            CodeTypeDeclaration class1 = new CodeTypeDeclaration();
            class1.Name = "Class1";
            ns.Types.Add(class1);

            CodeMemberMethod cmm = new CodeMemberMethod();
            cmm.Name = "for";
            class1.Members.Add(cmm);

            cmm = new CodeMemberMethod();
            cmm.Name = "while";
            cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public;
            cmm.Statements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "for")));
            class1.Members.Add(cmm);

            class1 = new CodeTypeDeclaration();
            class1.Name = "TestMasking";
            ns.Types.Add(class1);

            cmm = new CodeMemberMethod();
            cmm.Name = "TestMasks";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i"));
            cmm.Attributes = MemberAttributes.Static | MemberAttributes.Public;
            cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("Class1"), "temp", new CodeObjectCreateExpression(new CodeTypeReference("Class1"))));
            cmm.Statements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("temp"), "while")));
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("i")));
            class1.Members.Add(cmm);

            AssertEqual(ns,
                @"Namespace ns
                  Public Class Class1
                      Private Sub [for]()
                      End Sub
                      Public Sub [while]()
                          Me.for
                      End Sub
                  End Class
                  Public Class TestMasking
                      Public Shared Function TestMasks(ByVal i As Integer) As Integer
                          Dim temp As Class1 = New Class1()
                          temp.while
                          Return i
                      End Function
                  End Class
              End Namespace");
        }
Exemplo n.º 35
0
        public async Task Name_Dotted()
        {
            CodeNamespace testObject = await GetCodeNamespaceAsync(3);

            Assert.Equal("A.B", testObject.Name);
        }
Exemplo n.º 36
0
        public async Task Name()
        {
            CodeNamespace testObject = await GetCodeNamespaceAsync(2);

            Assert.Equal("Foo", testObject.Name);
        }
Exemplo n.º 37
0
        protected virtual void processInterface(Protocol protocol)
        {
            // Create abstract class
            string protocolNameMangled = CodeGenUtil.Instance.Mangle(protocol.Name);

            var ctd = new CodeTypeDeclaration(protocolNameMangled);

            ctd.TypeAttributes = TypeAttributes.Abstract | TypeAttributes.Public;
            ctd.IsClass        = true;
            ctd.BaseTypes.Add("Avro.Specific.ISpecificProtocol");

            AddProtocolDocumentation(protocol, ctd);

            // Add static protocol field.
            var protocolField = new CodeMemberField();

            protocolField.Attributes = MemberAttributes.Private | MemberAttributes.Static | MemberAttributes.Final;
            protocolField.Name       = "protocol";
            protocolField.Type       = new CodeTypeReference("readonly Avro.Protocol");

            var cpe  = new CodePrimitiveExpression(protocol.ToString());
            var cmie = new CodeMethodInvokeExpression(
                new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(Protocol)), "Parse"),
                new CodeExpression[] { cpe });

            protocolField.InitExpression = cmie;

            ctd.Members.Add(protocolField);

            // Add overridden Protocol method.
            var property = new CodeMemberProperty();

            property.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            property.Name       = "Protocol";
            property.Type       = new CodeTypeReference("Avro.Protocol");
            property.HasGet     = true;


            property.GetStatements.Add(new CodeTypeReferenceExpression("return protocol"));
            ctd.Members.Add(property);

            //var requestMethod = CreateRequestMethod();
            //ctd.Members.Add(requestMethod);

            var requestMethod = CreateRequestMethod();
            //requestMethod.Attributes |= MemberAttributes.Override;
            var builder = new StringBuilder();

            if (protocol.Messages.Count > 0)
            {
                builder.Append("switch(messageName)\n\t\t\t{");

                foreach (var a in protocol.Messages)
                {
                    builder.Append("\n\t\t\t\tcase \"").Append(a.Key).Append("\":\n");

                    bool   unused = false;
                    string type   = getType(a.Value.Response, false, ref unused);

                    builder.Append("\t\t\t\trequestor.Request<")
                    .Append(type)
                    .Append(">(messageName, args, callback);\n");
                    builder.Append("\t\t\t\tbreak;\n");
                }

                builder.Append("\t\t\t}");
            }
            var cseGet = new CodeSnippetExpression(builder.ToString());

            requestMethod.Statements.Add(cseGet);
            ctd.Members.Add(requestMethod);

            AddMethods(protocol, false, ctd);

            string nspace = protocol.Namespace;

            if (string.IsNullOrEmpty(nspace))
            {
                throw new CodeGenException("Namespace required for enum schema " + nspace);
            }
            CodeNamespace codens = addNamespace(nspace);

            codens.Types.Add(ctd);

            // Create callback abstract class
            ctd = new CodeTypeDeclaration(protocolNameMangled + "Callback");
            ctd.TypeAttributes = TypeAttributes.Abstract | TypeAttributes.Public;
            ctd.IsClass        = true;
            ctd.BaseTypes.Add(protocolNameMangled);

            // Need to override



            AddProtocolDocumentation(protocol, ctd);

            AddMethods(protocol, true, ctd);

            codens.Types.Add(ctd);
        }
Exemplo n.º 38
0
        public async Task Members()
        {
            CodeNamespace testObject = await GetCodeNamespaceAsync("Foo");

            Assert.Equal(3, testObject.Members.Count);
        }
Exemplo n.º 39
0
        public void Indexers()
        {
            CodeNamespace nspace = new CodeNamespace("NSPC");

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

            CodeMemberField field = new CodeMemberField();
            field.Name = "PublicField";
            field.InitExpression = new CodeArrayCreateExpression(new CodeTypeReference(typeof(int)), new CodeExpression[]{
                new CodePrimitiveExpression(0), new CodePrimitiveExpression(0),new CodePrimitiveExpression(0),new CodePrimitiveExpression(0),
                new CodePrimitiveExpression(0),new CodePrimitiveExpression(0), new CodePrimitiveExpression(0)});
            field.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            field.Type = new CodeTypeReference(typeof(int[]));
            cd.Members.Add(field);

            // nonarray indexers
            CodeMemberProperty indexerProperty = new CodeMemberProperty();
            indexerProperty.Name = "Item";
            indexerProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            indexerProperty.Type = new CodeTypeReference(typeof(int));
            indexerProperty.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
            // uses array indexer
            indexerProperty.SetStatements.Add(new CodeAssignStatement(new CodeArrayIndexerExpression(
                new CodeFieldReferenceExpression(new CodeThisReferenceExpression()
                , "PublicField"), new CodeExpression[] { new CodeVariableReferenceExpression("i") }),
                new CodeVariableReferenceExpression("value")));
            indexerProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodeArrayIndexerExpression(
                new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "PublicField"),
                new CodeVariableReferenceExpression("i"))));
            cd.Members.Add(indexerProperty);

            // nonarray indexers
            indexerProperty = new CodeMemberProperty();
            indexerProperty.Name = "Item";
            indexerProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            indexerProperty.Type = new CodeTypeReference(typeof(int));
            indexerProperty.SetStatements.Add(new CodeAssignStatement(new CodeArrayIndexerExpression(
                new CodeFieldReferenceExpression(new CodeThisReferenceExpression()
                , "PublicField"), new CodeExpression[] { new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add,
                                                            new CodeVariableReferenceExpression("b"))}),
                new CodeVariableReferenceExpression("value")));
            indexerProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodeArrayIndexerExpression(
                new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "PublicField"),
                new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression("b")))));
            indexerProperty.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "a"));
            indexerProperty.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "b"));
            // uses array indexer

            cd.Members.Add(indexerProperty);

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

            CodeMemberMethod cmm = new CodeMemberMethod();
            cmm.Name = "TestMethod";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
            cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public;
            cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("TEST"),
                "temp", new CodeObjectCreateExpression("TEST")));
            cmm.Statements.Add(new CodeAssignStatement(new CodeIndexerExpression(
                new CodeVariableReferenceExpression("temp"), new CodeExpression[] { new CodePrimitiveExpression(1) }),
                new CodeVariableReferenceExpression("i")));
            cmm.Statements.Add(new CodeAssignStatement(new CodeIndexerExpression(
                new CodeVariableReferenceExpression("temp"), new CodeExpression[]{new CodePrimitiveExpression(2),
                new CodePrimitiveExpression(4)}),
                new CodePrimitiveExpression(83)));
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(
                new CodeIndexerExpression(new CodeVariableReferenceExpression("temp"), new CodeExpression[] { new CodePrimitiveExpression(1) }),
                CodeBinaryOperatorType.Add,
                new CodeIndexerExpression(new CodeVariableReferenceExpression("temp"), new CodeExpression[] { new CodePrimitiveExpression(2), new CodePrimitiveExpression(4) }))));

            cd.Members.Add(cmm);

            AssertEqual(nspace,
                @"Namespace NSPC
                  Public Class TEST
                      Public PublicField() As Integer = New Integer() {0, 0, 0, 0, 0, 0, 0}
                      Public Overloads Default Property Item(ByVal i As Integer) As Integer
                          Get
                              Return Me.PublicField(i)
                          End Get
                          Set
                              Me.PublicField(i) = value
                          End Set
                      End Property
                      Public Overloads Default Property Item(ByVal a As Integer, ByVal b As Integer) As Integer
                          Get
                              Return Me.PublicField((a + b))
                          End Get
                          Set
                              Me.PublicField((a + b)) = value
                          End Set
                      End Property
                  End Class
                  Public Class UseTEST

                      Public Function TestMethod(ByVal i As Integer) As Integer
                          Dim temp As TEST = New TEST()
                          temp(1) = i
                          temp(2, 4) = 83
                          Return (temp(1) + temp(2, 4))
                      End Function
                  End Class
              End Namespace");
        }
Exemplo n.º 40
0
        /// <summary>
        /// Creates a class declaration
        /// </summary>
        /// <param name="schema">record schema</param>
        /// <param name="ns">namespace</param>
        /// <returns></returns>
        protected virtual CodeTypeDeclaration processRecord(Schema schema)
        {
            RecordSchema recordSchema = schema as RecordSchema;

            if (null == recordSchema)
            {
                throw new CodeGenException("Unable to cast schema into a record");
            }

            bool isError = recordSchema.Tag == Schema.Type.Error;

            // declare the class
            var ctd = new CodeTypeDeclaration(CodeGenUtil.Instance.Mangle(recordSchema.Name));

            // ctd.BaseTypes.Add(isError ? "SpecificException" : "ISpecificRecord");

            ctd.Attributes = MemberAttributes.Public;
            ctd.IsClass    = true;
            //ctd.IsPartial = true;

            //createSchemaField(schema, ctd, isError);

            //// declare Get() to be used by the Writer classes
            //var cmmGet = new CodeMemberMethod();
            //cmmGet.Name = "Get";
            //cmmGet.Attributes = MemberAttributes.Public;
            //cmmGet.ReturnType = new CodeTypeReference("System.Object");
            //cmmGet.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "fieldPos"));
            //StringBuilder getFieldStmt = new StringBuilder("switch (fieldPos)\n\t\t\t{\n");

            //// declare Put() to be used by the Reader classes
            //var cmmPut = new CodeMemberMethod();
            //cmmPut.Name = "Put";
            //cmmPut.Attributes = MemberAttributes.Public;
            //cmmPut.ReturnType = new CodeTypeReference(typeof(void));
            //cmmPut.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "fieldPos"));
            //cmmPut.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "fieldValue"));
            //var putFieldStmt = new StringBuilder("switch (fieldPos)\n\t\t\t{\n");

            //if (isError)
            //{
            //    cmmGet.Attributes |= MemberAttributes.Override;
            //    cmmPut.Attributes |= MemberAttributes.Override;
            //}

            foreach (Field field in recordSchema.Fields)
            {
                // Determine type of field
                bool   nullibleEnum = false;
                string baseType     = getType(field.Schema, false, ref nullibleEnum);
                var    ctrfield     = new CodeTypeReference(baseType);

                // Create field
                string privFieldName = string.Concat("_", field.Name);
                var    codeField     = new CodeMemberField(ctrfield, privFieldName);
                codeField.Attributes = MemberAttributes.Private;

                // Process field documentation if it exist and add to the field
                CodeCommentStatement propertyComment = null;
                if (!string.IsNullOrEmpty(field.Documentation))
                {
                    propertyComment = createDocComment(field.Documentation);
                    if (null != propertyComment)
                    {
                        codeField.Comments.Add(propertyComment);
                    }
                }

                // Add field to class
                ctd.Members.Add(codeField);

                // Create reference to the field - this.fieldname
                var fieldRef    = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), privFieldName);
                var mangledName = CodeGenUtil.Instance.Mangle(field.Name);

                // Create field property with get and set methods
                var property = new CodeMemberProperty();
                property.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                property.Name       = mangledName.FirstCharToUpper();
                property.Type       = ctrfield;
                property.GetStatements.Add(new CodeMethodReturnStatement(fieldRef));
                property.SetStatements.Add(new CodeAssignStatement(fieldRef, new CodePropertySetValueReferenceExpression()));
                if (null != propertyComment)
                {
                    property.Comments.Add(propertyComment);
                }

                // Add field property to class
                ctd.Members.Add(property);

                if (field.Schema.Tag == Schema.Type.Union) // union
                {
                    var unionSchema = (UnionSchema)field.Schema;

                    var attr = new CodeAttributeDeclaration("Microsoft.Hadoop.Avro.AvroUnion");

                    foreach (var item in unionSchema.Schemas)
                    {
                        var name = item.Name;

                        if (name == "null")
                        {
                            name = "Microsoft.Hadoop.Avro.AvroNull";
                        }
                        else if (name == "bytes")
                        {
                            name = "byte[]";
                        }
                        else if (name == "boolean")
                        {
                            name = "bool";
                        }

                        attr.Arguments.Add(new CodeAttributeArgument(new CodeSnippetExpression(string.Format("typeof({0})", name))));
                    }

                    property.CustomAttributes.Add(attr);
                }

                // add to Get()
                //getFieldStmt.Append("\t\t\tcase ");
                //getFieldStmt.Append(field.Pos);
                //getFieldStmt.Append(": return this.");
                //getFieldStmt.Append(privFieldName);
                //getFieldStmt.Append(";\n");

                //// add to Put()
                //putFieldStmt.Append("\t\t\tcase ");
                //putFieldStmt.Append(field.Pos);
                //putFieldStmt.Append(": this.");
                //putFieldStmt.Append(privFieldName);

                //if (nullibleEnum)
                //{
                //    putFieldStmt.Append(" = fieldValue == null ? (");
                //    putFieldStmt.Append(baseType);
                //    putFieldStmt.Append(")null : (");

                //    string type = baseType.Remove(0, 16);  // remove System.Nullable<
                //    type = type.Remove(type.Length - 1);   // remove >

                //    putFieldStmt.Append(type);
                //    putFieldStmt.Append(")fieldValue; break;\n");
                //}
                //else
                //{
                //    putFieldStmt.Append(" = (");
                //    putFieldStmt.Append(baseType);
                //    putFieldStmt.Append(")fieldValue; break;\n");
                //}
            }

            //// end switch block for Get()
            //getFieldStmt.Append("\t\t\tdefault: throw new AvroRuntimeException(\"Bad index \" + fieldPos + \" in Get()\");\n\t\t\t}");
            //var cseGet = new CodeSnippetExpression(getFieldStmt.ToString());
            //cmmGet.Statements.Add(cseGet);
            //ctd.Members.Add(cmmGet);

            //// end switch block for Put()
            //putFieldStmt.Append("\t\t\tdefault: throw new AvroRuntimeException(\"Bad index \" + fieldPos + \" in Put()\");\n\t\t\t}");
            //var csePut = new CodeSnippetExpression(putFieldStmt.ToString());
            //cmmPut.Statements.Add(csePut);
            //ctd.Members.Add(cmmPut);

            string nspace = recordSchema.Namespace;

            if (string.IsNullOrEmpty(nspace))
            {
                throw new CodeGenException("Namespace required for record schema " + recordSchema.Name);
            }
            CodeNamespace codens = addNamespace(nspace);

            codens.Types.Add(ctd);

            return(ctd);
        }
Exemplo n.º 41
0
        public async Task Kind()
        {
            CodeNamespace testObject = await GetCodeNamespaceAsync("Foo");

            Assert.Equal(vsCMElement.vsCMElementNamespace, testObject.Kind);
        }
Exemplo n.º 42
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");
        }
Exemplo n.º 43
0
        public void NamespaceWithMultipleClasses()
        {
            var ns = new CodeNamespace("SomeNamespace");
            ns.Types.Add(new CodeTypeDeclaration("PublicClass") { IsClass = true, TypeAttributes = TypeAttributes.Public });
            ns.Types.Add(new CodeTypeDeclaration("PrivateClass") { IsClass = true, TypeAttributes = TypeAttributes.NotPublic });
            ns.Types.Add(new CodeTypeDeclaration("SealedClass") { IsClass = true, TypeAttributes = TypeAttributes.Sealed });
            ns.Types.Add(new CodeTypeDeclaration("PartialClass") { IsClass = true, IsPartial = true });
            ns.Types.Add(new CodeTypeDeclaration("PartialClass") { IsClass = true, IsPartial = true });

            AssertEqual(ns,
                @"Namespace SomeNamespace
                      Public Class PublicClass
                      End Class
                      Friend Class PrivateClass
                      End Class
                      Friend NotInheritable Class SealedClass
                      End Class
                      Partial Public Class PartialClass
                      End Class
                      Partial Public Class PartialClass
                      End Class
                  End Namespace");
        }
Exemplo n.º 44
0
        public void BinaryOperators()
        {
            CodeNamespace ns = new CodeNamespace("Namespace1");
            ns.Imports.Add(new CodeNamespaceImport("System"));

            CodeTypeDeclaration class1 = new CodeTypeDeclaration();
            class1.Name = "Class1";
            class1.BaseTypes.Add(new CodeTypeReference(typeof(object)));
            ns.Types.Add(class1);

            CodeMemberMethod retMethod = new CodeMemberMethod();
            retMethod.Name = "ReturnMethod";
            retMethod.Attributes = (retMethod.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            retMethod.ReturnType = new CodeTypeReference(typeof(int));
            retMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "intInput"));

            CodeBinaryOperatorExpression cboExpression = new CodeBinaryOperatorExpression(
                new CodeBinaryOperatorExpression(
                new CodePrimitiveExpression(18),
                CodeBinaryOperatorType.Divide,
                new CodeBinaryOperatorExpression(
                new CodePrimitiveExpression(6),
                CodeBinaryOperatorType.Subtract,
                new CodePrimitiveExpression(4))),
                CodeBinaryOperatorType.Multiply,
                new CodeArgumentReferenceExpression("intInput"));

            CodeVariableDeclarationStatement variableDeclaration = null;
            variableDeclaration = new CodeVariableDeclarationStatement(typeof(int), "x1", cboExpression);

            retMethod.Statements.Add(variableDeclaration);
            retMethod.Statements.Add(
                new CodeVariableDeclarationStatement(
                typeof(int),
                "x2",
                new CodeBinaryOperatorExpression(
                new CodePrimitiveExpression(19),
                CodeBinaryOperatorType.Modulus,
                new CodePrimitiveExpression(8))));
            retMethod.Statements.Add(
                new CodeVariableDeclarationStatement(
                typeof(int),
                "x3",
                new CodeBinaryOperatorExpression(
                new CodeBinaryOperatorExpression(
                new CodePrimitiveExpression(15),
                CodeBinaryOperatorType.BitwiseAnd,
                new CodePrimitiveExpression(35)),
                CodeBinaryOperatorType.BitwiseOr,
                new CodePrimitiveExpression(129))));
            retMethod.Statements.Add(
                new CodeVariableDeclarationStatement(
                typeof(int),
                "x4",
                new CodePrimitiveExpression(0)));
            retMethod.Statements.Add(
                new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x2"),
                CodeBinaryOperatorType.ValueEquality,
                new CodePrimitiveExpression(3)),
                CodeBinaryOperatorType.BooleanOr,
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x3"),
                CodeBinaryOperatorType.LessThan,
                new CodePrimitiveExpression(129))),
                new CodeStatement[] { CreateVariableIncrementExpression("x4", 1) },
                new CodeStatement[] { CreateVariableIncrementExpression("x4", 2) }));
            retMethod.Statements.Add(
                new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x2"),
                CodeBinaryOperatorType.GreaterThan,
                new CodePrimitiveExpression(-1)),
                CodeBinaryOperatorType.BooleanAnd,
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x3"),
                CodeBinaryOperatorType.GreaterThanOrEqual,
                new CodePrimitiveExpression(5000))),
                new CodeStatement[] { CreateVariableIncrementExpression("x4", 4) },
                new CodeStatement[] { CreateVariableIncrementExpression("x4", 8) }));
            retMethod.Statements.Add(
                new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x2"),
                CodeBinaryOperatorType.LessThanOrEqual,
                new CodePrimitiveExpression(3)),
                CodeBinaryOperatorType.BooleanAnd,
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x3"),
                CodeBinaryOperatorType.IdentityInequality,
                new CodePrimitiveExpression(1))),
                new CodeStatement[] { CreateVariableIncrementExpression("x4", 16) },
                new CodeStatement[] { CreateVariableIncrementExpression("x4", 32) }));
            retMethod.Statements.Add(
                new CodeMethodReturnStatement(
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x1"),
                CodeBinaryOperatorType.Add,
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x2"),
                CodeBinaryOperatorType.Add,
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x3"),
                CodeBinaryOperatorType.Add,
                new CodeVariableReferenceExpression("x4"))))));
            class1.Members.Add(retMethod);

            retMethod = new CodeMemberMethod();
            retMethod.Name = "SecondReturnMethod";
            retMethod.Attributes = (retMethod.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            retMethod.ReturnType = new CodeTypeReference(typeof(int));
            retMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "intInput"));

            retMethod.Statements.Add(new CodeCommentStatement("To test CodeBinaryOperatorType.IdentiEquality operator"));
            retMethod.Statements.Add(
                new CodeConditionStatement(
                new CodeBinaryOperatorExpression(new CodeCastExpression("Object",
                new CodeVariableReferenceExpression("intInput")),
                CodeBinaryOperatorType.IdentityEquality, new CodeCastExpression("Object",
                new CodePrimitiveExpression(5))),
                new CodeStatement[] { new CodeMethodReturnStatement(new
                CodePrimitiveExpression(5)) }, new CodeStatement[] { new
                CodeMethodReturnStatement(new CodePrimitiveExpression(4))}));
            class1.Members.Add(retMethod);

            AssertEqual(ns,
                @"Imports System

                  Namespace Namespace1

                      Public Class Class1
                          Inherits Object

                          Public Function ReturnMethod(ByVal intInput As Integer) As Integer
                              Dim x1 As Integer = ((18  _
                                          / (6 - 4))  _
                                          * intInput)
                              Dim x2 As Integer = (19 Mod 8)
                              Dim x3 As Integer = ((15 And 35)  _
                                          Or 129)
                              Dim x4 As Integer = 0
                              If ((x2 = 3)  _
                                          OrElse (x3 < 129)) Then
                                  x4 = (x4 + 1)
                              Else
                                  x4 = (x4 + 2)
                              End If
                              If ((x2 > -1)  _
                                          AndAlso (x3 >= 5000)) Then
                                  x4 = (x4 + 4)
                              Else
                                  x4 = (x4 + 8)
                              End If
                              If ((x2 <= 3)  _
                                          AndAlso (x3 <> 1)) Then
                                  x4 = (x4 + 16)
                              Else
                                  x4 = (x4 + 32)
                              End If
                              Return (x1  _
                                          + (x2  _
                                          + (x3 + x4)))
                          End Function

                          Public Function SecondReturnMethod(ByVal intInput As Integer) As Integer
                              'To test CodeBinaryOperatorType.IdentiEquality operator
                              If (CType(intInput,[Object]) Is CType(5,[Object])) Then
                                  Return 5
                              Else
                                  Return 4
                              End If
                          End Function
                      End Class
                  End Namespace");
        }
Exemplo n.º 45
0
        /// <summary>
        /// 动态调用web服务
        /// </summary>
        /// <param name="url">WSDL服务地址</param>
        /// <param name="classname">服务接口类名</param>
        /// <param name="methodname">方法名</param>
        /// <param name="args">参数值</param>
        /// <returns></returns>
        public static object InvokeWebService(string url, string classname, string methodname, object[] args)
        {
            string @namespace = "WebService.DynamicWebCalling";

            if ((classname == null) || (classname == ""))
            {
                classname = WebServiceHelper.GetWsClassName(url);
            }
            try
            {
                //获取WSDL
                WebClient wc     = new WebClient();
                Stream    stream = wc.OpenRead(url + "?WSDL");
                System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream);
                //注意classname一定要赋值获取
                classname = sd.Services[0].Name;

                ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                CodeNamespace cn = new CodeNamespace(@namespace);

                //生成客户端代理类代码
                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);
                CSharpCodeProvider icc = new CSharpCodeProvider();


                //设定编译参数
                CompilerParameters cplist = new CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory   = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");
                //编译代理类
                CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }
                //生成代理实例,并调用方法
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                string newpath = System.Environment.CurrentDirectory + "\\" + getMd5Sum(url) + ".dll";
                //if (!File.Exists(newpath))
                //{
                //    File.Copy(cr.PathToAssembly, System.Environment.CurrentDirectory + "\\" + getMd5Sum(url) + ".dll");
                //}

                Type   t   = assembly.GetType(@namespace + "." + classname, true, true);
                object obj = Activator.CreateInstance(t);
                System.Reflection.MethodInfo mi = t.GetMethod(methodname);
                return(mi.Invoke(obj, args));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
                // return "Error:WebService调用错误!" + ex.Message;
            }
        }
Exemplo n.º 46
0
        private bool GenerateOutput()
        {
            string shortClassName, classNamespace;
            int    dot = className.LastIndexOf('.');

            if (dot >= 0)
            {
                classNamespace = className.Substring(0, dot);
                shortClassName = className.Substring(dot + 1);
            }
            else
            {
                classNamespace = null;
                shortClassName = className;
            }

            bool isPrivate = false;

            if (classModifier != null)
            {
                string publicModifier = null, privateModifier = null;
                if (typeAttributesConverter != null && typeAttributesConverter.CanConvertTo(typeof(string)))
                {
                    try {
                        publicModifier  = typeAttributesConverter.ConvertTo(TypeAttributes.Public, typeof(string)) as string;
                        privateModifier = typeAttributesConverter.ConvertTo(TypeAttributes.NotPublic, typeof(string)) as string;
                    } catch (NotSupportedException) {
                    }
                }

                if (string.Equals(classModifier, privateModifier, StringComparison.OrdinalIgnoreCase))
                {
                    isPrivate = true;
                }
                else if (!string.Equals(classModifier, publicModifier, StringComparison.OrdinalIgnoreCase))
                {
                    LogError(classModifierLineNumber, 1503, "Language '" + Language + "' does not support x:ClassModifier '" + classModifier + "'.");
                    return(false);
                }
            }

            var unit = new CodeCompileUnit();

            var ns = new CodeNamespace(classNamespace);

            unit.Namespaces.Add(ns);
            foreach (string importName in importedNamespaces)
            {
                var import = new CodeNamespaceImport(importName);
                if (importedNamespacesLineNumber != 0)
                {
                    import.LinePragma = new CodeLinePragma(InputFileName.ItemSpec, importedNamespacesLineNumber);
                }
                ns.Imports.Add(import);
            }
            var type = new CodeTypeDeclaration {
                Name      = shortClassName,
                IsPartial = true,
                BaseTypes = { typeof(ILambdaConverterProvider) }
            };

            ns.Types.Add(type);
            if (isPrivate)
            {
                type.TypeAttributes &= ~TypeAttributes.Public;
            }

            var method = new CodeMemberMethod {
                Name = "GetConverterForLambda",
                PrivateImplementationType = new CodeTypeReference(typeof(ILambdaConverterProvider)),
                ReturnType = new CodeTypeReference(typeof(LambdaConverter)),
                Parameters =
                {
                    new CodeParameterDeclarationExpression
                    {
                        Name = "lambda__",
                        Type = new CodeTypeReference(typeof(string))
                    }
                },
                CustomAttributes =
                {
                    new CodeAttributeDeclaration(new CodeTypeReference(typeof(GeneratedCodeAttribute)))
                    {
                        Arguments =
                        {
                            new CodeAttributeArgument(new CodePrimitiveExpression(ToolName)),
                            new CodeAttributeArgument(new CodePrimitiveExpression(typeof(ExtractLambdasFromXaml).Assembly.GetName().Version.ToString()))
                        }
                    }
                }
            };

            type.Members.Add(method);

            foreach (var lambda in lambdas)
            {
                var cond = new CodeConditionStatement {
                    Condition = new CodeBinaryOperatorExpression {
                        Operator = CodeBinaryOperatorType.ValueEquality,
                        Left     = new CodeArgumentReferenceExpression("lambda__"),
                        Right    = new CodePrimitiveExpression(lambda.Code)
                    },
                    TrueStatements =
                    {
                        new CodeMethodReturnStatement
                        {
                            Expression = new CodeMethodInvokeExpression
                            {
                                Method = new CodeMethodReferenceExpression
                                {
                                    TargetObject = new CodeTypeReferenceExpression(typeof(LambdaConverter)),
                                    MethodName   = "Create"
                                },
                                Parameters =
                                {
                                    new CodeSnippetExpression(lambda.Code)
                                }
                            },
                            LinePragma = new CodeLinePragma
                            {
                                FileName   = InputFileName.ItemSpec,
                                LineNumber = lambda.LineNumber
                            }
                        }
                    }
                };

                method.Statements.Add(cond);
            }

            method.Statements.Add(
                new CodeThrowExceptionStatement {
                ToThrow = new CodeObjectCreateExpression {
                    CreateType = new CodeTypeReference(typeof(ArgumentOutOfRangeException)),
                    Parameters =
                    {
                        new CodePrimitiveExpression("lambda__")
                    }
                }
            });

            try {
                using (var writer = File.CreateText(OutputFileName.ItemSpec)) {
                    var options = new CodeGeneratorOptions();
                    codeDomProvider.GenerateCodeFromCompileUnit(unit, writer, options);
                }
            } catch (IOException ex) {
                LogError(2002, ex.Message);
                return(false);
            }

            return(true);
        }
Exemplo n.º 47
0
        public void ForLoops()
        {
            CodeNamespace nspace = new CodeNamespace("NSPC");

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

            CodeMemberMethod cmm = new CodeMemberMethod();
            cmm.Name = "TestBasicIterationStatement";
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(int)), "i"));
            cmm.Statements.Add(new CodeIterationStatement(new CodeAssignStatement(new
                CodeVariableReferenceExpression("i"), new CodePrimitiveExpression(1)),
                new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
                CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(8)),
                new CodeAssignStatement(new CodeVariableReferenceExpression("i"),
                new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Multiply,
                new CodePrimitiveExpression(2)))));
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("i")));
            class1.Members.Add(cmm);

            cmm = new CodeMemberMethod();
            cmm.Name = "TestComplexIterationStatement";
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(int)), "i"));
            cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(int)), "a", new CodePrimitiveExpression(7)));
            cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(int)), "b"));
            cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(int)), "c", new CodePrimitiveExpression(9)));
            cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(int)), "d", new CodePrimitiveExpression(2)));
            CodeIterationStatement iteration = new CodeIterationStatement();
            iteration.IncrementStatement = new CodeAssignStatement(new CodeVariableReferenceExpression("i"),
                new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add,
                new CodePrimitiveExpression(1)));
            iteration.InitStatement = new CodeAssignStatement(new CodeVariableReferenceExpression("i"), new
                CodePrimitiveExpression(0));
            iteration.TestExpression = (new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
                CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(2)));
            CodeConditionStatement secondIf = new CodeConditionStatement(new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("c"), CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(10)),
                new CodeAssignStatement(new CodeVariableReferenceExpression("d"), new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("d"), CodeBinaryOperatorType.Subtract, new CodePrimitiveExpression(1))));

            CodeIterationStatement secondFor = new CodeIterationStatement();
            secondFor.Statements.Add(secondIf);
            secondFor.IncrementStatement = new CodeAssignStatement(new CodeVariableReferenceExpression("b"),
                new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("b"), CodeBinaryOperatorType.Add,
                new CodePrimitiveExpression(1)));
            secondFor.InitStatement = new CodeAssignStatement(new CodeVariableReferenceExpression("b"), new
                CodePrimitiveExpression(0));
            secondFor.TestExpression = (new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("b"),
                CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(2)));
            secondFor.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("d"),
                new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("d"), CodeBinaryOperatorType.Multiply,
                new CodePrimitiveExpression(2))));

            CodeConditionStatement firstIf = new CodeConditionStatement();
            firstIf.Condition = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.LessThan,
                new CodePrimitiveExpression(16));
            firstIf.TrueStatements.Add(secondFor);

            iteration.Statements.Add(firstIf);
            cmm.Statements.Add(iteration);
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("d")));
            class1.Members.Add(cmm);

            AssertEqual(nspace,
                @"Namespace NSPC
                  Public Class ClassWithMethod
                      Public Shared Function TestBasicIterationStatement() As Integer
                          Dim i As Integer
                          i = 1
                          Do While (i < 8)
                              i = (i * 2)
                          Loop
                          Return i
                      End Function
                      Public Shared Function TestComplexIterationStatement() As Integer
                          Dim i As Integer
                          Dim a As Integer = 7
                          Dim b As Integer
                          Dim c As Integer = 9
                          Dim d As Integer = 2
                          i = 0
                          Do While (i < 2)
                              If (a < 16) Then
                                  b = 0
                                  Do While (b < 2)
                                      If (c < 10) Then
                                          d = (d - 1)
                                      End If
                                      d = (d * 2)
                                      b = (b + 1)
                                  Loop
                              End If
                              i = (i + 1)
                          Loop
                          Return d
                      End Function
                  End Class
              End Namespace");
        }
Exemplo n.º 48
0
        /// <summary>
        /// 获取实例对象
        /// </summary>
        /// <param name="url">服务地址</param>
        /// <param name="classname">类名</param>
        /// <returns>返回结果</returns>
        public static object GetClassInstance(string url, string classname)
        {
            string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";

            if ((classname == null) || (classname == ""))
            {
                classname = WebServiceHelper.GetWsClassName(url);
            }

            try
            {
                //获取WSDL
                WebClient wc = new WebClient();

                wc.Credentials = new NetworkCredential("guest", "123");

                Stream                     stream = wc.OpenRead(url + "?WSDL");
                ServiceDescription         sd     = ServiceDescription.Read(stream);
                ServiceDescriptionImporter sdi    = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                CodeNamespace cn = new CodeNamespace(@namespace);



                //生成客户端代理类代码
                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);
                CSharpCodeProvider csc = new CSharpCodeProvider();
                //ICodeCompiler icc = csc.CreateCompiler();

                //设定编译参数
                CompilerParameters cplist = new CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory   = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");

                //编译代理类
                CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }

                //生成代理实例,并调用方法
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Type   t   = assembly.GetType(@namespace + "." + classname, true, true);
                object obj = Activator.CreateInstance(t);

                return(obj);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
        }
Exemplo n.º 49
0
        public void GlobalKeyword()
        {
            CodeNamespace ns = new CodeNamespace("Foo");
            ns.Comments.Add(new CodeCommentStatement("Foo namespace"));

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

            string fieldName1 = "_verifyGlobalGeneration1";
            CodeMemberField field = new CodeMemberField();
            field.Name = fieldName1;
            field.Type = new CodeTypeReference(typeof(int), CodeTypeReferenceOptions.GlobalReference);
            field.Attributes = MemberAttributes.Public;
            field.InitExpression = new CodePrimitiveExpression(int.MaxValue);
            cd.Members.Add(field);

            string fieldName2 = "_verifyGlobalGeneration2";
            CodeMemberField field2 = new CodeMemberField();
            field2.Name = fieldName2;
            CodeTypeReference typeRef = new CodeTypeReference("System.Nullable", CodeTypeReferenceOptions.GlobalReference);
            typeRef.TypeArguments.Add(new CodeTypeReference(typeof(int), CodeTypeReferenceOptions.GlobalReference));
            field2.Type = typeRef;
            field2.InitExpression = new CodePrimitiveExpression(0);
            cd.Members.Add(field2);

            CodeMemberMethod method1 = new CodeMemberMethod();
            method1.Name = "TestMethod01";
            method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public | MemberAttributes.Static;
            method1.ReturnType = new CodeTypeReference(typeof(int));
            method1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(int.MaxValue)));
            cd.Members.Add(method1);

            CodeMemberMethod method2 = new CodeMemberMethod();
            method2.Name = "TestMethod02";
            method2.Attributes = (method2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            method2.ReturnType = new CodeTypeReference(typeof(int));
            method2.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "iReturn"));

            CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression(
                                              new CodeMethodReferenceExpression(
                                              new CodeTypeReferenceExpression(new CodeTypeReference("Foo.Foo", CodeTypeReferenceOptions.GlobalReference)), "TestMethod01"));
            CodeAssignStatement cas = new CodeAssignStatement(new CodeVariableReferenceExpression("iReturn"), cmie);
            method2.Statements.Add(cas);
            method2.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("iReturn")));
            cd.Members.Add(method2);

            CodeMemberMethod method3 = new CodeMemberMethod();
            method3.Name = "TestMethod03";
            method3.Attributes = (method3.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            method3.ReturnType = new CodeTypeReference(typeof(int));
            method3.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "iReturn"));
            CodeTypeReferenceOptions ctro = CodeTypeReferenceOptions.GlobalReference;
            CodeTypeReference ctr = new CodeTypeReference(typeof(Math), ctro);
            cmie = new CodeMethodInvokeExpression(
                                              new CodeMethodReferenceExpression(
                                              new CodeTypeReferenceExpression(ctr), "Abs"), new CodeExpression[] { new CodePrimitiveExpression(-1) });
            cas = new CodeAssignStatement(new CodeVariableReferenceExpression("iReturn"), cmie);
            method3.Statements.Add(cas);
            method3.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("iReturn")));
            cd.Members.Add(method3);

            CodeMemberProperty property = new CodeMemberProperty();
            property.Name = "GlobalTestProperty1";
            property.Type = new CodeTypeReference(typeof(int));
            property.Attributes = (property.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            property.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression(fieldName1)));
            property.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(fieldName1), new CodeVariableReferenceExpression("value")));
            cd.Members.Add(property);

            CodeMemberProperty property2 = new CodeMemberProperty();
            property2.Name = "GlobalTestProperty2";
            property2.Type = typeRef;
            property2.Attributes = (property.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            property2.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression(fieldName2)));
            property2.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(fieldName2), new CodeVariableReferenceExpression("value")));
            cd.Members.Add(property2);

            AssertEqual(ns,
                @"'Foo namespace
                  Namespace Foo
                      Public Class Foo
                          Public _verifyGlobalGeneration1 As Integer = 2147483647
                          Private _verifyGlobalGeneration2 As Global.System.Nullable(Of Integer) = 0
                          Public Property GlobalTestProperty1() As Integer
                              Get
                                  Return _verifyGlobalGeneration1
                              End Get
                              Set
                                  _verifyGlobalGeneration1 = value
                              End Set
                          End Property
                          Public Property GlobalTestProperty2() As Global.System.Nullable(Of Integer)
                              Get
                                  Return _verifyGlobalGeneration2
                              End Get
                              Set
                                  _verifyGlobalGeneration2 = value
                              End Set
                          End Property
                          Public Shared Function TestMethod01() As Integer
                              Return 2147483647
                          End Function
                          Public Function TestMethod02() As Integer
                              Dim iReturn As Integer
                              iReturn = Global.Foo.Foo.TestMethod01
                              Return iReturn
                          End Function
                          Public Function TestMethod03() As Integer
                              Dim iReturn As Integer
                              iReturn = Global.System.Math.Abs(-1)
                              Return iReturn
                          End Function
                      End Class
                  End Namespace");
        }
Exemplo n.º 50
0
        /// <summary>
        /// 动态调用web服务
        /// </summary>
        /// <param name="url">WSDL服务地址</param>
        /// <param name="classname">类名</param>
        /// <param name="methodname">方法名</param>
        /// <param name="args">参数</param>
        /// <returns></returns>
        public static object InvokeWebService(string url, string classname, string methodname, Dictionary <string, object> args)
        {
            string @namespace = "";

            if ((classname == null) || (classname == ""))
            {
                classname = GetWsClassName(url);
            }
            try
            { //获取WSDL
                var wc     = new WebClient();
                var stream = wc.OpenRead(url + "?WSDL");
                var sd     = ServiceDescription.Read(stream);
                var sdi    = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                var cn = new CodeNamespace(@namespace);
                //生成客户端代理类代码
                var ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);
                var icc = new CSharpCodeProvider();
                //设定编译参数
                var cplist = new CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory   = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");
                //编译代理类
                var cr = icc.CompileAssemblyFromDom(cplist, ccu);
                if (cr.Errors.HasErrors)
                {
                    var sb = new StringBuilder();
                    foreach (CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce);
                        sb.Append(Environment.NewLine);
                    }
                    throw new System.Exception(sb.ToString());
                }
                //生成代理实例,并调用方法
                var assembly   = cr.CompiledAssembly;
                var t          = assembly.GetType(@namespace + "." + classname, true, true);
                var service    = Activator.CreateInstance(t);
                var methodInfo = t.GetMethod(methodname);
                var paramsInfo = methodInfo.GetParameters();
                if (paramsInfo.Length != args.Count)
                {
                    throw new System.Exception("参数个数不匹配!");
                }
                var obj = new List <object>();
                for (int i = 0; i < paramsInfo.Length; i++)
                {
                    obj.Add(CoralConvert.Convert(args[paramsInfo[i].Name], paramsInfo[i].ParameterType));
                }
                return(methodInfo.Invoke(service, obj.ToArray()));
            }
            catch (System.Exception ex)
            {
                throw new System.Exception(ex.Message, new System.Exception(ex.StackTrace));
            }
        }
Exemplo n.º 51
0
        public void GenericTypesAndConstraints()
        {
            CodeNamespace ns = new CodeNamespace("NS");
            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));

            CodeTypeDeclaration class1 = new CodeTypeDeclaration();
            class1.Name = "MyDictionary";
            class1.BaseTypes.Add(new CodeTypeReference("Dictionary", new CodeTypeReference[] { new CodeTypeReference("TKey"), new CodeTypeReference("TValue"), }));
            CodeTypeParameter kType = new CodeTypeParameter("TKey");
            kType.HasConstructorConstraint = true;
            kType.Constraints.Add(new CodeTypeReference(typeof(IComparable)));
            kType.CustomAttributes.Add(new CodeAttributeDeclaration(
                "System.ComponentModel.DescriptionAttribute", new CodeAttributeArgument(new CodePrimitiveExpression("KeyType"))));

            CodeTypeReference iComparableT = new CodeTypeReference("IComparable");
            iComparableT.TypeArguments.Add(new CodeTypeReference(kType));
            kType.Constraints.Add(iComparableT);

            CodeTypeParameter vType = new CodeTypeParameter("TValue");
            vType.Constraints.Add(new CodeTypeReference(typeof(IList<System.String>)));
            vType.CustomAttributes.Add(new CodeAttributeDeclaration(
                "System.ComponentModel.DescriptionAttribute", new CodeAttributeArgument(new CodePrimitiveExpression("ValueType"))));

            class1.TypeParameters.Add(kType);
            class1.TypeParameters.Add(vType);
            ns.Types.Add(class1);

            // Declare a generic method.
            CodeMemberMethod printMethod = new CodeMemberMethod();
            CodeTypeParameter sType = new CodeTypeParameter("S");
            sType.HasConstructorConstraint = true;
            CodeTypeParameter tType = new CodeTypeParameter("T");
            sType.HasConstructorConstraint = true;

            printMethod.Name = "Nop";
            printMethod.TypeParameters.Add(sType);
            printMethod.TypeParameters.Add(tType);
            printMethod.Attributes = MemberAttributes.Public;
            class1.Members.Add(printMethod);

            var class2 = new CodeTypeDeclaration();
            class2.Name = "Demo";

            var methodMain = new CodeEntryPointMethod();
            var myClass = new CodeTypeReference(
                "MyDictionary",
                new CodeTypeReference[] {
                    new CodeTypeReference(typeof(int)),
                    new CodeTypeReference("List",
                       new CodeTypeReference[]
                            {new CodeTypeReference("System.String") })});
            methodMain.Statements.Add(new CodeVariableDeclarationStatement(myClass, "dict", new CodeObjectCreateExpression(myClass)));
            string dictionaryTypeName = typeof(System.Collections.Generic.Dictionary<int, System.Collections.Generic.List<string>>[]).FullName;

            var dictionaryType = new CodeTypeReference(dictionaryTypeName);
            methodMain.Statements.Add(
                  new CodeVariableDeclarationStatement(dictionaryType, "dict2",
                     new CodeArrayCreateExpression(dictionaryType, new CodeExpression[1] { new CodePrimitiveExpression(null) })));

            class2.Members.Add(methodMain);
            ns.Types.Add(class2);

            AssertEqual(ns,
                @"Imports System
                  Imports System.Collections.Generic
                  Namespace NS
                      Public Class MyDictionary(Of TKey As  {System.IComparable, IComparable(Of TKey), New}, TValue As System.Collections.Generic.IList(Of String))
                          Inherits Dictionary(Of TKey, TValue)
                          Public Overridable Sub Nop(Of S As New, T)()
                          End Sub
                      End Class
                      Public Class Demo
                          Public Shared Sub Main()
                              Dim dict As MyDictionary(Of Integer, List(Of String)) = New MyDictionary(Of Integer, List(Of String))()
                              Dim dict2() As System.Collections.Generic.Dictionary(Of Integer, System.Collections.Generic.List(Of String)) = New System.Collections.Generic.Dictionary(Of Integer, System.Collections.Generic.List(Of String))() {Nothing}
                          End Sub
                      End Class
                  End Namespace");
        }
Exemplo n.º 52
0
 protected override void Visit(CodeNamespace @namespace)
 {
     VisitList(@namespace.Name);
     VisitList(@namespace.Members);
 }
Exemplo n.º 53
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");
        }
Exemplo n.º 54
0
        // SxS: This method does not take any resource name and does not expose any resources to the caller.
        // It's OK to suppress the SxS warning.
        private Assembly CompileAssembly(List <ScriptClass> scriptsForLang)
        {
            TempFileCollection      allTempFiles = _compiler.CompilerResults.TempFiles;
            CompilerErrorCollection allErrors    = _compiler.CompilerResults.Errors;
            ScriptClass             lastScript   = scriptsForLang[scriptsForLang.Count - 1];
            CodeDomProvider         provider;
            bool isVB = false;

            try
            {
                provider = lastScript.compilerInfo.CreateProvider();
            }
            catch (ConfigurationException e)
            {
                // The CodeDom provider type could not be located, or some error in machine.config
                allErrors.Add(_compiler.CreateError(lastScript.EndLineInfo, /*[XT_041]*/ SR.Xslt_ScriptCompileException, e.Message));
                return(null);
            }

#if !FEATURE_PAL // visualbasic
            isVB = provider is Microsoft.VisualBasic.VBCodeProvider;
#endif // !FEATURE_PAL

            CodeCompileUnit[]  codeUnits    = new CodeCompileUnit[scriptsForLang.Count];
            CompilerParameters compilParams = lastScript.compilerInfo.CreateDefaultCompilerParameters();

            // REVIEW: You cannot say just "System.Xml", because JScript compiler loads it from
            // the Framework folder, while other compilers load it from GAC, thus we would have
            // two distinct copies of System.Xml in the memory
            compilParams.ReferencedAssemblies.Add(typeof(SR).GetTypeInfo().Assembly.GetName().ToString());
            compilParams.ReferencedAssemblies.Add("System.dll");
            if (isVB)
            {
                compilParams.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll");
            }

            bool refAssembliesByHref = false;

            for (int idx = 0; idx < scriptsForLang.Count; idx++)
            {
                ScriptClass   script   = scriptsForLang[idx];
                CodeNamespace scriptNs = new CodeNamespace(ScriptClassesNamespace);

                // Add imported namespaces
                foreach (string ns in s_defaultNamespaces)
                {
                    scriptNs.Imports.Add(new CodeNamespaceImport(ns));
                }
                if (isVB)
                {
                    scriptNs.Imports.Add(new CodeNamespaceImport("Microsoft.VisualBasic"));
                }
                foreach (string ns in script.nsImports)
                {
                    scriptNs.Imports.Add(new CodeNamespaceImport(ns));
                }

                scriptNs.Types.Add(script.typeDecl);

                CodeCompileUnit unit = new CodeCompileUnit();
                {
                    unit.Namespaces.Add(scriptNs);

                    if (isVB)
                    {
                        // This settings have sense for Visual Basic only. In future releases we may allow to specify
                        // them explicitly in the msxsl:script element.
                        unit.UserData["AllowLateBound"]             = true;  // Allow variables to be declared untyped
                        unit.UserData["RequireVariableDeclaration"] = false; // Allow variables to be undeclared
                    }

                    // Put SecurityTransparentAttribute and SecurityRulesAttribute on the first CodeCompileUnit only
                    if (idx == 0)
                    {
                        unit.AssemblyCustomAttributes.Add(new CodeAttributeDeclaration("System.Security.SecurityTransparentAttribute"));

                        // We want the assemblies generated for scripts to stick to the old security model
                        unit.AssemblyCustomAttributes.Add(
                            new CodeAttributeDeclaration(
                                new CodeTypeReference(typeof(System.Security.SecurityRulesAttribute)),
                                new CodeAttributeArgument(
                                    new CodeFieldReferenceExpression(
                                        new CodeTypeReferenceExpression(typeof(System.Security.SecurityRuleSet)), "Level1"))));
                    }
                }

                codeUnits[idx] = unit;
                foreach (string name in script.refAssemblies)
                {
                    compilParams.ReferencedAssemblies.Add(name);
                }

                refAssembliesByHref |= script.refAssembliesByHref;
            }

            XsltSettings settings = _compiler.Settings;
            compilParams.WarningLevel            = settings.WarningLevel >= 0 ? settings.WarningLevel : compilParams.WarningLevel;
            compilParams.TreatWarningsAsErrors   = settings.TreatWarningsAsErrors;
            compilParams.IncludeDebugInformation = _compiler.IsDebug;

            string asmPath = _compiler.ScriptAssemblyPath;
            if (asmPath != null && scriptsForLang.Count < _scriptClasses.Count)
            {
                asmPath = Path.ChangeExtension(asmPath, "." + GetLanguageName(lastScript.compilerInfo) + Path.GetExtension(asmPath));
            }
            compilParams.OutputAssembly = asmPath;

            string tempDir = (settings.TempFiles != null) ? settings.TempFiles.TempDir : null;
            compilParams.TempFiles = new TempFileCollection(tempDir);

            // We need only .dll and .pdb, but there is no way to specify that
            bool keepFiles = (_compiler.IsDebug && asmPath == null);
#if DEBUG
            keepFiles = keepFiles || XmlILTrace.IsEnabled;
#endif
            keepFiles = keepFiles && !settings.CheckOnly;


            compilParams.TempFiles.KeepFiles = keepFiles;

            // If GenerateInMemory == true, then CodeDom loads the compiled assembly using Assembly.Load(byte[])
            // instead of Assembly.Load(AssemblyName).  That means the assembly will be loaded in the anonymous
            // context (http://blogs.msdn.com/suzcook/archive/2003/05/29/57143.aspx), and its dependencies can only
            // be loaded from the Load context or using AssemblyResolve event.  However we want to use the LoadFrom
            // context to preload all dependencies specified by <ms:assembly href="uri-reference"/>, so we turn off
            // GenerateInMemory here.
            compilParams.GenerateInMemory = (asmPath == null && !_compiler.IsDebug && !refAssembliesByHref) || settings.CheckOnly;

            CompilerResults results;

            try
            {
                results = provider.CompileAssemblyFromDom(compilParams, codeUnits);
            }
            catch (Exception e)
            {
                if (e.HResult == HResults.EFail)
                {
                    // Compiler might have created temporary files
                    results = new CompilerResults(compilParams.TempFiles);
                    results.Errors.Add(_compiler.CreateError(lastScript.EndLineInfo, /*[XT_041]*/ SR.Xslt_ScriptCompileException, e.Message));
                }
                else
                {
                    throw e;
                }
            }

            if (!settings.CheckOnly)
            {
                foreach (string fileName in results.TempFiles)
                {
                    allTempFiles.AddFile(fileName, allTempFiles.KeepFiles);
                }
            }

            foreach (CompilerError error in results.Errors)
            {
                FixErrorPosition(error, scriptsForLang);
                _compiler.AddModule(error.FileName);
            }

            allErrors.AddRange(results.Errors);
            return(results.Errors.HasErrors ? null : results.CompiledAssembly);
        }
Exemplo n.º 55
0
 public CodeNamespaceNodeFactory(CodeNamespace element) : base(element as CodeElement)
 {
     _namespace = element;
 }
Exemplo n.º 56
0
        /// <summary>
        /// 代码构成脚本
        /// </summary>
        /// <param name="connection">连接字符串</param>
        /// <param name="name">名称</param>
        /// <param name="xmlNode">操作节点</param>
        /// <param name="maxConditionsCount">最大条件数</param>
        /// <param name="parameters">返回属性数组</param>
        /// <param name="codeReturnType">返回数据类型</param>
        /// <param name="provider">返回代码编译容器</param>
        /// <param name="compilerParameters">返回代码参数</param>
        /// <param name="codeCompileUnit">返回代码容器</param>
        private void CodeSetUp(string connection
                               , string name
                               , XmlNode xmlNode
                               , int maxConditionsCount
                               , out XmlNodeList parameters
                               , out Type codeReturnType
                               , out CodeDomProvider provider
                               , out CompilerParameters compilerParameters
                               , out CodeCompileUnit codeCompileUnit)
        {
            provider = CodeDomProvider.CreateProvider("CSharp");

            XmlNode sqlNode = XmlHelper.GetInstance().GetNode(xmlNode, "sql");

            if (sqlNode == null)
            {
                throw new Exception($"{name}不包含SQL节点,该XML文档是无效的");
            }

            string sQL = sqlNode.InnerText.Replace("\r", " ").Replace("\t", " ").Replace("\n", " ").Trim();

            //诺是无任何条件标记则为true (即是无 {0},{1},{2},... 中任意一个)
            bool isNotActiveConditionInsQL;

            //格式化SQL字段,分割SQL并写出对应条件键值
            List <SqlFormat> sqlList = SqlFormatAction(sQL, maxConditionsCount, out isNotActiveConditionInsQL);

            #region 格式化条件字符

            List <CodeParameterDeclarationExpression> codeParameterDeclarationExpressions = new List <CodeParameterDeclarationExpression>();

            //从XML中获取Parameters所有内容
            XmlNode parametersFarther = XmlHelper.GetInstance().GetNode(xmlNode, "parameters");
            parameters = null;
            if (parametersFarther != null)
            {
                parameters = parametersFarther.ChildNodes;
            }
            //将Parameters内容格化式
            Dictionary <int, List <Dictionary <PARAMETER, string> > > parametersDict = ParFormatAction(codeParameterDeclarationExpressions, parameters);

            #endregion

            //返回类型
            string query = XmlHelper.GetInstance().GetNodeAttribute(xmlNode, "query");
            if (string.IsNullOrWhiteSpace(query))
            {
                query = "select";
            }

            codeReturnType = query.ConventToTypes();

            //添加系统组件
            compilerParameters = new CompilerParameters
            {
                GenerateExecutable = false,
                GenerateInMemory   = true
            };
            compilerParameters.ReferencedAssemblies.Add("System.dll");
            compilerParameters.ReferencedAssemblies.Add("System.Xml.dll");
            compilerParameters.ReferencedAssemblies.Add("System.Data.dll");

            codeCompileUnit = new CodeCompileUnit();

            //创建命名空间
            CodeNamespace nameSpace = new CodeNamespace("Autogeneration.Dao.SQL");

            //创建类
            CodeTypeDeclaration codeTypeDeclarations = new CodeTypeDeclaration();
            codeTypeDeclarations.Name       = $"{name}Class";
            codeTypeDeclarations.Attributes = MemberAttributes.Public | MemberAttributes.Final;

            //创建方法
            CodeMemberMethod codeMemberMethod = new CodeMemberMethod
            {
                Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static
            };
            codeMemberMethod.Name       = name;
            codeMemberMethod.ReturnType = new CodeTypeReference(codeReturnType);

            //为方法添加参数
            codeMemberMethod.Parameters.AddRange(codeParameterDeclarationExpressions.ToArray());
            List <string> referencedAssemblies = new List <string>();
            codeMemberMethod.Statements.AddRange(Build(parametersDict
                                                       , sqlList
                                                       , connection
                                                       , isNotActiveConditionInsQL
                                                       , referencedAssemblies
                                                       , codeReturnType
                                                       , query
                                                       ));
            if (referencedAssemblies.Count > 0)
            {
                compilerParameters.ReferencedAssemblies.AddRange(referencedAssemblies.ToArray());
            }

            //在类中添加方法
            codeTypeDeclarations.Members.Add(codeMemberMethod);
            //在命名空间添加类
            nameSpace.Types.Add(codeTypeDeclarations);
            //在代码容器中添加命名空间
            codeCompileUnit.Namespaces.Add(nameSpace);
        }
Exemplo n.º 57
0
    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);
    }
        private int RunFieldInitalizers(CompilationModule[] compiledModules)
        {
            CompilationModule[] modulesToInitialize = compiledModules.Where(e => e.fieldsWithInitializers.Count > 0).ToArray();

            // We don't need to run the costly compilation if the user hasn't defined any fields with initializers
            if (modulesToInitialize.Length == 0)
            {
                return(0);
            }

            int initializerErrorCount = 0;

            SyntaxTree[]    initializerTrees   = new SyntaxTree[modulesToInitialize.Length];
            StringBuilder[] codeStringBuilders = new StringBuilder[modulesToInitialize.Length];

            for (int moduleIdx = 0; moduleIdx < modulesToInitialize.Length; ++moduleIdx)
            {
                CompilationModule module = modulesToInitialize[moduleIdx];

                CodeCompileUnit compileUnit = new CodeCompileUnit();
                CodeNamespace   ns          = new CodeNamespace("FieldInitialzers");
                compileUnit.Namespaces.Add(ns);
                foreach (var resolverUsingNamespace in module.resolver.usingNamespaces)
                {
                    if (!string.IsNullOrEmpty(resolverUsingNamespace))
                    {
                        ns.Imports.Add(new CodeNamespaceImport(resolverUsingNamespace));
                    }
                }

                CodeTypeDeclaration _class = new CodeTypeDeclaration($"Initializer{moduleIdx}");
                ns.Types.Add(_class);
                CodeMemberMethod method = new CodeMemberMethod();
                _class.Members.Add(method);
                method.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                method.ReturnType = new CodeTypeReference(typeof(void));
                method.Name       = "DoInit";
                method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IUdonProgram), "program"));

                foreach (var fieldDeclarationSyntax in module.fieldsWithInitializers)
                {
                    var  type    = fieldDeclarationSyntax.Declaration.Type;
                    int  count   = 0;
                    bool isConst = fieldDeclarationSyntax.Modifiers.Any(t => t.ToString() == "const");
                    foreach (var variable in fieldDeclarationSyntax.Declaration.Variables)
                    {
                        FieldDefinition fieldDef = module.compiledClassDefinition?.fieldDefinitions?.Find(e => (e.fieldSymbol.declarationType == SymbolDeclTypeFlags.Private || e.fieldSymbol.declarationType == SymbolDeclTypeFlags.Public) &&
                                                                                                          e.fieldSymbol.symbolOriginalName == variable.Identifier.ToString());

                        string typeQualifiedName = type.ToString();
                        if (fieldDef != null)
                        {
                            if (fieldDef.fieldSymbol.symbolCsType.Namespace.Length == 0)
                            {
                                typeQualifiedName = fieldDef.fieldSymbol.symbolCsType.Name;
                            }
                            else
                            {
                                typeQualifiedName = fieldDef.fieldSymbol.symbolCsType.Namespace + "." + fieldDef.fieldSymbol.symbolCsType.Name;
                            }
                        }

                        if (variable.Initializer != null)
                        {
                            string name = variable.Identifier.ToString();
                            if (isConst)
                            {
                                _class.Members.Add(new CodeSnippetTypeMember($"const {typeQualifiedName} {name} {variable.Initializer};"));
                            }
                            else
                            {
                                method.Statements.Add(new CodeSnippetStatement($"{typeQualifiedName} {name} {variable.Initializer};"));
                            }

                            method.Statements.Add(new CodeSnippetStatement(
                                                      $"program.Heap.SetHeapVariable(program.SymbolTable.GetAddressFromSymbol(\"{variable.Identifier}\"), {name});"));

                            count++;
                        }
                    }
                }

                StringBuilder sb = new StringBuilder();
                codeStringBuilders[moduleIdx] = sb;

                CSharpCodeProvider provider = new CSharpCodeProvider();
                using (StringWriter streamWriter = new StringWriter(sb))
                {
                    provider.GenerateCodeFromCompileUnit(compileUnit, streamWriter, new CodeGeneratorOptions());
                }

                SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sb.ToString());

                initializerTrees[moduleIdx] = syntaxTree;
            }

            var assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
            var references = new List <MetadataReference>();

            for (int i = 0; i < assemblies.Length; i++)
            {
                if (!assemblies[i].IsDynamic && assemblies[i].Location.Length > 0)
                {
                    references.Add(MetadataReference.CreateFromFile(assemblies[i].Location));
                }
            }

            CSharpCompilation compilation = CSharpCompilation.Create(
                $"init{initAssemblyCounter++}",
                syntaxTrees: initializerTrees,
                references: references,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var memoryStream = new MemoryStream())
            {
                EmitResult result = compilation.Emit(memoryStream);
                if (!result.Success)
                {
                    // todo: make these errors point to the correct source files
                    bool error = false;
                    foreach (Diagnostic diagnostic in result.Diagnostics)
                    {
                        if (diagnostic.Severity == DiagnosticSeverity.Error)
                        {
                            Debug.LogError(diagnostic);
                            error = true;
                            initializerErrorCount++;
                        }
                    }

                    if (error)
                    {
                        Debug.LogError($"Generated Source code: {string.Join("\n", codeStringBuilders.Select(e => e.ToString()))}");
                    }
                }
                else
                {
                    memoryStream.Seek(0, SeekOrigin.Begin);

                    Assembly assembly = Assembly.Load(memoryStream.ToArray());

                    for (int moduleIdx = 0; moduleIdx < modulesToInitialize.Length; ++moduleIdx)
                    {
                        CompilationModule module  = modulesToInitialize[moduleIdx];
                        IUdonProgram      program = module.programAsset.GetRealProgram();

                        System.Type cls        = assembly.GetType($"FieldInitialzers.Initializer{moduleIdx}");
                        MethodInfo  methodInfo = cls.GetMethod("DoInit", BindingFlags.Public | BindingFlags.Static);
                        methodInfo.Invoke(null, new[] { program });

                        foreach (var fieldDeclarationSyntax in module.fieldsWithInitializers)
                        {
                            foreach (var variable in fieldDeclarationSyntax.Declaration.Variables)
                            {
                                string varName = variable.Identifier.ToString();

                                object heapValue = program.Heap.GetHeapVariable(program.SymbolTable.GetAddressFromSymbol(varName));

                                if (heapValue != null && UdonSharpUtils.IsUserDefinedType(heapValue.GetType()))
                                {
                                    UdonSharpUtils.LogBuildError($"Field: '{varName}' UdonSharp does not yet support field initializers on user-defined types or jagged arrays", AssetDatabase.GetAssetPath(module.programAsset.sourceCsScript), 0, 0);
                                }
                            }
                        }
                    }
                }
            }

            return(initializerErrorCount);
        }
    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
    }
Exemplo n.º 60
0
 public CoderFeeder(StateMachineType model, StateBuilderOptions options, CodeNamespace codeNamespace)
     : base(model, options, codeNamespace)
 {
 }