Example #1
0
        public IActionResult test1()
        {
            List <FieldModel> list = new List <FieldModel>();

            for (int i = 0; i < 5; i++)
            {
                list.Add(new FieldModel()
                {
                    FieldName = "Field" + i * 3,
                    Desc      = "注释" + i,
                    type      = i % 2 == 0 ? typeof(string) : typeof(int)
                });
            }

            //创建一个新的编译单元
            CodeCompileUnit compileUnit = new CodeCompileUnit();
            //定义命名空间
            CodeNamespace samples = new CodeNamespace("zhou.Admin.Controllers");

            //添加引用
            samples.Imports.Add(new CodeNamespaceImport("System"));
            compileUnit.Namespaces.Add(samples);

            //定义类型 类,接口,枚举等
            CodeTypeDeclaration class1 = new CodeTypeDeclaration($"User{DateTime.Now.ToString("HHmmss")}");

            class1.IsClass = true;
            class1.BaseTypes.Add("BaseEntity");//在这里声明继承关系 (基类 , 接口)
            samples.Types.Add(class1);

            //声明空的构造函数
            CodeConstructor constructor1 = new CodeConstructor();

            constructor1.Attributes = MemberAttributes.Public;
            class1.Members.Add(constructor1);

            foreach (var item in list)
            {
                string FieldName = "_" + item.FieldName;

                CodeSnippetTypeMember field = new CodeSnippetTypeMember($@"
        /// <summary>
        /// {item.Desc}
        /// </summary>
        public string a_{item.FieldName} {{ get; set; }}");
                class1.Members.Add(field);
            }

            CodeDomProvider      provider = CodeDomProvider.CreateProvider("CSharp");
            CodeGeneratorOptions options  = new CodeGeneratorOptions();

            options.BracingStyle = "C";
            FileStream file = new FileStream($"C:/zhouliang/a代码/Blog190901/zhou/zhou.Models/DBModels/User{DateTime.Now.ToString("HHmmss")}.cs", FileMode.CreateNew);

            using (StreamWriter sourceWriter = new StreamWriter(file))
            {
                provider.GenerateCodeFromCompileUnit(compileUnit, sourceWriter, options);
            }

            return(Json(new { a = 1, b = 2 }));
        }
Example #2
0
        //Adapted from CodeDomFileDescriptionTemplate.cs
        //TODO: Remove need to have a namespace and type (i.e. translate fragments)
        public override string CreateContent(Project project, Dictionary <string, string> tags, string language)
        {
            //get target language's ICodeGenerator
            if (language == null || language == "")
            {
                throw new InvalidOperationException("Language not defined in CodeDom based template.");
            }

            CodeDomProvider provider = GetCodeDomProvider(language);

            //parse the source code
            if (tempSubstitutedContent == null)
            {
                throw new Exception("Expected ModifyTags to be called before CreateContent");
            }

            CodeCompileUnit ccu;

            using (StringReader sr = new StringReader(tempSubstitutedContent)) {
                try {
                    ccu = parserProvider.Parse(sr);
                } catch (NotImplementedException) {
                    throw new InvalidOperationException("Invalid Code Translation template: the CodeDomProvider of the source language '"
                                                        + language + "' has not implemented the Parse method.");
                } catch (Exception ex) {
                    LoggingService.LogError("Unparseable template: '" + tempSubstitutedContent + "'.", ex);
                    throw;
                }
            }

            foreach (CodeNamespace cns in ccu.Namespaces)
            {
                cns.Name = CodeDomFileDescriptionTemplate.StripImplicitNamespace(project, tags, cns.Name);
            }

            tempSubstitutedContent = null;

            //and generate the code
            CodeGeneratorOptions options = new CodeGeneratorOptions();

            options.IndentString = "\t";
            options.BracingStyle = "C";

            string txt = string.Empty;

            using (StringWriter sw = new StringWriter()) {
                provider.GenerateCodeFromCompileUnit(ccu, sw, options);
                txt = sw.ToString();
            }

            if (showAutogenerationNotice)
            {
                return(txt);
            }

            //remove auto-generation notice
            int i = txt.IndexOf("</autogenerated>");

            if (i == -1)
            {
                return(txt);
            }
            i = txt.IndexOf('\n', i);
            if (i == -1)
            {
                return(txt);
            }
            i = txt.IndexOf('\n', i + 1);
            if (i == -1)
            {
                return(txt);
            }

            return(txt.Substring(i + 1));
        }
        void GenerateCode()
        {
            //Create the target directory if required
            Directory.CreateDirectory(Path.GetDirectoryName(OutputFile));

            var ccu = new CodeCompileUnit();

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

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

            var declNs = new CodeNamespace(RootClrNamespace);

            ccu.Namespaces.Add(declNs);

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

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

            declType.BaseTypes.Add(BaseType);

            declNs.Types.Add(declType);

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

                declType.Members.Add(ctor);
            }

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

            declType.Members.Add(initcomp);

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

            foreach (var namedField in NamedFields)
            {
                declType.Members.Add(namedField);

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

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

                initcomp.Statements.Add(assign);
            }

writeAndExit:
            //write the result
            using (var writer = new StreamWriter(OutputFile))
                Provider.GenerateCodeFromCompileUnit(ccu, writer, new CodeGeneratorOptions());
        }
Example #4
0
        private void CreateInteropFormProxiesForDocument(List <CodeClass> interopFormClasses, Project currentAssembly, ProjectItem interopFormDoc)
        {
            if (interopFormClasses.Count <= 0)
            {
                return;
            }

            CodeCompileUnit     unit1   = new CodeCompileUnit();
            CodeNamespaceImport import1 = new CodeNamespaceImport(this._attrTypeForm.Namespace);

            System.CodeDom.CodeNamespace namespace1 = new System.CodeDom.CodeNamespace();
            namespace1.Name = "Interop";
            unit1.Namespaces.Add(namespace1);
            namespace1.Imports.Add(import1);
            foreach (CodeClass class1 in interopFormClasses)
            {
                string text2 = class1.FullName;
                CodeTypeDeclaration declaration1 = new CodeTypeDeclaration(class1.Name);
                namespace1.Types.Add(declaration1);
                declaration1.IsClass   = true;
                declaration1.IsPartial = true;
                CodePrimitiveExpression expression2 = new CodePrimitiveExpression(true);
                CodeSnippetExpression   expression1 = new CodeSnippetExpression("System.Runtime.InteropServices.ClassInterfaceType.AutoDual");
                declaration1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Runtime.InteropServices.ClassInterface", new System.CodeDom.CodeAttributeArgument[] { new System.CodeDom.CodeAttributeArgument(expression1) }));
                declaration1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Runtime.InteropServices.ComVisible", new System.CodeDom.CodeAttributeArgument[] { new System.CodeDom.CodeAttributeArgument(expression2) }));
                declaration1.BaseTypes.Add(new CodeTypeReference(typeof(InteropFormProxyBase).Name));
                CodeTypeDeclaration declaration2 = new CodeTypeDeclaration("I" + declaration1.Name + "EventSink");
                declaration2.CustomAttributes.Add(new CodeAttributeDeclaration("System.Runtime.InteropServices.InterfaceTypeAttribute", new System.CodeDom.CodeAttributeArgument[] { new System.CodeDom.CodeAttributeArgument(new CodeSnippetExpression("System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIDispatch")) }));
                declaration2.CustomAttributes.Add(new CodeAttributeDeclaration("System.Runtime.InteropServices.ComVisible", new System.CodeDom.CodeAttributeArgument[] { new System.CodeDom.CodeAttributeArgument(expression2) }));
                declaration2.IsInterface = true;
                CodeConstructor      constructor1 = new CodeConstructor();
                CodeSnippetStatement statement1   = GetStatementInitializeForm(text2);
                CodeSnippetStatement statement2   = GetStatementRegisterForm();
                constructor1.Statements.Add(statement1);
                constructor1.Statements.Add(statement2);
                constructor1.Attributes = MemberAttributes.Public;
                declaration1.Members.Add(constructor1);
                if (class1.Members.Count > 0)
                {
                    foreach (CodeElement element1 in class1.Members)
                    {
                        switch (element1.Kind)
                        {
                        case vsCMElement.vsCMElementFunction:
                            CodeFunction2 function1 = (CodeFunction2)element1;
                            if (function1.Access == vsCMAccess.vsCMAccessPublic)
                            {
                                foreach (CodeElement element2 in function1.Attributes)
                                {
                                    if (this.AttributesMatch(element2, this._attrTypeInitializer))
                                    {
                                        this.AddInitializeMethodForConstructor(declaration1, class1, function1);
                                        break;
                                    }
                                    if (this.AttributesMatch(element2, this._attrTypeMethod))
                                    {
                                        this.AddMethod(declaration1, class1, function1);
                                        break;
                                    }
                                }
                            }
                            break;

                        case vsCMElement.vsCMElementProperty:
                            CodeProperty property1 = (CodeProperty)element1;
                            if (property1.Access == vsCMAccess.vsCMAccessPublic)
                            {
                                foreach (CodeElement element3 in property1.Attributes)
                                {
                                    if (this.AttributesMatch(element3, this._attrTypeProperty))
                                    {
                                        this.AddProperty(declaration1, class1, property1);
                                        break;
                                    }
                                }
                            }
                            break;

                        case vsCMElement.vsCMElementEvent:
                            CodeEvent event1 = (CodeEvent)element1;
                            if (event1.Access == vsCMAccess.vsCMAccessPublic)
                            {
                                foreach (CodeElement element3 in event1.Attributes)
                                {
                                    if (this.AttributesMatch(element3, this._attrTypeEvent))
                                    {
                                        this.AddEvent(currentAssembly, declaration1, class1, event1, declaration2);
                                        break;
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
                if (declaration2.Members.Count > 0)
                {
                    namespace1.Types.Add(declaration2);
                    declaration1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Runtime.InteropServices.ComSourceInterfaces", new System.CodeDom.CodeAttributeArgument[] { new System.CodeDom.CodeAttributeArgument(new CodeTypeOfExpression(declaration2.Name)) }));
                }
            }


            ProjectItem generatedFolderItem = GetGeneratedFolderItem(currentAssembly);
            FileInfo    generatedItemInfo   = getGeneratedItem(currentAssembly, generatedFolderItem, interopFormDoc);

            StreamWriter writer1 = new StreamWriter(generatedItemInfo.Create());

            writer1.AutoFlush = true;
            CodeDomProvider      provider = GetProvider();
            CodeGeneratorOptions options1 = new CodeGeneratorOptions();

            provider.GenerateCodeFromCompileUnit(unit1, writer1, options1);
            writer1.Close();
            writer1.Dispose();
            generatedFolderItem.ProjectItems.AddFromFile(generatedItemInfo.FullName);
        }
Example #5
0
        /// <summary>
        /// 通过 c# dom 生成模板类
        /// </summary>
        /// <param name="s"></param>
        public static void MakeActionCode(String s)
        {
            string name       = "Action" + s;
            string outputFile = Application.dataPath + ACTION_PATH + name + ".cs";

            if (File.Exists(outputFile))
            {
                return;
            }


            //准备一个代码编译器单元

            CodeCompileUnit unit = new CodeCompileUnit();

            //准备必要的命名空间(这个是指要生成的类的空间)
            CodeNamespace sampleNamespace = new CodeNamespace("");

            //导入必要的命名空间
            sampleNamespace.Imports.Add(new CodeNamespaceImport("System"));
            sampleNamespace.Imports.Add(new CodeNamespaceImport("UnityEngine"));
            sampleNamespace.Imports.Add(new CodeNamespaceImport("System"));

            //准备要生成的类的定义

            CodeTypeDeclaration Customerclass = new CodeTypeDeclaration(name);

            //指定这是一个Class

            Customerclass.IsClass = true;

            Customerclass.TypeAttributes = TypeAttributes.Public;

            //把这个类放在这个命名空间下

            sampleNamespace.Types.Add(Customerclass);

            //把该命名空间加入到编译器单元的命名空间集合中

            Customerclass.BaseTypes.Add("LogicAction");

            unit.Namespaces.Add(sampleNamespace);

            //这是输出文件
            //定义方法
            CodeMemberMethod moth = new CodeMemberMethod();

            moth.Name       = "ProcessAction";
            moth.ReturnType = new CodeTypeReference("System.Boolean");             //返回值
            moth.Attributes = MemberAttributes.Override | MemberAttributes.Public; //声明方法是公开 并且override的
            Customerclass.Members.Add(moth);

            CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

            CodeGeneratorOptions options = new CodeGeneratorOptions();

            options.BracingStyle = "C";

            options.BlankLinesBetweenMembers = true;

            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputFile))
            {
                provider.GenerateCodeFromCompileUnit(unit, sw, options);
            }


            //添加字段

            //CodeMemberField field = new CodeMemberField(typeof(System.String), "_Id");

            //field.Attributes = MemberAttributes.Private;

            //Customerclass.Members.Add(field);

            //添加属性

            //CodeMemberProperty property = new CodeMemberProperty();

            //property.Attributes = MemberAttributes.Public | MemberAttributes.Final;

            //property.Name = "Id";

            //property.HasGet = true;

            //property.HasSet = true;

            //property.Type = new CodeTypeReference(typeof(System.String));

            //property.Comments.Add(new CodeCommentStatement("这是Id属性"));

            //property.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_Id")));

            //property.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_Id"), new CodePropertySetValueReferenceExpression()));

            //Customerclass.Members.Add(property);



            //添加构造器(使用CodeConstructor) --此处略

            //添加程序入口点(使用CodeEntryPointMethod) --此处略

            //添加事件(使用CodeMemberEvent) --此处略

            //添加特征(使用 CodeAttributeDeclaration)

            //Customerclass.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeAttributeDeclaration("Serializable"));

            //生成代码
        }
Example #6
0
    public void Json2Class(string file, string json, List <object> list)
    {
        string structName = Path.GetFileName(file).Replace(".xlsx", "");

        structName = structName.Substring(0, 1).ToUpper() + structName.Substring(1);

        string outputFile = Path.Combine(Application.dataPath, "Scripts/Table");

        if (!Directory.Exists(outputFile))
        {
            Directory.CreateDirectory(outputFile);
        }

        outputFile = Path.Combine(outputFile, Path.GetFileName(file).Replace(".xlsx", ".cs"));

        // 生成类服务
        CodeCompileUnit unit = new CodeCompileUnit();

        // 生成类名空间
        CodeNamespace namespaces = new CodeNamespace("Game.Data." + structName);

        unit.Namespaces.Add(namespaces);
        namespaces.Imports.Add(new CodeNamespaceImport("System"));
        namespaces.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));

        //命名空间下添加一个类
        CodeTypeDeclaration ration = new CodeTypeDeclaration(structName);

        ration.IsClass     = true;
        ration.IsEnum      = false;
        ration.IsInterface = false;
        ration.IsPartial   = false;
        ration.IsStruct    = false;
        namespaces.Types.Add(ration);

        JsonData jsonData = JsonMapper.ToObject(json)[0];
        int      i        = 0;

        foreach (var key in jsonData.Keys)
        {
            string memberString = @"        public [type] [name] {get;set;}";


            CodeSnippetTypeMember member = new CodeSnippetTypeMember();
            if (key.ToLower() == "id" && key != "Id")
            {
                Debug.LogErrorFormat("<color=yellow>表格{0}字段为Id[大小写],请修改", structName);
                break;
            }
            else if (key == "Id")
            {
                memberString = @"
        public [type] [name] {get;set;}
";
            }

            string type = null;

            JsonData value = jsonData[key];
            if (value.IsArray)
            {
                string str = value.ToJson();
                if (str.IndexOf("\"") > 0)
                {
                    type = "List<string>";
                }
                else
                {
                    type = "List<double>";
                }
            }
            else if (value.IsBoolean)
            {
                type = "bool";
            }
            else if (value.IsDouble)
            {
                type = "double";
            }
            else if (value.IsInt)
            {
                type = "int";
            }
            else if (value.IsString)
            {
                type = "string";
            }

            // 注释
            member.Comments.Add(new CodeCommentStatement(list[i].ToString()));
            member.Text = memberString.Replace("[type]", type).Replace("[name]", key);

            ration.Members.Add(member);
            i++;

            // 生成代码
            CodeDomProvider      provider = CodeDomProvider.CreateProvider("CSharp");
            CodeGeneratorOptions options  = new CodeGeneratorOptions();
            options.BracingStyle             = "C";
            options.BlankLinesBetweenMembers = true;

            using (StreamWriter writer = new StreamWriter(outputFile))
            {
                provider.GenerateCodeFromCompileUnit(unit, writer, options);
            }
        }
    }
Example #7
0
        private void XXGenerateCode()
        {
            //准备一个代码编译器单元

            CodeCompileUnit unit = new CodeCompileUnit();

            //准备必要的命名空间(这个是指要生成的类的空间)

            CodeNamespace sampleNamespace = new CodeNamespace("Xizhang.com");

            //导入必要的命名空间

            sampleNamespace.Imports.Add(new CodeNamespaceImport("System"));
            sampleNamespace.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));

            //准备要生成的类的定义

            CodeTypeDeclaration Customerclass = new CodeTypeDeclaration("Customer");//替换节点

            //指定这是一个Class

            Customerclass.IsClass = true;

            Customerclass.TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed;

            //把这个类放在这个命名空间下

            sampleNamespace.Types.Add(Customerclass);

            //把该命名空间加入到编译器单元的命名空间集合中

            unit.Namespaces.Add(sampleNamespace);

            //这是输出文件

            string outputFile = "Customer.cs";

            //添加字段

            CodeMemberField field = new CodeMemberField(typeof(System.String), "_Id");

            field.Attributes = MemberAttributes.Private;

            Customerclass.Members.Add(field);

            //添加属性

            CodeMemberProperty property = new CodeMemberProperty();

            property.Attributes = MemberAttributes.Public | MemberAttributes.Final;

            property.Name = "Id";

            property.HasGet = true;

            property.HasSet = true;

            property.Type = new CodeTypeReference(typeof(System.String));

            property.Comments.Add(new CodeCommentStatement("这是Id属性"));

            property.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_Id")));

            property.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_Id"), new CodePropertySetValueReferenceExpression()));

            Customerclass.Members.Add(property);

            //添加方法(使用CodeMemberMethod)--此处略

            //添加构造器(使用CodeConstructor) --此处略

            //添加程序入口点(使用CodeEntryPointMethod) --此处略

            //添加事件(使用CodeMemberEvent) --此处略

            //添加特征(使用 CodeAttributeDeclaration)

            Customerclass.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(SerializableAttribute))));

            //生成代码

            CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

            CodeGeneratorOptions options = new CodeGeneratorOptions();

            options.BracingStyle = "C";

            options.BlankLinesBetweenMembers = true;

            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputFile))
            {
                provider.GenerateCodeFromCompileUnit(unit, sw, options);
            }
        }
Example #8
0
        /// <summary>
        /// Function that builds the contents of the generated file based on the contents of the input file
        /// </summary>
        /// <param name="inputFileContent">Content of the input file</param>
        /// <returns>Generated file as a byte array</returns>
        protected override byte[] GenerateCode(string inputFileContent)
        {
            //Validate the XML file against the schema
            using (StringReader contentReader = new StringReader(inputFileContent))
            {
                VerifyDocumentSchema(contentReader);
            }

            if (!validXML)
            {
                //Returning null signifies that generation has failed
                return(null);
            }

            CodeDomProvider provider = GetCodeProvider();

            try
            {
                //Load the XML file
                XmlDocument doc = new XmlDocument();
                //We have already validated the XML. No XmlException can be thrown here
                doc.LoadXml(inputFileContent);

                //Create the CodeCompileUnit from the passed-in XML file
                CodeCompileUnit compileUnit = SourceCodeGenerator.CreateCodeCompileUnit(doc, FileNameSpace);

                if (this.CodeGeneratorProgress != null)
                {
                    //Report that we are 1/2 done
                    this.CodeGeneratorProgress.Progress(50, 100);
                }

                using (StringWriter writer = new StringWriter(new StringBuilder()))
                {
                    CodeGeneratorOptions options = new CodeGeneratorOptions();
                    options.BlankLinesBetweenMembers = false;
                    options.BracingStyle             = "C";

                    //Generate the code
                    provider.GenerateCodeFromCompileUnit(compileUnit, writer, options);

                    if (this.CodeGeneratorProgress != null)
                    {
                        //Report that we are done
                        this.CodeGeneratorProgress.Progress(100, 100);
                    }
                    writer.Flush();

                    //Get the Encoding used by the writer. We're getting the WindowsCodePage encoding,
                    //which may not work with all languages
                    Encoding enc = Encoding.GetEncoding(writer.Encoding.WindowsCodePage);

                    //Get the preamble (byte-order mark) for our encoding
                    byte[] preamble       = enc.GetPreamble();
                    int    preambleLength = preamble.Length;

                    //Convert the writer contents to a byte array
                    byte[] body = enc.GetBytes(writer.ToString());

                    //Prepend the preamble to body (store result in resized preamble array)
                    Array.Resize <byte>(ref preamble, preambleLength + body.Length);
                    Array.Copy(body, 0, preamble, preambleLength, body.Length);

                    //Return the combined byte array
                    return(preamble);
                }
            }
            catch (Exception e)
            {
                this.GeneratorError(4, e.ToString(), 1, 1);
                //Returning null signifies that generation has failed
                return(null);
            }
        }
Example #9
0
        ///
        /// <summary>
        ///	Generate code for the specified ServiceDescription.
        /// </summary>
        ///
        public bool GenerateCode(WebReferenceCollection references, CodeCompileUnit codeUnit)
        {
            bool hasWarnings = false;

            CodeDomProvider provider = GetProvider();

            StringCollection    validationWarnings;
            WebReferenceOptions opts = new WebReferenceOptions();

            opts.CodeGenerationOptions = options;
            opts.Style         = style;
            opts.Verbose       = verbose;
            validationWarnings = ServiceDescriptionImporter.GenerateWebReferences(references, provider, codeUnit, opts);

            for (int n = 0; n < references.Count; n++)
            {
                WebReference wr = references [n];

                BasicProfileViolationCollection violations = new BasicProfileViolationCollection();
                if (String.Compare(protocol, "SOAP", StringComparison.OrdinalIgnoreCase) == 0 && !WebServicesInteroperability.CheckConformance(WsiProfiles.BasicProfile1_1, wr, violations))
                {
                    wr.Warnings |= ServiceDescriptionImportWarnings.WsiConformance;
                }

                if (wr.Warnings != 0)
                {
                    if (!hasWarnings)
                    {
                        WriteText("", 0, 0);
                        WriteText("There where some warnings while generating the code:", 0, 0);
                    }

                    WriteText("", 0, 0);
                    WriteText(urls[n], 2, 2);

                    if ((wr.Warnings & ServiceDescriptionImportWarnings.WsiConformance) > 0)
                    {
                        WriteText("- This web reference does not conform to WS-I Basic Profile v1.1", 4, 6);
                        foreach (BasicProfileViolation vio in violations)
                        {
                            WriteText(vio.NormativeStatement + ": " + vio.Details, 8, 8);
                            foreach (string ele in vio.Elements)
                            {
                                WriteText("* " + ele, 10, 12);
                            }
                        }
                    }

                    if ((wr.Warnings & ServiceDescriptionImportWarnings.NoCodeGenerated) > 0)
                    {
                        WriteText("- WARNING: No proxy class was generated", 4, 6);
                    }
                    if ((wr.Warnings & ServiceDescriptionImportWarnings.NoMethodsGenerated) > 0)
                    {
                        WriteText("- WARNING: The proxy class generated includes no methods", 4, 6);
                    }
                    if ((wr.Warnings & ServiceDescriptionImportWarnings.OptionalExtensionsIgnored) > 0)
                    {
                        WriteText("- WARNING: At least one optional extension has been ignored", 4, 6);
                    }
                    if ((wr.Warnings & ServiceDescriptionImportWarnings.RequiredExtensionsIgnored) > 0)
                    {
                        WriteText("- WARNING: At least one necessary extension has been ignored", 4, 6);
                    }
                    if ((wr.Warnings & ServiceDescriptionImportWarnings.UnsupportedBindingsIgnored) > 0)
                    {
                        WriteText("- WARNING: At least one binding is of an unsupported type and has been ignored", 4, 6);
                    }
                    if ((wr.Warnings & ServiceDescriptionImportWarnings.UnsupportedOperationsIgnored) > 0)
                    {
                        WriteText("- WARNING: At least one operation is of an unsupported type and has been ignored", 4, 6);
                    }

                    hasWarnings = true;
                }
            }

            if (hasWarnings)
            {
                WriteText("", 0, 0);
            }

            string filename    = outFilename;
            bool   hasBindings = false;

            foreach (object doc in references[0].Documents.Values)
            {
                ServiceDescription desc = doc as ServiceDescription;
                if (desc == null)
                {
                    continue;
                }

                if (desc.Services.Count > 0 && filename == null)
                {
                    filename = desc.Services[0].Name + "." + provider.FileExtension;
                }

                if (desc.Bindings.Count > 0 || desc.Services.Count > 0)
                {
                    hasBindings = true;
                }
            }

            if (filename == null)
            {
                filename = "output." + provider.FileExtension;
            }

            if (hasBindings)
            {
                WriteText("Writing file '" + filename + "'", 0, 0);
                StreamWriter writer = new StreamWriter(filename);

                CodeGeneratorOptions compilerOptions = new CodeGeneratorOptions();
                provider.GenerateCodeFromCompileUnit(codeUnit, writer, compilerOptions);
                writer.Close();
            }

            return(hasWarnings);
        }
Example #10
0
        private static void GenerateCalculatorClass()
        {
            // Create the CodeCompileUnit that will contain the code for the class.
            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();

            // Create the namespace
            CodeNamespace codeNamespace = new CodeNamespace("Reflection");

            // Add the using statements
            codeNamespace.Imports.Add(new CodeNamespaceImport("System"));
            codeNamespace.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
            codeNamespace.Imports.Add(new CodeNamespaceImport("System.Linq"));
            codeNamespace.Imports.Add(new CodeNamespaceImport("System.Text"));
            codeNamespace.Imports.Add(new CodeNamespaceImport("System.Threading.Tasks"));

            // Declare the class
            CodeTypeDeclaration targetClass = new CodeTypeDeclaration("Calculator");

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

            // Add the class to the namespace.
            codeNamespace.Types.Add(targetClass);

            // Add the namespace to the code compile unit
            codeCompileUnit.Namespaces.Add(codeNamespace);

            // Create the fields
            CodeMemberField xField = new CodeMemberField();

            xField.Name = "_x";
            xField.Type = new CodeTypeReference(typeof(double));
            targetClass.Members.Add(xField);

            CodeMemberField yField = new CodeMemberField();

            yField.Name = "_y";
            yField.Type = new CodeTypeReference(typeof(double));
            targetClass.Members.Add(yField);

            // Create the properties
            CodeMemberProperty xProperty = new CodeMemberProperty();

            xProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            xProperty.Name       = "X";
            xProperty.HasGet     = true;
            xProperty.HasSet     = true;
            xProperty.Type       = new CodeTypeReference(typeof(System.Double));
            xProperty.GetStatements.Add(
                new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_x")));
            xProperty.SetStatements.Add(
                new CodeAssignStatement(
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_x"),
                    new CodePropertySetValueReferenceExpression()));
            targetClass.Members.Add(xProperty);

            CodeMemberProperty yProperty = new CodeMemberProperty();

            yProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            yProperty.Name       = "Y";
            yProperty.HasGet     = true;
            yProperty.HasSet     = true;
            yProperty.Type       = new CodeTypeReference(typeof(System.Double));
            yProperty.GetStatements.Add(
                new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_y")));
            yProperty.SetStatements.Add(
                new CodeAssignStatement(
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_y"),
                    new CodePropertySetValueReferenceExpression()));
            targetClass.Members.Add(yProperty);

            // Create the divide method
            CodeMemberMethod divideMethod = new CodeMemberMethod();

            divideMethod.Name       = "Divide";
            divideMethod.ReturnType = new CodeTypeReference(typeof(double));
            divideMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;

            // Create the body of the method
            CodeConditionStatement ifLogic = new CodeConditionStatement();

            ifLogic.Condition =
                new CodeBinaryOperatorExpression(
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), yProperty.Name),
                    CodeBinaryOperatorType.ValueEquality,
                    new CodePrimitiveExpression(0));
            ifLogic.TrueStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(0)));
            ifLogic.FalseStatements.Add(
                new CodeMethodReturnStatement(
                    new CodeBinaryOperatorExpression(
                        new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), xProperty.Name),
                        CodeBinaryOperatorType.Divide,
                        new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), yProperty.Name))));
            divideMethod.Statements.Add(ifLogic);

            // Add the method to the class.
            targetClass.Members.Add(divideMethod);

            // Create the Exponent method
            CodeMemberMethod exponentMethod = new CodeMemberMethod();

            exponentMethod.Name       = "Exponent";
            exponentMethod.ReturnType = new CodeTypeReference(typeof(double));
            exponentMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;

            CodeParameterDeclarationExpression powerParameter = new CodeParameterDeclarationExpression(
                typeof(double),
                "power");

            exponentMethod.Parameters.Add(powerParameter);

            CodeMethodInvokeExpression callToMath =
                new CodeMethodInvokeExpression(
                    new CodeTypeReferenceExpression("System.Math"),
                    "Pow",
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), xProperty.Name),
                    new CodeArgumentReferenceExpression("power"));

            exponentMethod.Statements.Add(new CodeMethodReturnStatement(callToMath));

            targetClass.Members.Add(exponentMethod);

            // Generate the file as a C# class.
            CodeDomProvider      provider = CodeDomProvider.CreateProvider("CSharp");
            CodeGeneratorOptions options  = new CodeGeneratorOptions();

            options.BlankLinesBetweenMembers = false;
            options.BracingStyle             = "C";

            using (StreamWriter sourceWriter = new StreamWriter(@"c:\CodeDom\Calculator." + provider.FileExtension))
            {
                provider.GenerateCodeFromCompileUnit(codeCompileUnit, sourceWriter, options);
            }
        }
Example #11
0
        private void GenerateCode(ServiceDescriptionCollection sources, XmlSchemas schemas, string uriToWSDL, CodeDomProvider codeGen, string fileExtension)
        {
            this.proxyCode = " <ERROR> ";
            StringWriter w = null;

            this.compileUnit = new CodeCompileUnit();
            ServiceDescriptionImporter importer = new ServiceDescriptionImporter();

            importer.Schemas.Add(schemas);
            foreach (ServiceDescription description in sources)
            {
                importer.AddServiceDescription(description, "", "");
            }
            importer.Style = ServiceDescriptionImportStyle.Client;
            Protocol protocol = this.WsdlProperties.Protocol;

            importer.ProtocolName = this.WsdlProperties.Protocol.ToString();
            CodeNamespace namespace2 = new CodeNamespace(this.proxyNamespace);

            this.compileUnit.Namespaces.Add(namespace2);
            ServiceDescriptionImportWarnings warnings = importer.Import(namespace2, this.compileUnit);

            try
            {
                try
                {
                    w = new StringWriter();
                }
                catch
                {
                    throw;
                }
                MemoryStream stream = null;
                if (schemas.Count > 0)
                {
                    this.compileUnit.ReferencedAssemblies.Add("System.Data.dll");
                    foreach (XmlSchema schema in schemas)
                    {
                        string targetNamespace = null;
                        try
                        {
                            targetNamespace = schema.TargetNamespace;
                            if (XmlSchemas.IsDataSet(schema))
                            {
                                if (stream == null)
                                {
                                    stream = new MemoryStream();
                                }
                                stream.Position = 0L;
                                stream.SetLength(0L);
                                schema.Write(stream);
                                stream.Position = 0L;
                                DataSet dataSet = new DataSet();
                                dataSet.ReadXmlSchema(stream);
                                System.Data.Design.TypedDataSetGenerator.Generate(dataSet, namespace2, codeGen);
                            }
                            continue;
                        }
                        catch
                        {
                            throw;
                        }
                    }
                }
                try
                {
                    GenerateVersionComment(this.compileUnit.Namespaces[0]);
                    this.ChangeBaseType(this.compileUnit);
                    codeGen.GenerateCodeFromCompileUnit(this.compileUnit, w, null);
                }
                catch (Exception exception)
                {
                    if (w != null)
                    {
                        w.Write("Exception in generating code");
                        w.Write(exception.Message);
                    }
                    throw new InvalidOperationException("Error generating ", exception);
                }
            }
            finally
            {
                this.proxyCode = w.ToString();
                if (w != null)
                {
                    w.Close();
                }
            }
        }
Example #12
0
        /// <summary>
        /// 构建帮助器类定义
        /// </summary>
        /// <param name="byMsgType"></param>
        /// <returns></returns>
        private static System.Type BuildHelperType(System.Type byMsgType)
        {
            // 断言参数不为空
            Assert.NotNull(byMsgType, "byMsgType");

            // 获取编译器对象
            CodeCompileUnit CC = new CodeCompileUnit();
            // 创建并添加名称空间对象
            CodeNamespace NS = new CodeNamespace(byMsgType.Namespace);

            CC.Namespaces.Add(NS);
            // 创建并添加 Helper 类
            CodeTypeDeclaration helperTypeDef = new CodeTypeDeclaration("WriteHelper_" + byMsgType.Name);

            NS.Types.Add(helperTypeDef);

            // 令 helper 实现 IWriteHelper 接口
            helperTypeDef.BaseTypes.Add(typeof(IWriteHelper));
            // 构建函数文本
            BuildFuncText(helperTypeDef, byMsgType);

            // 创建 C# 编译器
            CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

#if DEBUG
            string srcFilePath = null;
            // C# 源代码文件
            srcFilePath = @"D:\Temp_Test\{0}.cs";
            srcFilePath = string.Format(srcFilePath, helperTypeDef.Name);

            // 源文件输出流
            StreamWriter sw = new StreamWriter(srcFilePath, false);
            // 写出源文件
            provider.GenerateCodeFromCompileUnit(CC, sw, new CodeGeneratorOptions());

            sw.Flush();
            sw.Close();
#endif

            // 创建编译参数
            CompilerParameters cp = new CompilerParameters();

            // 添加对 DLL 的引用
            cp.ReferencedAssemblies.Add("System.dll");
            cp.ReferencedAssemblies.Add(typeof(IWriteHelper).Assembly.Location);
            cp.ReferencedAssemblies.Add(byMsgType.Assembly.Location);

            for (int i = 0; i < 64; i++)
            {
                if (byMsgType.BaseType == null ||
                    byMsgType.BaseType == typeof(BaseMsgObj))
                {
                    // 如果父类为空,
                    // 或者父类已经是 BaseMsgObj 类型,
                    // 则跳出循环!
                    break;
                }

                // 获取父类定义并添加到引用集
                System.Type baseType = byMsgType.BaseType;
                cp.ReferencedAssemblies.Add(baseType.Assembly.Location);
            }

            // 只在内存中编译
            cp.GenerateInMemory = true;

            // 编译并获取编译结果
            CompilerResults compileResult = provider.CompileAssemblyFromDom(cp, CC);

            // 编译失败则抛出异常
            if (compileResult.NativeCompilerReturnValue != 0)
            {
                if (compileResult.Errors.HasErrors)
                {
                    // 抛出异常并告知原因
                    throw new MsgError("编译失败! " + compileResult.Errors[0].ErrorText);
                }
                else
                {
                    // 抛出异常!
                    throw new MsgError("编译失败! 原因未知...");
                }
            }

            // 获取类定义
            return(compileResult.CompiledAssembly.GetType(
                       string.Format("{0}.{1}",
                                     NS.Name,
                                     helperTypeDef.Name
                                     )));
        }
Example #13
0
        private static void Json2Class(string fileName, string json, List <object> statements, bool isForSql = false)
        {
            string structName = "";

            if (isForSql)
            {
                structName = Path.GetFileName(fileName).ToLower().Replace(".xlsx", "_SQL");
            }
            else
            {
                structName = Path.GetFileName(fileName).ToLower().Replace(".xlsx", "");
            }
            //首字母大写
            structName = structName.Substring(0, 1).ToUpper() + structName.Substring(1);
            string outputFile = "";

            if (isForSql)
            {
                outputFile = fileName.Replace(".xlsx", "_SQL.cs");
            }
            else
            {
                outputFile = fileName.Replace(".xlsx", ".cs");
            }

            //生成类服务
            CodeCompileUnit compunit = new CodeCompileUnit();
            CodeNamespace   sample   = new CodeNamespace("Game.Data");

            compunit.Namespaces.Add(sample);
            //引用命名空间
            sample.Imports.Add(new CodeNamespaceImport("System"));
            sample.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
            sample.Imports.Add(new CodeNamespaceImport("Game.Data"));
            sample.Imports.Add(new CodeNamespaceImport("SQLite4Unity3d"));

            //在命名空间下添加一个类
            CodeTypeDeclaration wrapProxyStruct = new CodeTypeDeclaration(structName);

            wrapProxyStruct.IsClass     = false;
            wrapProxyStruct.IsEnum      = false;
            wrapProxyStruct.IsInterface = false;
            wrapProxyStruct.IsPartial   = false;
            wrapProxyStruct.IsStruct    = true;
            //把这个类添加到命名空间
            sample.Types.Add(wrapProxyStruct);

            //
            var jsonData = JsonMapper.ToObject(json)[0];

            int i = 0;

            foreach (var key in jsonData.Keys)
            {
                //字段

                string memberContent =
                    @"       public [type] [Name] {get;set;}";
                CodeSnippetTypeMember member = new CodeSnippetTypeMember();
                if (key.ToLower() == "id" && key != "Id")
                {
                    Debug.LogErrorFormat("<color=yellow>表格{0}字段必须为Id[大小写],请修改后生成</color>", structName);
                    break;
                }
                else if (key == "Id")
                {
                    //增加一个sqlite主键
                    //member.CustomAttributes.Add(new CodeAttributeDeclaration("PrimaryKey"));
                    memberContent =
                        @"      [PrimaryKey] 
        public [type] [Name] {get;set;}";
                }
                var value = jsonData[key];



                string type = null;
                if (value.IsArray)
                {
                    if (isForSql)
                    {
                        type = "string";
                    }
                    else
                    {
                        var str = value.ToJson();
                        if (str.IndexOf("\"") > 0)
                        {
                            type = "List<string>";
                        }
                        else
                        {
                            type = "List<double>";
                        }
                    }
                }
                else if (value.IsInt)
                {
                    type = "int";
                }
                else if (value.IsDouble || value.IsLong)
                {
                    type = "double";
                }
                else if (value.IsBoolean)
                {
                    type = "bool";
                }
                else if (value.IsString)
                {
                    type = "string";
                }

                //注释
                member.Comments.Add(new CodeCommentStatement(statements[i].ToString()));

                member.Text = memberContent.Replace("[type]", type).Replace("[Name]", key);


                wrapProxyStruct.Members.Add(member);
                i++;
            }

            //生成代码
            CodeDomProvider      provider = CodeDomProvider.CreateProvider("CSharp");
            CodeGeneratorOptions options  = new CodeGeneratorOptions();

            options.BracingStyle             = "C";
            options.BlankLinesBetweenMembers = true;

            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputFile))
            {
                provider.GenerateCodeFromCompileUnit(compunit, sw, options);
            }
        }
Example #14
0
        private static void Json2Class(string fileName, string json, List <object> statements, bool isForSql = false)
        {
            string className = "";

            if (isForSql)
            {
                className = Path.GetFileName(fileName).ToLower().Replace(".xlsx", "_SQL");
            }
            else
            {
                className = Path.GetFileName(fileName).ToLower().Replace(".xlsx", "");
            }
            string outputFile = "";

            if (isForSql)
            {
                outputFile = fileName.Replace(".xlsx", "_SQL.cs");
            }
            else
            {
                outputFile = fileName.Replace(".xlsx", ".cs");
            }

            //生成类服务
            CodeCompileUnit compunit = new CodeCompileUnit();
            CodeNamespace   sample   = new CodeNamespace("Game.Data");

            compunit.Namespaces.Add(sample);
            //引用命名空间
            sample.Imports.Add(new CodeNamespaceImport("System"));
            sample.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
            sample.Imports.Add(new CodeNamespaceImport("Game.Data"));
            //在命名空间下添加一个类
            CodeTypeDeclaration wrapProxyClass = new CodeTypeDeclaration(className);

            //把这个类添加到命名空间
            sample.Types.Add(wrapProxyClass);
            wrapProxyClass.BaseTypes.Add(new CodeTypeReference("LocalDataBase"));

            //
            var jsonData = JsonMapper.ToObject(json)[0];

            int i = 0;

            foreach (var key in jsonData.Keys)
            {
                if (key.ToLower() == "id" && key != "Id")
                {
                    Debug.LogErrorFormat("<color=yellow>表格{0}字段必须为Id[大小写],请修改后生成</color>", className);
                    break;
                }
                else if (key == "Id")
                {
                    i++;
                    continue;
                }
                var value = jsonData[key];

                //字段
                CodeMemberField field = new CodeMemberField();
                field.Attributes = MemberAttributes.Private;
                //属性
                CodeMemberProperty property = new CodeMemberProperty();
                property.Attributes = MemberAttributes.Public | MemberAttributes.Final;;

                CodeTypeReference type = null;
                if (value.IsArray)
                {
                    if (isForSql)
                    {
                        type = new CodeTypeReference(typeof(string));
                    }
                    else
                    {
                        var str = value.ToJson();
                        if (str.IndexOf("\"") > 0)
                        {
                            type = new CodeTypeReference(typeof(List <string>));
                        }
                        else
                        {
                            type = new CodeTypeReference(typeof(List <double>));
                        }
                    }
                }
                else if (value.IsInt)
                {
                    type = new CodeTypeReference(typeof(int));
                }
                else if (value.IsDouble || value.IsLong)
                {
                    type = new CodeTypeReference(typeof(double));
                }
                else if (value.IsBoolean)
                {
                    type = new CodeTypeReference(typeof(bool));
                }
                else if (value.IsString)
                {
                    type = new CodeTypeReference(typeof(string));
                }

                //字段
                field.Type = type;
                field.Name = "_" + key;
                //属性
                property.Type   = type;
                property.Name   = key;
                property.HasGet = true;
                property.HasSet = true;

                property.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), field.Name)));
                property.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), field.Name), new CodePropertySetValueReferenceExpression()));

                property.Comments.Add(new CodeCommentStatement(statements[i].ToString()));

                //
                wrapProxyClass.Members.Add(field);
                wrapProxyClass.Members.Add(property);
                i++;
            }

            //生成代码
            CodeDomProvider      provider = CodeDomProvider.CreateProvider("CSharp");
            CodeGeneratorOptions options  = new CodeGeneratorOptions();

            options.BracingStyle             = "C";
            options.BlankLinesBetweenMembers = true;

            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputFile))
            {
                provider.GenerateCodeFromCompileUnit(compunit, sw, options);
            }
        }
Example #15
0
        public string GenerateCode()
        {
            _codeTransformer.Initialize(this, _directives);

            // Create the engine
            RazorTemplateEngine engine = new RazorTemplateEngine(this);

            // Generate code
            GeneratorResults results = null;

            try
            {
                Stream stream = File.OpenRead(_fullPath);
                using (var reader = new StreamReader(stream, Encoding.Default, detectEncodingFromByteOrderMarks: true))
                {
                    results = engine.GenerateCode(reader, className: DefaultClassName, rootNamespace: DefaultNamespace, sourceFileName: _fullPath);
                }
            }
            catch (Exception e)
            {
                OnGenerateError(4, e.ToString(), 1, 1);
                //Returning null signifies that generation has failed
                return(null);
            }

            // Output errors
            foreach (RazorError error in results.ParserErrors)
            {
                OnGenerateError(4, error.Message, (uint)error.Location.LineIndex + 1, (uint)error.Location.CharacterIndex + 1);
            }

            try
            {
                OnCodeCompletion(50, 100);

                using (StringWriter writer = new StringWriter())
                {
                    CodeGeneratorOptions options = new CodeGeneratorOptions();
                    options.BlankLinesBetweenMembers = false;
                    options.BracingStyle             = "C";

                    //Generate the code
                    writer.WriteLine(CodeLanguageUtil.GetPreGeneratedCodeBlock());
                    _codeDomProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, writer, options);
                    writer.WriteLine(CodeLanguageUtil.GetPostGeneratedCodeBlock());

                    OnCodeCompletion(100, 100);
                    writer.Flush();

                    // Perform output transformations and return
                    string codeContent = writer.ToString();
                    codeContent = _codeTransformer.ProcessOutput(codeContent);
                    return(codeContent);
                }
            }
            catch (Exception e)
            {
                OnGenerateError(4, e.ToString(), 1, 1);
                //Returning null signifies that generation has failed
                return(null);
            }
        }
Example #16
0
        /// <summary>
        /// MSBuild engine will call this to initialize the factory. This should initialize the factory enough so that the factory can be asked
        ///  whether or not task names can be created by the factory.
        /// </summary>
        public bool Initialize(string taskName, IDictionary <string, TaskPropertyInfo> taskParameters, string taskElementContents, IBuildEngine taskFactoryLoggingHost)
        {
            ErrorUtilities.VerifyThrowArgumentNull(taskName, "taskName");
            ErrorUtilities.VerifyThrowArgumentNull(taskParameters, "taskParameters");

            TaskLoggingHelper log = new TaskLoggingHelper(taskFactoryLoggingHost, taskName);

            log.TaskResources     = AssemblyResources.PrimaryResources;
            log.HelpKeywordPrefix = "MSBuild.";

            if (taskElementContents == null)
            {
                log.LogErrorWithCodeFromResources("Xaml.MissingTaskBody");
                return(false);
            }

            TaskElementContents = taskElementContents.Trim();

            // Attempt to load the task
            TaskParser parser = new TaskParser();

            bool parseSuccessful = parser.Parse(TaskElementContents, taskName);

            TaskName      = parser.GeneratedTaskName;
            TaskNamespace = parser.Namespace;
            TaskGenerator generator = new TaskGenerator(parser);

            CodeCompileUnit dom = generator.GenerateCode();

            string pathToMSBuildBinaries = ToolLocationHelper.GetPathToBuildTools(ToolLocationHelper.CurrentToolsVersion);

            // create the code generator options
            // Since we are running msbuild 12.0 these had better load.
            CompilerParameters compilerParameters = new CompilerParameters
                                                    (
                new string[]
            {
                "System.dll",
                Path.Combine(pathToMSBuildBinaries, "Microsoft.Build.Framework.dll"),
                Path.Combine(pathToMSBuildBinaries, "Microsoft.Build.Utilities.Core.dll"),
                Path.Combine(pathToMSBuildBinaries, "Microsoft.Build.Tasks.Core.dll")
            }

                                                    );

            compilerParameters.GenerateInMemory      = true;
            compilerParameters.TreatWarningsAsErrors = false;

            // create the code provider
            CodeDomProvider codegenerator = CodeDomProvider.CreateProvider("cs");
            CompilerResults results;
            bool            debugXamlTask = Environment.GetEnvironmentVariable("MSBUILDWRITEXAMLTASK") == "1";

            if (debugXamlTask)
            {
                using (StreamWriter outputWriter = new StreamWriter(taskName + "_XamlTask.cs"))
                {
                    CodeGeneratorOptions options = new CodeGeneratorOptions();
                    options.BlankLinesBetweenMembers = true;
                    options.BracingStyle             = "C";

                    codegenerator.GenerateCodeFromCompileUnit(dom, outputWriter, options);
                }

                results = codegenerator.CompileAssemblyFromFile(compilerParameters, taskName + "_XamlTask.cs");
            }
            else
            {
                results = codegenerator.CompileAssemblyFromDom(compilerParameters, new[] { dom });
            }

            try
            {
                _taskAssembly = results.CompiledAssembly;
            }
            catch (FileNotFoundException)
            {
                // This occurs if there is a failure to compile the assembly.  We just pass through because we will take care of the failure below.
            }

            if (_taskAssembly == null)
            {
                StringBuilder errorList = new StringBuilder();
                errorList.AppendLine();
                foreach (CompilerError error in results.Errors)
                {
                    if (error.IsWarning)
                    {
                        continue;
                    }

                    if (debugXamlTask)
                    {
                        errorList.AppendLine(String.Format(Thread.CurrentThread.CurrentUICulture, "({0},{1}) {2}", error.Line, error.Column, error.ErrorText));
                    }
                    else
                    {
                        errorList.AppendLine(error.ErrorText);
                    }
                }

                log.LogErrorWithCodeFromResources("Xaml.TaskCreationFailed", errorList.ToString());
            }

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

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

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

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

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

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

            CodeCompileUnit cu = new CodeCompileUnit();

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

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

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

            CodeDomProvider provider = project.LanguageBinding.GetCodeDomProvider();

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

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

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

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

            return(fileName);
        }
        protected override string CreateProxyFile(DotNetProject dotNetProject, FilePath basePath, string proxyNamespace, string referenceName)
        {
            CodeCompileUnit ccu = new CodeCompileUnit();
            CodeNamespace   cns = new CodeNamespace(proxyNamespace);

            ccu.Namespaces.Add(cns);

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

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

            ServiceContractGenerator generator = new ServiceContractGenerator(ccu);

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

            MetadataSet mset;

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

            CodeDomProvider code_provider = GetProvider(dotNetProject);

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

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

            WsdlImporter importer = new WsdlImporter(mset);

            try {
                ConfigureImporter(importer);
            } catch {
                ;
            }

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

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

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

            using (TextWriter w = File.CreateText(fileSpec)) {
                code_provider.GenerateCodeFromCompileUnit(ccu, w, null);
            }
            return(fileSpec);
        }
Example #19
0
        public static Stetic.CodeGenerationResult GenerateSteticCode(IProgressMonitor monitor, DotNetProject project, ConfigurationSelector configuration)
        {
            if (generating || !GtkDesignInfo.HasDesignedObjects(project))
            {
                return(null);
            }

            using (var timer = Counters.SteticFileGeneratedTimer.BeginTiming()) {
                timer.Trace("Checking references");
                GtkDesignInfo info = GtkDesignInfo.FromProject(project);

                DateTime last_gen_time = File.Exists(info.SteticGeneratedFile) ? File.GetLastWriteTime(info.SteticGeneratedFile) : DateTime.MinValue;

                bool ref_changed = false;

                // Disabled check for changes in referenced assemblies, since it cause too much
                // regeneration of code. If a component has changed in a referenced project, this
                // project may not build, but this can be solved by editing some file in the
                // designer and saving.

/*				foreach (ProjectReference pref in project.References) {
 *                                      if (!pref.IsValid)
 *                                              continue;
 *                                      foreach (string filename in pref.GetReferencedFileNames (configuration)) {
 *                                              if (File.GetLastWriteTime (filename) > last_gen_time) {
 *                                                      ref_changed = true;
 *                                                      break;
 *                                              }
 *                                      }
 *                                      if (ref_changed)
 *                                              break;
 *                              }*/

                // Check if generated code is already up to date.
                if (!ref_changed && last_gen_time >= File.GetLastWriteTime(info.SteticFile))
                {
                    return(null);
                }

                if (info.GuiBuilderProject.HasError)
                {
                    monitor.ReportError(GettextCatalog.GetString("GUI code generation failed for project '{0}'. The file '{1}' could not be loaded.", project.Name, info.SteticFile), null);
                    monitor.AsyncOperation.Cancel();
                    return(null);
                }

                if (info.GuiBuilderProject.IsEmpty)
                {
                    return(null);
                }

                monitor.Log.WriteLine(GettextCatalog.GetString("Generating GUI code for project '{0}'...", project.Name));

                timer.Trace("Copy support files");

                // Make sure the referenced assemblies are up to date. It is necessary to do
                // it now since they may contain widget libraries.
                project.CopySupportFiles(monitor, configuration);

                timer.Trace("Update libraries");

                info.GuiBuilderProject.UpdateLibraries();

                ArrayList projects = new ArrayList();
                projects.Add(info.GuiBuilderProject.File);

                generating = true;
                Stetic.CodeGenerationResult generationResult = null;
                Exception generatedException = null;

                bool canGenerateInProcess = IsolationMode != Stetic.IsolationMode.None || info.GuiBuilderProject.SteticProject.CanGenerateCode;

                if (!canGenerateInProcess)
                {
                    timer.Trace("Generating out of process");

                    // Run the generation in another thread to avoid freezing the GUI
                    System.Threading.ThreadPool.QueueUserWorkItem(delegate {
                        try {
                            // Generate the code in another process if stetic is not isolated
                            CodeGeneratorProcess cob = (CodeGeneratorProcess)Runtime.ProcessService.CreateExternalProcessObject(typeof(CodeGeneratorProcess), false);
                            using (cob) {
                                generationResult = cob.GenerateCode(projects, info.GenerateGettext, info.GettextClass, info.ImageResourceLoaderClass, project.UsePartialTypes);
                            }
                        } catch (Exception ex) {
                            generatedException = ex;
                        } finally {
                            generating = false;
                        }
                    });

                    while (generating)
                    {
                        DispatchService.RunPendingEvents();
                        System.Threading.Thread.Sleep(100);
                    }
                }
                else
                {
                    timer.Trace("Generating in-process");
                    // No need to create another process, since stetic has its own backend process
                    // or the widget libraries have no custom wrappers
                    try {
                        Stetic.GenerationOptions options = new Stetic.GenerationOptions();
                        options.UseGettext               = info.GenerateGettext;
                        options.GettextClass             = info.GettextClass;
                        options.ImageResourceLoaderClass = info.ImageResourceLoaderClass;
                        options.UsePartialClasses        = project.UsePartialTypes;
                        options.GenerateSingleFile       = false;
                        options.GenerateModifiedOnly     = true;
                        generationResult = SteticApp.GenerateProjectCode(options, info.GuiBuilderProject.SteticProject);
                        info.GuiBuilderProject.SteticProject.ResetModifiedWidgetFlags();
                    } catch (Exception ex) {
                        generatedException = ex;
                    }
                    generating = false;
                }
                timer.Trace("Writing code units");

                if (generatedException != null)
                {
                    LoggingService.LogError("GUI code generation failed", generatedException);
                    throw new UserException("GUI code generation failed: " + generatedException.Message);
                }

                if (generationResult == null)
                {
                    return(null);
                }

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

                string basePath = Path.GetDirectoryName(info.SteticGeneratedFile);
                string ext      = Path.GetExtension(info.SteticGeneratedFile);

                var pol = project.Policies.Get <TextStylePolicy> ();
                var codeGeneratorOptions = new CodeGeneratorOptions()
                {
                    IndentString             = pol.TabsToSpaces? new string (' ', pol.TabWidth) : "\t",
                    BlankLinesBetweenMembers = true
                };

                foreach (Stetic.SteticCompilationUnit unit in generationResult.Units)
                {
                    string fname;
                    if (unit.Name.Length == 0)
                    {
                        fname = info.SteticGeneratedFile;
                    }
                    else
                    {
                        fname = Path.Combine(basePath, unit.Name) + ext;
                    }
                    StringWriter sw = new StringWriter();
                    try {
                        foreach (CodeNamespace ns in unit.Namespaces)
                        {
                            ns.Comments.Add(new CodeCommentStatement("This file has been generated by the GUI designer. Do not modify."));
                        }
                        timer.Trace("Generating code for " + unit.Name);
                        provider.GenerateCodeFromCompileUnit(unit, sw, codeGeneratorOptions);
                        string content = sw.ToString();

                        timer.Trace("Formatting code");
                        content = FormatGeneratedFile(fname, content, project, provider);
                        timer.Trace("Writing code");
                        File.WriteAllText(fname, content);
                    } finally {
                        timer.Trace("Notifying changes");
                        FileService.NotifyFileChanged(fname);
                    }
                }

                timer.Trace("Updating GTK folder");

                // Make sure the generated files are added to the project
                if (info.UpdateGtkFolder())
                {
                    Gtk.Application.Invoke(delegate {
                        IdeApp.ProjectOperations.Save(project);
                    });
                }

                return(generationResult);
            }
        }
Example #20
0
        internal static void GenerateCode(string rootType, string rootNs, CodeTypeReference baseType,
                                          IDictionary <string, CodeTypeReference> namesAndTypes, string outFile)
        {
            if (rootType == null)
            {
                File.WriteAllText(outFile, "");
                return;
            }

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

            ccu.Namespaces.Add(declNs);

            declNs.Imports.Add(new CodeNamespaceImport("System"));
            declNs.Imports.Add(new CodeNamespaceImport("Xamarin.Forms"));
            declNs.Imports.Add(new CodeNamespaceImport("Xamarin.Forms.Xaml"));

            var declType = new CodeTypeDeclaration(rootType);

            declType.IsPartial = true;
            declType.BaseTypes.Add(baseType);

            declNs.Types.Add(declType);

            var initcomp = new CodeMemberMethod
            {
                Name             = "InitializeComponent",
                CustomAttributes =
                {
                    new CodeAttributeDeclaration(new CodeTypeReference(typeof(GeneratedCodeAttribute)),
                                                 new CodeAttributeArgument(new CodePrimitiveExpression("Xamarin.Forms.Build.Tasks.XamlG")),
                                                 new CodeAttributeArgument(new CodePrimitiveExpression("0.0.0.0")))
                }
            };

            declType.Members.Add(initcomp);

            initcomp.Statements.Add(new CodeMethodInvokeExpression(
                                        new CodeThisReferenceExpression(),
                                        "LoadFromXaml", new CodeTypeOfExpression(declType.Name)));

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

                var field = new CodeMemberField
                {
                    Name             = name,
                    Type             = type,
                    CustomAttributes =
                    {
                        new CodeAttributeDeclaration(new CodeTypeReference(typeof(GeneratedCodeAttribute)),
                                                     new CodeAttributeArgument(new CodePrimitiveExpression("Xamarin.Forms.Build.Tasks.XamlG")),
                                                     new CodeAttributeArgument(new CodePrimitiveExpression("0.0.0.0")))
                    }
                };

                declType.Members.Add(field);

                var find_invoke = new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(
                        new CodeThisReferenceExpression(),
                        "FindByName", type), new CodePrimitiveExpression(name));

                //CodeCastExpression cast = new CodeCastExpression (type, find_invoke);

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

                initcomp.Statements.Add(assign);
            }

            using (var writer = new StreamWriter(outFile))
                Provider.GenerateCodeFromCompileUnit(ccu, writer, new CodeGeneratorOptions());
        }
Example #21
0
        public static void CSharpCode(string pathName, DynamicJsonObject code)
        {
            // namespace
            foreach (var ns in code.Dictionary)
            {
                var compileUnit = new CodeCompileUnit();
                var nameSpace   = new CodeNamespace(ns.Key);
                compileUnit.Namespaces.Add(nameSpace);
                nameSpace.Imports.Add(new CodeNamespaceImport("System"));
                nameSpace.Imports.Add(new CodeNamespaceImport("System.IO"));
                nameSpace.Imports.Add(new CodeNamespaceImport("System.Linq"));
                nameSpace.Imports.Add(new CodeNamespaceImport("System.Collections"));
                nameSpace.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
                var q = ns.Value as Dictionary <string, object>;
                foreach (var cl in q)
                {
                    // enum
                    if (cl.Key.StartsWith("enum"))
                    {
                        var enumName = cl.Key.Split(' ');
                        if (enumName[0].Equals("enum"))
                        {
                            var generateEnum = new CodeTypeDeclaration(enumName[1]);
                            nameSpace.Types.Add(generateEnum);
                            generateEnum.IsEnum = true;
                            var m = cl.Value as Dictionary <string, object>;
                            foreach (var mem in m)
                            {
                                CodeMemberField m1 = new CodeMemberField();
                                m1.Name       = mem.Key;
                                m1.Attributes = MemberAttributes.Public;
                                generateEnum.Members.Add(m1);
                            }
                        }
                    }
                    // class
                    else
                    {
                        var generateClass = new CodeTypeDeclaration(cl.Key);
                        generateClass.IsClass   = true;
                        generateClass.IsPartial = true;

                        nameSpace.Types.Add(generateClass);
                        // member
                        var m = cl.Value as Dictionary <string, object>;
                        foreach (var mem in m)
                        {
                            var property = new CodeMemberProperty();
                            property.Name = mem.Key;
                            SetMemberType(property, mem.Value.ToString());
                            property.HasSet     = true;
                            property.HasGet     = true;
                            property.Attributes = MemberAttributes.Final | MemberAttributes.Public;
                            generateClass.Members.Add(property);
                        }
                    }
                    CodeDomProvider      provider = CodeDomProvider.CreateProvider(codeLanguage);
                    CodeGeneratorOptions options  = new CodeGeneratorOptions();
                    options.BracingStyle             = "C";
                    options.BlankLinesBetweenMembers = false;
                    using (var sw = new StreamWriter(pathName))
                    {
                        provider.GenerateCodeFromCompileUnit(compileUnit, sw, options);
                    }
                }
            }
        }
        static void CreateGenericsCode(string providerName, string sourceFileName, string assemblyName)
        {
            CodeDomProvider provider = CodeDomProvider.CreateProvider(providerName);

            LogMessage("Building CodeDOM graph...");

            CodeCompileUnit cu = new CodeCompileUnit();

            CreateGraph(provider, cu);

            StringWriter sw = new StringWriter();

            LogMessage("Generating code...");
            provider.GenerateCodeFromCompileUnit(cu, sw, null);

            string output = sw.ToString();

            output = Regex.Replace(output, "Runtime Version:[^\r\n]*",
                                   "Runtime Version omitted for demo");

            LogMessage("Dumping source...");
            LogMessage(output);

            LogMessage("Writing source to file...");
            Stream       s = File.Open(sourceFileName, FileMode.Create);
            StreamWriter t = new StreamWriter(s);

            t.Write(output);
            t.Close();
            s.Close();

            CompilerParameters opt = new CompilerParameters(new string[] {
                "System.dll",
                "System.Xml.dll",
                "System.Windows.Forms.dll",
                "System.Data.dll",
                "System.Drawing.dll"
            });

            opt.GenerateExecutable      = false;
            opt.TreatWarningsAsErrors   = true;
            opt.IncludeDebugInformation = true;
            opt.GenerateInMemory        = true;

            CompilerResults results;

            LogMessage("Compiling with " + providerName);
            results = provider.CompileAssemblyFromFile(opt, sourceFileName);

            OutputResults(results);
            if (results.NativeCompilerReturnValue != 0)
            {
                LogMessage("");
                LogMessage("Compilation failed.");
            }
            else
            {
                LogMessage("");
                LogMessage("Demo completed successfully.");
            }
            File.Delete(sourceFileName);
        }
Example #23
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);
        }
Example #24
0
        void Run(string [] args)
        {
            co.ProcessArgs(args);
            if (co.Usage)
            {
                co.DoUsage();
                return;
            }

            if (co.Version)
            {
                co.DoVersion();
                return;
            }

            if (co.Help || co.RemainingArguments.Count == 0)
            {
                co.DoHelp();
                return;
            }
            if (!co.NoLogo)
            {
                co.ShowBanner();
            }

            CodeCompileUnit ccu = new CodeCompileUnit();
            CodeNamespace   cns = new CodeNamespace(co.Namespace);

            ccu.Namespaces.Add(cns);

            generator          = new ServiceContractGenerator(ccu);
            generator.Options  = GetGenerationOption();
            generator.Options |= ServiceContractGenerationOptions.ChannelInterface;

            code_provider = GetCodeProvider();
            MetadataSet metadata = null;

            // For now only assemblyPath is supported.
            foreach (string arg in co.RemainingArguments)
            {
                if (!File.Exists(arg))
                {
                    Uri uri = null;
                    if (Uri.TryCreate(arg, UriKind.Absolute, out uri))
                    {
                        metadata = ResolveWithDisco(arg);
                        if (metadata == null)
                        {
                            metadata = ResolveWithWSMex(arg);
                        }

                        continue;
                    }
                }
                else
                {
                    FileInfo fi = new FileInfo(arg);
                    switch (fi.Extension)
                    {
                    case ".exe":
                    case ".dll":
                        GenerateContractType(fi.FullName);
                        break;

                    default:
                        throw new NotSupportedException("Not supported file extension: " + fi.Extension);
                    }
                }
            }

            if (metadata != null)
            {
                List <IWsdlImportExtension> list = new List <IWsdlImportExtension> ();
                list.Add(new TransportBindingElementImporter());
                //list.Add (new DataContractSerializerMessageContractImporter ());
                list.Add(new XmlSerializerMessageContractImporter());

                //WsdlImporter importer = new WsdlImporter (metadata, null, list);
                WsdlImporter importer = new WsdlImporter(metadata);
                ServiceEndpointCollection        endpoints = importer.ImportAllEndpoints();
                Collection <ContractDescription> contracts = new Collection <ContractDescription> ();
                if (endpoints.Count > 0)
                {
                    foreach (var se in endpoints)
                    {
                        contracts.Add(se.Contract);
                    }
                }
                else
                {
                    foreach (var cd in importer.ImportAllContracts())
                    {
                        contracts.Add(cd);
                    }
                }

                Console.WriteLine("Generating files..");

                // FIXME: could better become IWsdlExportExtension
                foreach (ContractDescription cd in contracts)
                {
                    if (co.GenerateMoonlightProxy)
                    {
                        var moonctx = new MoonlightChannelBaseContext();
                        cd.Behaviors.Add(new MoonlightChannelBaseContractExtension(moonctx, co.GenerateMonoTouchProxy));
                        foreach (var od in cd.Operations)
                        {
                            od.Behaviors.Add(new MoonlightChannelBaseOperationExtension(moonctx, co.GenerateMonoTouchProxy));
                        }
                        generator.GenerateServiceContractType(cd);
                        moonctx.Fixup();
                    }
                    else
                    {
                        generator.GenerateServiceContractType(cd);
                    }
                }
            }

            /*if (cns.Types.Count == 0) {
             *      Console.Error.WriteLine ("Argument assemblies have no types.");
             *      Environment.Exit (1);
             * }*/

            //FIXME: Generate .config

            Console.WriteLine(GetOutputFilename());
            using (TextWriter w = File.CreateText(GetOutputFilename())) {
                code_provider.GenerateCodeFromCompileUnit(ccu, w, null);
            }
        }
Example #25
0
        // TODO: Convert some internal parameters to members?
        public string GenerateCode(string codeNamespace, MessageData messages, string className)
        {
            this.defaultNamespace = codeNamespace;
            this.className        = className;

            // We use "string" so much that we have a common reference...
            CodeTypeReference stringRef = new CodeTypeReference(typeof(string));

            CodeCompileUnit compileUnit = new CodeCompileUnit();

            CodeNamespace cns = new CodeNamespace(codeNamespace);

            cns.Imports.Add(new CodeNamespaceImport("System"));
            CodeTypeDeclarationCollection types = cns.Types;

            compileUnit.Namespaces.Add(cns);

            CodeTypeDeclaration theClass    = new CodeTypeDeclaration(className);
            CodeTypeReference   theClassRef = new CodeTypeReference(new CodeTypeParameter(className));

            theClass.IsClass        = true;
            theClass.TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed;

            types.Add(theClass);

            theClass.Comments.Add(
                new CodeCommentStatement(
                    string.Format(
                        "<summary>{0} generated messages class.</summary>",
                        className),
                    true));

            theClass.Comments.Add(
                new CodeCommentStatement(
                    "<remarks>To change any behavior in this class, the code generator will need to change.</remarks>",
                    true));

            CodeMethodReferenceExpression resManGetString = this.CreateResourceManager(theClass);
            CodeFieldReferenceExpression  resCultureRef   = this.CreateResourceCulture(theClass);

            // Add the message types (error, warning, verbose...)
            string messageTypeName           = string.Concat(className, "Type");
            CodeTypeDeclaration messageTypes = new CodeTypeDeclaration(messageTypeName);

            messageTypes.IsEnum         = true;
            messageTypes.TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed;
            theClass.Members.Add(messageTypes);

            messageTypes.Comments.Add(
                new CodeCommentStatement(
                    "<summary>The allowable types of messages.</summary>",
                    true));

            messageTypes.Comments.Add(
                new CodeCommentStatement(
                    "<remarks>To change this list, add 'type' lines to your source file.</remarks>",
                    true));

            CodeTypeReferenceExpression messageTypeRef = new CodeTypeReferenceExpression(messageTypeName);
            Dictionary <MessageType, CodeFieldReferenceExpression> typeReferences = new Dictionary <MessageType, CodeFieldReferenceExpression>();

            foreach (MessageType sourceMessageType in messages.Types)
            {
                CodeMemberField typeField = new CodeMemberField();
                // We capitalize the message type's first letter for the code.
                typeField.Name = string.Concat(
                    sourceMessageType.Name[0].ToString().ToUpperInvariant(),
                    sourceMessageType.Name.Substring(1));

                messageTypes.Members.Add(typeField);

                typeField.Comments.Add(
                    new CodeCommentStatement(
                        string.Format(
                            "<summary>'{0}' message range: {1}-{2}</summary>",
                            sourceMessageType.Name,
                            sourceMessageType.FirstId,
                            sourceMessageType.LastId),
                        true));

                typeReferences.Add(sourceMessageType, new CodeFieldReferenceExpression(messageTypeRef, typeField.Name));
            }

            CodeConstructor classConstructor = new CodeConstructor();

            classConstructor.Attributes = MemberAttributes.Private;
            theClass.Members.Add(classConstructor);

            // Add the members and private constructor...
            this.CreateProperty(theClass, classConstructor, "Type", new CodeTypeReference(messageTypeName), "Gets the type (error/warning/verbose) of the message");
            this.CreateProperty(theClass, classConstructor, "Id", new CodeTypeReference(typeof(int)), "Gets the ID of the message.");
            this.CreateProperty(theClass, classConstructor, "Name", stringRef, "Gets the name of the message.");
            this.CreateProperty(theClass, classConstructor, "Message", stringRef, "Get the message text for the message.");

            foreach (var message in messages.Messages)
            {
                if (message.Type == null)
                {
                    // TODO: throw an error?  Skip?
                    continue;
                }

                CodeFieldReferenceExpression messageType = typeReferences[message.Type];

                foreach (var instance in message.Instances)
                {
                    CodeMemberMethod method = new CodeMemberMethod();
                    method.Attributes = MemberAttributes.Public | MemberAttributes.Static | MemberAttributes.Final; // final == non-virtual?
                    method.ReturnType = theClassRef;
                    method.Name       = message.Name;
                    method.LinePragma = new CodeLinePragma(messages.Filename, instance.PragmaLine);

                    theClass.Members.Add(method);

                    string messageVarName = "message";

                    // Ensure we don't have any variable name collisions...
                    if (instance.ParameterList.Count > 0)
                    {
                        messageVarName = "messageFormat";
                        string messageVarNameBase = messageVarName;
                        int    suffixCount        = 1;
                        while (instance.ParameterList.Any(t => string.Equals(t.Item1, messageVarName, StringComparison.Ordinal)))
                        {
                            messageVarName = string.Concat(messageVarNameBase, (++suffixCount).ToString());
                        }
                    }

                    ////// TODO: Inject an error if there was an error in the source file?
                    ////// This would help avoid missing these errors in a command-line scenario...
                    ////if (!string.IsNullOrEmpty(message.Error))
                    ////{
                    ////    method.Statements.Add(new CodePrimitiveExpression("ERROR!"));
                    ////    method.Statements.Add(new CodePrimitiveExpression(message.Error));
                    ////    method.Statements.Add(new CodePrimitiveExpression("ERROR!"));
                    ////}

                    ////// TODO: Inject an error if there was an error in the source file?
                    ////// This would help avoid missing these errors in a command-line scenario...
                    ////if (!string.IsNullOrEmpty(instance.Error))
                    ////{
                    ////    method.Statements.Add(new CodePrimitiveExpression("ERROR!"));
                    ////    method.Statements.Add(new CodePrimitiveExpression(instance.Error));
                    ////    method.Statements.Add(new CodePrimitiveExpression("ERROR!"));
                    ////}

                    // Get the string from the generated resources...
                    method.Statements.Add(
                        new CodeVariableDeclarationStatement(
                            stringRef,
                            messageVarName,
                            new CodeMethodInvokeExpression(
                                resManGetString,
                                new CodePrimitiveExpression(string.Concat(this.className, ".", instance.Name)),
                                resCultureRef)));

                    // Default the return expression to just the message itself.
                    CodeExpression messageExpression = new CodeVariableReferenceExpression(messageVarName);

                    // If we've got parameterList, we need a more complex expression.
                    if (instance.ParameterList.Count > 0)
                    {
                        List <CodeExpression> formatParameters = new List <CodeExpression>();

                        formatParameters.Add(messageExpression);

                        instance.ParameterList.ForEach(t =>
                        {
                            method.Parameters.Add(
                                new CodeParameterDeclarationExpression(
                                    new CodeTypeReference(t.Item2),
                                    t.Item1));

                            formatParameters.Add(new CodeVariableReferenceExpression(t.Item1));
                        });

                        messageExpression = new CodeMethodInvokeExpression(
                            new CodeTypeReferenceExpression(stringRef),
                            "Format",
                            formatParameters.ToArray());
                    }

                    method.Statements.Add(new CodeMethodReturnStatement(
                                              new CodeObjectCreateExpression(
                                                  theClassRef,
                                                  messageType,                               // type
                                                  new CodePrimitiveExpression(message.Id),   // id
                                                  new CodePrimitiveExpression(message.Name), // name
                                                  messageExpression)));                      // message
                }
            }

            // Create the code...
            string output = null;

            using (CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"))
            {
                CodeGeneratorOptions options = new CodeGeneratorOptions();
                options.BracingStyle = "C";

                using (StringWriter sourceWriter = new StringWriter())
                {
                    provider.GenerateCodeFromCompileUnit(compileUnit, sourceWriter, options);
                    output = sourceWriter.ToString();
                }
            }

            return(output);
        }
        private Assembly CompileInMemoryAssembly()
        {
            List <string> finalReferenceList = new List <string>();

            this.CombineReferencedAssemblies(finalReferenceList);
            string[] strArray = this.CombineUsingNamespaces();
            using (CodeDomProvider provider = CodeDomProvider.CreateProvider(this.language))
            {
                if (provider is CSharpCodeProvider)
                {
                    this.AddReferenceAssemblyToReferenceList(finalReferenceList, "System");
                }
                CompilerParameters parameters = new CompilerParameters(finalReferenceList.ToArray())
                {
                    IncludeDebugInformation = true,
                    GenerateInMemory        = true,
                    GenerateExecutable      = false
                };
                StringBuilder        sb      = new StringBuilder();
                StringWriter         writer  = new StringWriter(sb, CultureInfo.CurrentCulture);
                CodeGeneratorOptions options = new CodeGeneratorOptions {
                    BlankLinesBetweenMembers = true,
                    VerbatimOrder            = true
                };
                CodeCompileUnit compileUnit = new CodeCompileUnit();
                if (this.sourcePath != null)
                {
                    this.sourceCode = File.ReadAllText(this.sourcePath);
                }
                string sourceCode = this.sourceCode;
                if (this.typeIsFragment || this.typeIsMethod)
                {
                    CodeTypeDeclaration codeTypeDeclaration = this.CreateTaskClass();
                    this.CreateTaskProperties(codeTypeDeclaration);
                    if (this.typeIsFragment)
                    {
                        CreateExecuteMethodFromFragment(codeTypeDeclaration, this.sourceCode);
                    }
                    else
                    {
                        CreateTaskBody(codeTypeDeclaration, this.sourceCode);
                    }
                    CodeNamespace namespace2 = new CodeNamespace("InlineCode");
                    foreach (string str2 in strArray)
                    {
                        namespace2.Imports.Add(new CodeNamespaceImport(str2));
                    }
                    namespace2.Types.Add(codeTypeDeclaration);
                    compileUnit.Namespaces.Add(namespace2);
                    provider.GenerateCodeFromCompileUnit(compileUnit, writer, options);
                }
                else
                {
                    provider.GenerateCodeFromStatement(new CodeSnippetStatement(this.sourceCode), writer, options);
                }
                sourceCode = sb.ToString();
                CompilerResults results = provider.CompileAssemblyFromSource(parameters, new string[] { sourceCode });
                string          path    = null;
                if ((results.Errors.Count > 0) || (Environment.GetEnvironmentVariable("MSBUILDLOGCODETASKFACTORYOUTPUT") != null))
                {
                    string tempPath = Path.GetTempPath();
                    string str5     = "MSBUILDCodeTaskFactoryGeneratedFile" + Guid.NewGuid().ToString() + ".txt";
                    path = Path.Combine(tempPath, str5);
                    File.WriteAllText(path, sourceCode);
                }
                if ((results.NativeCompilerReturnValue != 0) && (results.Errors.Count > 0))
                {
                    this.log.LogErrorWithCodeFromResources("CodeTaskFactory.FindSourceFileAt", new object[] { path });
                    foreach (CompilerError error in results.Errors)
                    {
                        this.log.LogErrorWithCodeFromResources("CodeTaskFactory.CompilerError", new object[] { error.ToString() });
                    }
                    return(null);
                }
                return(results.CompiledAssembly);
            }
        }
Example #27
0
    static void Run()
    {
        // Get a WSDL file describing a service.
        ServiceDescription description = ServiceDescription.Read("DataTypes_CS.wsdl");

        // Initialize a service description importer.
        ServiceDescriptionImporter importer = new ServiceDescriptionImporter();

        importer.ProtocolName = "Soap12"; // Use SOAP 1.2.
        importer.AddServiceDescription(description, null, null);

        // Report on the service descriptions.
        Console.WriteLine("Importing {0} service descriptions with {1} associated schemas.",
                          importer.ServiceDescriptions.Count, importer.Schemas.Count);

        // Generate a proxy client.
        importer.Style = ServiceDescriptionImportStyle.Client;

        // Generate properties to represent primitive values.
        importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;

        // Initialize a Code-DOM tree into which we will import the service.
        CodeNamespace   nmspace = new CodeNamespace();
        CodeCompileUnit unit1   = new CodeCompileUnit();

        unit1.Namespaces.Add(nmspace);

        // Import the service into the Code-DOM tree. This creates proxy code
        // that uses the service.
        ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);

        if (warning == 0)
        {
            // Generate and print the proxy code in C#.
            CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");
            provider1.GenerateCodeFromCompileUnit(unit1, Console.Out, new CodeGeneratorOptions());
        }
        else
        {
            // Print an error message.
            Console.WriteLine("Warning: " + warning);
        }


        string url = "AddNumbers.wsdl";

// <snippet1>
        // Read in a WSDL service description.
        XmlTextReader      reader = new XmlTextReader(url);
        ServiceDescription wsdl   = ServiceDescription.Read(reader);
// </snippet1>

// <snippet2>
        // Create a WSDL collection.
        DiscoveryClientDocumentCollection wsdlCollection = new DiscoveryClientDocumentCollection();

        wsdlCollection.Add(url, wsdl);
// </snippet2>

// <snippet3>
        // Create a namespace and a unit for compilation.
        CodeNamespace   space = new CodeNamespace();
        CodeCompileUnit unit  = new CodeCompileUnit();

        unit.Namespaces.Add(space);
// </snippet3>

// <snippet4>
        // Create a web referernce using the WSDL collection.
        WebReference reference = new WebReference(wsdlCollection, space);

        reference.ProtocolName = "Soap12";
// </snippet4>

// <snippet5>
        // Print some information about the web reference.
        Console.WriteLine("Base Url = {0}", reference.AppSettingBaseUrl);
        Console.WriteLine("Url Key = {0}", reference.AppSettingUrlKey);
        Console.WriteLine("Documents = {0}", reference.Documents.Count);
// </snippet5>

// <snippet6>
        // Create a web reference collection.
        WebReferenceCollection references = new WebReferenceCollection();

        references.Add(reference);
// </snippet6>

// <snippet7>
        // Compile a proxy client and print out the code.
        CodeDomProvider     provider = CodeDomProvider.CreateProvider("CSharp");
        WebReferenceOptions options  = new WebReferenceOptions();

        options.Style = ServiceDescriptionImportStyle.Client;
        options.CodeGenerationOptions = CodeGenerationOptions.GenerateNewAsync;
        ServiceDescriptionImporter.GenerateWebReferences(
            references,
            provider,
            unit,
            options
            );
        provider.GenerateCodeFromCompileUnit(unit, Console.Out, new CodeGeneratorOptions());
// </snippet7>
    }
Example #28
0
        public static BuildResult GenerateFile(CodeDomProvider provider, string app_name,
                                               string xaml_file, string xaml_path_in_project, string out_file)
        {
            XmlDocument xmldoc = new XmlDocument();

            xmldoc.Load(xaml_file);

            BuildResult result = new BuildResult();

            XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmldoc.NameTable);

            nsmgr.AddNamespace("x", "http://schemas.microsoft.com/winfx/2006/xaml");

            XmlNode root = xmldoc.SelectSingleNode("/*", nsmgr);

            if (root == null)
            {
                result.AddError(xaml_file, 0, 0, "", "No root node found.");
                return(result);
            }

            XmlAttribute root_class = root.Attributes ["x:Class"];

            if (root_class == null)
            {
                File.WriteAllText(out_file, "");
                return(result);
            }

            bool   is_application = root.LocalName == "Application";
            string root_ns;
            string root_type;
            string root_asm;

            ParseXmlns(root_class.Value, out root_type, out root_ns, out root_asm);

            Hashtable names_and_types = GetNamesAndTypes(root, nsmgr);
//			Hashtable keys_and_types = GetKeysAndTypes (root, nsmgr);

            CodeCompileUnit ccu     = new CodeCompileUnit();
            CodeNamespace   decl_ns = new CodeNamespace(root_ns);

            ccu.Namespaces.Add(decl_ns);

            decl_ns.Imports.Add(new CodeNamespaceImport("System"));
            decl_ns.Imports.Add(new CodeNamespaceImport("System.Windows"));
            decl_ns.Imports.Add(new CodeNamespaceImport("System.Windows.Controls"));
            decl_ns.Imports.Add(new CodeNamespaceImport("System.Windows.Documents"));
            decl_ns.Imports.Add(new CodeNamespaceImport("System.Windows.Input"));
            decl_ns.Imports.Add(new CodeNamespaceImport("System.Windows.Media"));
            decl_ns.Imports.Add(new CodeNamespaceImport("System.Windows.Media.Animation"));
            decl_ns.Imports.Add(new CodeNamespaceImport("System.Windows.Shapes"));
            decl_ns.Imports.Add(new CodeNamespaceImport("System.Windows.Controls.Primitives"));

            CodeTypeDeclaration decl_type = new CodeTypeDeclaration(root_type);

            decl_type.IsPartial = true;

            decl_ns.Types.Add(decl_type);

            CodeMemberMethod initcomp = new CodeMemberMethod();

            initcomp.Name = "InitializeComponent";
            decl_type.Members.Add(initcomp);

            if (sl2)
            {
                CodeMemberField field = new CodeMemberField();
                field.Name = "_contentLoaded";
                field.Type = new CodeTypeReference(typeof(bool));

                decl_type.Members.Add(field);

                CodeConditionStatement is_content_loaded = new CodeConditionStatement(new CodeVariableReferenceExpression("_contentLoaded"),
                                                                                      new CodeStatement [] { new CodeMethodReturnStatement() });
                initcomp.Statements.Add(is_content_loaded);

                CodeAssignStatement set_content_loaded = new CodeAssignStatement(new CodeVariableReferenceExpression("_contentLoaded"),
                                                                                 new CodePrimitiveExpression(true));

                initcomp.Statements.Add(set_content_loaded);

                string component_path = String.Format("/{0};component/{1}", app_name, xaml_path_in_project);
                CodeMethodInvokeExpression load_component = new CodeMethodInvokeExpression(
                    new CodeTypeReferenceExpression("System.Windows.Application"), "LoadComponent",
                    new CodeExpression [] { new CodeThisReferenceExpression(),
                                            new CodeObjectCreateExpression(new CodeTypeReference("System.Uri"), new CodeExpression [] {
                        new CodePrimitiveExpression(component_path),
                        new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.UriKind"), "Relative")
                    }) });
                initcomp.Statements.Add(load_component);
            }

            if (!is_application)
            {
                foreach (DictionaryEntry entry  in names_and_types)
                {
                    string            name = (string)entry.Key;
                    CodeTypeReference type = (CodeTypeReference)entry.Value;

                    CodeMemberField field = new CodeMemberField();

                    if (sl2)
                    {
                        field.Attributes = MemberAttributes.Assembly;
                    }

                    field.Name = name;
                    field.Type = type;

                    decl_type.Members.Add(field);

                    CodeMethodInvokeExpression find_invoke = new CodeMethodInvokeExpression(
                        new CodeThisReferenceExpression(), "FindName",
                        new CodeExpression[] { new CodePrimitiveExpression(name) });

                    CodeCastExpression cast = new CodeCastExpression(type, find_invoke);

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

                    initcomp.Statements.Add(assign);
                }
            }


            using (StreamWriter writer = new StreamWriter(out_file)) {
                provider.GenerateCodeFromCompileUnit(ccu, writer, new CodeGeneratorOptions());
            }

            return(result);
        }
        /// <summary>
        /// Compile the assembly in memory and get a reference to the assembly itself.
        /// If compilation fails, returns null.
        /// </summary>
        private Assembly CompileInMemoryAssembly()
        {
            // Combine our default assembly references with those specified
            List <string> finalReferencedAssemblies = new List <string>();

            CombineReferencedAssemblies(finalReferencedAssemblies);

            // Combine our default using's with those specified
            string[] finalUsingNamespaces = CombineUsingNamespaces();

            // Language can be anything that has a codedom provider, in the standard naming method
            // "c#;cs;csharp", "vb;vbs;visualbasic;vbscript", "js;jscript;javascript", "vj#;vjs;vjsharp", "c++;mc;cpp"
            using (CodeDomProvider provider = CodeDomProvider.CreateProvider(_language))
            {
                if (provider is CSharp.CSharpCodeProvider)
                {
                    AddReferenceAssemblyToReferenceList(finalReferencedAssemblies, "System");
                }

                var compilerParameters =
                    new CompilerParameters(finalReferencedAssemblies.ToArray())
                {
                    // We don't need debug information
                    IncludeDebugInformation = true,

                    // Not a file based assembly
                    GenerateInMemory = true,

                    // Indicates that a .dll should be generated.
                    GenerateExecutable = false
                };

                // Horrible code dom / compilation declarations
                var codeBuilder          = new StringBuilder();
                var writer               = new StringWriter(codeBuilder, CultureInfo.CurrentCulture);
                var codeGeneratorOptions = new CodeGeneratorOptions
                {
                    BlankLinesBetweenMembers = true,
                    VerbatimOrder            = true
                };
                var compilationUnit = new CodeCompileUnit();

                // If our code is in a separate file, then read it in here
                if (_sourcePath != null)
                {
                    _sourceCode = File.ReadAllText(_sourcePath);
                }

                // A fragment is essentially the contents of the execute method (except the final return true/false)
                // A method is the whole execute method specified
                // Anything else assumes that the whole class is being supplied
                if (_typeIsFragment || _typeIsMethod)
                {
                    CodeTypeDeclaration codeTypeDeclaration = CreateTaskClass();

                    CreateTaskProperties(codeTypeDeclaration);

                    if (_typeIsFragment)
                    {
                        CreateExecuteMethodFromFragment(codeTypeDeclaration, _sourceCode);
                    }
                    else
                    {
                        CreateTaskBody(codeTypeDeclaration, _sourceCode);
                    }

                    var codeNamespace = new CodeNamespace("InlineCode");
                    foreach (string importname in finalUsingNamespaces)
                    {
                        codeNamespace.Imports.Add(new CodeNamespaceImport(importname));
                    }

                    codeNamespace.Types.Add(codeTypeDeclaration);
                    compilationUnit.Namespaces.Add(codeNamespace);

                    // Create the source for the CodeDom
                    provider.GenerateCodeFromCompileUnit(compilationUnit, writer, codeGeneratorOptions);
                }
                else
                {
                    // We are a full class, so just create the CodeDom from the source
                    provider.GenerateCodeFromStatement(new CodeSnippetStatement(_sourceCode), writer, codeGeneratorOptions);
                }

                // Our code generation is complete, grab the source from the builder ready for compilation
                string fullCode = codeBuilder.ToString();

                var fullSpec = new FullTaskSpecification(finalReferencedAssemblies, fullCode);
                if (!s_compiledTaskCache.TryGetValue(fullSpec, out Assembly existingAssembly))
                {
                    // Invokes compilation.

                    // Note: CompileAssemblyFromSource uses Path.GetTempPath() directory, but will not create it. In some cases
                    // this will throw inside CompileAssemblyFromSource. To work around this, ensure the temp directory exists.
                    // See: https://github.com/Microsoft/msbuild/issues/328
                    Directory.CreateDirectory(Path.GetTempPath());

                    CompilerResults compilerResults = provider.CompileAssemblyFromSource(compilerParameters, fullCode);

                    string outputPath = null;
                    if (compilerResults.Errors.Count > 0 || Environment.GetEnvironmentVariable("MSBUILDLOGCODETASKFACTORYOUTPUT") != null)
                    {
                        string tempDirectory = Path.GetTempPath();
                        string fileName      = Guid.NewGuid().ToString() + ".txt";
                        outputPath = Path.Combine(tempDirectory, fileName);
                        File.WriteAllText(outputPath, fullCode);
                    }

                    if (compilerResults.NativeCompilerReturnValue != 0 && compilerResults.Errors.Count > 0)
                    {
                        _log.LogErrorWithCodeFromResources("CodeTaskFactory.FindSourceFileAt", outputPath);

                        foreach (CompilerError e in compilerResults.Errors)
                        {
                            _log.LogErrorWithCodeFromResources("CodeTaskFactory.CompilerError", e.ToString());
                        }

                        return(null);
                    }

                    // Add to the cache.  Failing to add is not a fatal error.
                    s_compiledTaskCache.TryAdd(fullSpec, compilerResults.CompiledAssembly);
                    return(compilerResults.CompiledAssembly);
                }
                else
                {
                    return(existingAssembly);
                }
            }
        }
Example #30
0
    void GenerateCode()
    {
        Directory.CreateDirectory (OutputDir);

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

        CodeTypeDeclaration libDecl = null;

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

            var decl = new CodeTypeDeclaration ("Libs");

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

            ns.Types.Add (decl);

            libDecl = decl;

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

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

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

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

            //Provider.GenerateCodeFromCompileUnit(cu, Console.Out, CodeGenOptions);
            using (TextWriter w = File.CreateText (Path.Combine (OutputDir, klass.Name + ".cs"))) {
                // These are reported for the fields of the native layout structures
                Provider.GenerateCodeFromCompileUnit (new CodeSnippetCompileUnit("#pragma warning disable 0414, 0169"), w, CodeGenOptions);
                Provider.GenerateCodeFromCompileUnit(cu, w, CodeGenOptions);
            }
        }
    }
Example #31
0
        void GenerateCode(string outFilePath)
        {
            //Create the target directory if required
            Directory.CreateDirectory(System.IO.Path.GetDirectoryName(outFilePath));

            var ccu = new CodeCompileUnit();

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

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

            var declNs = new CodeNamespace(RootClrNamespace);

            ccu.Namespaces.Add(declNs);

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

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

            declType.BaseTypes.Add(BaseType);

            declNs.Types.Add(declType);

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

                declType.Members.Add(ctor);
            }

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

            declType.Members.Add(initcomp);

            //Create and initialize fields

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

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

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

                initcomp.Statements.Add(assignEXamlObject);
            }

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

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

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

                initcomp.Statements.Add(assign);
            }

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

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

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

                declType.Members.Add(getEXamlPathcomp);

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