/// <summary>
 /// Verifies that <paramref name="source"/> compiles using the provided compiler.
 /// </summary>
 /// <param name="compiler">Compiler instance</param>
 /// <param name="source">Source code to compile</param>
 public static CompilerResults Compiles(CodeDomProvider provider, Stream source)
 {
     Assert.IsNotNull(provider);
     Assert.IsNotNull(source);
     CompilerParameters ps = new CompilerParameters();
     return Compiles(provider, ps, source);
 }
Example #2
1
        public static Assembly CompileScriptFromSource(string source, CodeDomProvider provider, ref string errors)
        {
            StringBuilder errorLog = new StringBuilder();
            errors = "";
            CompilerParameters compilerParameters = new CompilerParameters();
            compilerParameters.GenerateExecutable = false;
            compilerParameters.GenerateInMemory = true;
            compilerParameters.IncludeDebugInformation = false;
            compilerParameters.ReferencedAssemblies.Add("System.dll");
            compilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            compilerParameters.ReferencedAssemblies.Add("KedrahCore.dll");
            compilerParameters.ReferencedAssemblies.Add("TibiaAPI.dll");
            compilerParameters.ReferencedAssemblies.Add(System.Reflection.Assembly.GetExecutingAssembly().Location);
            CompilerResults results = provider.CompileAssemblyFromSource(compilerParameters, source);
            if (!results.Errors.HasErrors)
            {
                return results.CompiledAssembly;
            }
            else
            {
                foreach (CompilerError error in results.Errors)
                {
                    errorLog.AppendLine(error.ErrorText);
                }
            }

            errors = errorLog.ToString();
            return null;
        }
Example #3
1
        static ReflectionHelper()
        {
            UsingNamespaces = new List<String>();
            ClearUsings();

            // Create the C# Code Provider to compile C# Code
            IDictionary<string, string> providerOptions = new Dictionary<string, string>();
            providerOptions.Add("CompilerVersion", "v3.5");
            CodeProvider = new CSharpCodeProvider(providerOptions);
            CompilerParameters = new CompilerParameters();

            // Generate aclass library instead of an executable
            CompilerParameters.GenerateExecutable = false;

            // Specify the assembly file name to generate.
            CompilerParameters.OutputAssembly = "C:\\DummyAssembly.dll";

            // Save the assembly as a physical file.
            CompilerParameters.GenerateInMemory = false;

            // Set whether to treat all warnings as errors.
            CompilerParameters.TreatWarningsAsErrors = false;

            // Add a reference to the game and System.dll and XNA
            //CompilerParameters.ReferencedAssemblies.Add(typeof(Game).Assembly.FullName);
            ClearReferencedAsseblies();
        }
Example #4
0
 //***************************************************************************
 // Class Constructors
 // 
 /// <summary>
 /// Provides a simple container and methods for building a CodeDOM-based application.
 /// </summary>
 /// <param name="ProviderType">A value of type CodeDomProviderType indicating the type of code provider to use to generate code within this AosDynaCode object.</param>
 /// <param name="NameSpace">A string value indicating the namespace to use when generating code for this AosDynaCode object.</param>
 public DynaCode(CodeDomProviderType ProviderType, string NameSpace)
 {
     provider = GetProvider(ProviderType);
     nsMain = new CodeNamespace(NameSpace);
     compileUnit.Namespaces.Add(nsMain);
     nsMain.Imports.Add(new CodeNamespaceImport("System"));
 }
    public override CodeGeneratorOptions GetGeneratorOptions (CodeDomProvider provider) {
        CodeGeneratorOptions generatorOptions = base.GetGeneratorOptions (provider);
#if WHIDBEY
        generatorOptions.VerbatimOrder = true;
#endif
        return generatorOptions;
    }
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {

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

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

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

            cd.Members.Add (methodMain);
        }
    }
Example #7
0
        public FormulaEvaluator(IEnumerable<Sensor> sensors)
        {
            //Build the code provider
            _codeProvider = new CSharpCodeProvider();

            //Retrieve the sensor variables
            _sensorVariables = sensors.Select(x => x.Variable).ToList();

            //Create the compiler parameters
            _compilerParameters = new CompilerParameters
                                      {
                                          CompilerOptions = "/target:library /optimize",
                                          GenerateExecutable = false,
                                          GenerateInMemory = true,
                                          IncludeDebugInformation = false
                                      };

            //Add the needed references
            _compilerParameters.ReferencedAssemblies.Add("System.dll");
            _compilerParameters.ReferencedAssemblies.Add("System.Core.dll");
            _compilerParameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);

            //Build Math Objects
            _mathMembers = new ArrayList();
            _mathMembersMap = new Hashtable();

            //Populate Math Objects
            GetMathMemberNames();

            //Build String Builder
            _source = new StringBuilder();
        }
 protected TemplateCompilationParameters(RazorCodeLanguage language, CodeDomProvider codeProvider, CompilerParameters compilerParameters = null)
 {
     Language = language;
     CodeProvider = codeProvider;
     CompilerParameters = compilerParameters ?? new CompilerParameters { GenerateInMemory = true };
     AddAssemblyReference(typeof(TemplateBase));
 }
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {

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

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

        CodeMemberMethod cmm = new CodeMemberMethod ();
        cmm.Name = "MethodName";
        cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
        cmm.ReturnType = new CodeTypeReference (typeof (int));
        cmm.Statements.Add (new CodeExpressionStatement (new CodeSnippetExpression ("This is a CODE SNIPPET #*$*@")));
        cmm.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (3)));
        class1.Members.Add (cmm);
    }
Example #10
0
 public static void Init(this IPersistentMemberInfo persistentMemberInfo, Type codeTemplateType, CodeDomProvider codeDomProvider)
 {
     persistentMemberInfo.CodeTemplateInfo.CodeTemplate =CodeTemplateBuilder.CreateDefaultTemplate(
         persistentMemberInfo is IPersistentCollectionMemberInfo
             ? TemplateType.ReadOnlyMember
             : TemplateType.ReadWriteMember, persistentMemberInfo.Session, codeTemplateType,codeDomProvider);
 }
Example #11
0
 private void GenerateTestFile(SpecFlowFeatureFile featureFile, CodeDomProvider codeProvider, TextWriter outputWriter)
 {
     using(var reader = new StreamReader(featureFile.GetFullPath(project)))
     {
         GenerateTestFile(featureFile, codeProvider, reader, outputWriter);
     }
 }
    public override void BuildTree(CodeDomProvider provider, CodeCompileUnit cu) {
        //cu.UserData["AllowLateBound"] = true;

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

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

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

        ns.Types.Add(class1);

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

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

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

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

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

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

            if (Supports (provider, GeneratorSupport.DeclareValueTypes)) {
                AddScenario ("FindSealedPartialStruct", "Attempt to find 'SealedPartialStruct'");
                BuildClassesIntoNamespace (provider, ns, "SealedPartialStruct", ClassTypes.Struct, TypeAttributes.Sealed);
                BuildClassesIntoNamespace (provider, ns, "AbstractPartialStruct", ClassTypes.Struct, TypeAttributes.Abstract);
            }
        }
#endif
    }
 internal SchemaImporter(XmlSchemas schemas, CodeGenerationOptions options, CodeDomProvider codeProvider, System.Xml.Serialization.ImportContext context)
 {
     if (!schemas.Contains("http://www.w3.org/2001/XMLSchema"))
     {
         schemas.AddReference(XmlSchemas.XsdSchema);
         schemas.SchemaSet.Add(XmlSchemas.XsdSchema);
     }
     if (!schemas.Contains("http://www.w3.org/XML/1998/namespace"))
     {
         schemas.AddReference(XmlSchemas.XmlSchema);
         schemas.SchemaSet.Add(XmlSchemas.XmlSchema);
     }
     this.schemas = schemas;
     this.options = options;
     this.codeProvider = codeProvider;
     this.context = context;
     this.Schemas.SetCache(this.Context.Cache, this.Context.ShareTypes);
     SchemaImporterExtensionsSection section = System.Configuration.PrivilegedConfigurationManager.GetSection(ConfigurationStrings.SchemaImporterExtensionsSectionPath) as SchemaImporterExtensionsSection;
     if (section != null)
     {
         this.extensions = section.SchemaImporterExtensionsInternal;
     }
     else
     {
         this.extensions = new SchemaImporterExtensionCollection();
     }
 }
Example #16
0
		/////////////////////////////////////////////////////////////////////////////

		protected CompilerResults Compile(	CodeDomProvider codeProvider,
																				IEnumerable<string> compilerOptions,
																				IList<string> refAssemblies,
																				string assemblyName,
																				IList<string> filesIn,
																				IList<string> sourcesIn
																			)
		{
			// ******
			if( forceDebug ) {
				compilerOptions = ForceDebug( compilerOptions );
			}

	//
	// ??if want debug info then have to make sure code is passed in as a
	// file and library is on disk - currently no matter what we pass in
	// for debug we get "/debug-" in the xxx.cmdline file passed to the
	// compiler
	// 


			// ******
			using( var cb = new CodeCompileRunner(TempFilesDir, KeepTempFiles, codeProvider, compilerOptions) ) {
				var result = cb.Compile( refAssemblies, assemblyName, filesIn, sourcesIn );
				ErrorMessage = cb.ErrorMessage;
				return result;
			}
		}
 public static CodeExpression Is(CodeVariableReferenceExpression var,
     CodeTypeReferenceExpression type, CodeDomProvider provider)
 {
     return new CodeSnippetExpression(
         "((" + ExpressionToString(var, provider) + ") is " +
         ExpressionToString(type, provider) + ")");
 }
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {
        CodeNamespace ns = new CodeNamespace ("Namespace1");
        cu.Namespaces.Add (ns);

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

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

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

        AddScenario ("FindLinedStatement");
        CodeMethodReturnStatement ret = new CodeMethodReturnStatement (new CodePrimitiveExpression (0));
        ret.LinePragma = new CodeLinePragma ("LinedStatement", 300);
        method1.Statements.Add (ret);
    }
 protected TemplateCompilationParameters(RazorCodeLanguage language, CodeDomProvider codeProvider, CompilerParameters compilerParameters = null)
 {
     Language = language;
     CodeProvider = codeProvider;
     CompilerParameters = compilerParameters ?? new CompilerParameters { GenerateInMemory = true };
     CompilerParameters.ReferencedAssemblies.Add(AppDomain.CurrentDomain
                     .GetAssemblies().First(asm => asm.FullName.StartsWith("RazorPad.Web")).Location);
 }
 // courtesy of http://metasharp.net/index.php?title=More_technical_Csharp#Generating_the_.27is.27_operator
 public static string ExpressionToString(CodeExpression expr, CodeDomProvider provider)
 {
     using (TextWriter m = new StringWriter())
     {
         provider.GenerateCodeFromExpression(expr, m, new CodeGeneratorOptions());
         return m.ToString();
     }
 }
 /// <summary>
 /// Verifies that <paramref name="source"/> compiles using the provided compiler.
 /// </summary>
 /// <param name="compiler">Compiler instance</param>
 /// <param name="source">Source code to compile</param>
 public static CompilerResults Compiles(CodeDomProvider provider, string source)
 {
     Assert.IsNotNull(provider);
     Assert.IsNotNull(source);
     CompilerParameters ps = new CompilerParameters();
     ps.GenerateInMemory = true;
     return Compiles(provider, ps, source);
 }
Example #22
0
		public MapCodeGenerator (CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit, CodeDomProvider codeProvider, CodeGenerationOptions options, Hashtable mappings)
		{
//			this.codeCompileUnit = codeCompileUnit;
			this.codeNamespace = codeNamespace;
			this.options = options;
			this.codeProvider = codeProvider;
			this.identifiers = new CodeIdentifiers ((codeProvider.LanguageOptions & LanguageOptions.CaseInsensitive) == 0);
//			this.mappings = mappings;
		}
Example #23
0
 public static ICodeTemplate FindDefaultTemplate(TemplateType templateType, Session session, Type codeTemplateType, CodeDomProvider codeDomProvider){
     const ICodeTemplate template = null;
     var binaryOperator = new BinaryOperator(template.GetPropertyName(x => x.TemplateType),templateType);
     var isDefault = new BinaryOperator(template.GetPropertyName(x => x.IsDefault),true);
     var provider = new BinaryOperator(template.GetPropertyName(x => x.CodeDomProvider),codeDomProvider);
     return session.FindObject(PersistentCriteriaEvaluationBehavior.InTransaction,
                               codeTemplateType, new GroupOperator(binaryOperator, isDefault,provider))
            as ICodeTemplate;
 }
		public void InitBase()
		{
			provider = new CSharpCodeProvider ();
			generator = provider.CreateGenerator ();
			options = new CodeGeneratorOptions ();
			writer = new StringWriter ();

			writer.NewLine = "\n";
		}
Example #25
0
 public RuntimeCompiler()
 {
     compiler = CodeDomProvider.CreateProvider("CSharp");
     parameters = new CompilerParameters();
     AddRunningAssemblies();
     parameters.GenerateInMemory = true;
     parameters.GenerateExecutable = false;
     parameters.OutputAssembly = "RuntimeCompiler";
 }
    public override void Search (CodeDomProvider provider, String output) {
        int index;

        // find the snippet
        String str = "This is a CODE SNIPPET #*$*@";
        index = output.IndexOf (str);
        if (index >= 0 &&
                String.Compare (str, 0, output, index, str.Length, false, CultureInfo.InvariantCulture) == 0)
            VerifyScenario ("FindSnippet");
    }
    public override CompilerParameters GetCompilerParameters (CodeDomProvider provider) {
        CompilerParameters parms = base.GetCompilerParameters (provider);

        // some languages don't compile correctly if no executable is
        // generated and an entry point is defined
        if (Supports (provider, GeneratorSupport.EntryPointMethod)) {
            parms.GenerateExecutable = true;
        }
        return parms;
    }
 public Wsdl()
 {
     proxyCode = "<NOT YET>";
     proxyNamespace = "";
     paths = new StringCollection();
     codeProvider = null;
     wsdls = new StringCollection();
     xsds = new StringCollection();
     cancelled = false;
 }
        /// <summary>
        /// Verifies that <paramref name="source"/> compiles using the provided compiler.
        /// </summary>
        /// <param name="compiler">Compiler instance</param>
        /// <param name="references">Referenced assemblies</param>
        /// <param name="source">Source code to compile</param>
        public static CompilerResults Compiles(CodeDomProvider provider, StringCollection references, string source)
        {
            Assert.IsNotNull(provider);
            Assert.IsNotNull(references);
            Assert.IsNotNull(source);
            CompilerParameters ps = new CompilerParameters();
            foreach (string ra in references)
                ps.ReferencedAssemblies.Add(ra);

            return Compiles(provider, ps, source);
        }
Example #30
0
		// TODO: parse both and try to find the basetype of the partial codebehind
		//
		public CodeProvider (string fileName, string codeBehindFileName)
		{
			if (codeBehindFileName == null)
				throw new ArgumentNullException ("codeBehindFileName");
			if (fileName == null)
				throw new ArgumentNullException ("fileName");

			_codeBehindFileName = codeBehindFileName;
			_fileName = fileName;
			_provider = GetCodeProvider (fileName);
		}
        bool ProcessMarkupItem(ITaskItem markupItem, CodeDomProvider codeDomProvider)
        {
            string markupItemFileName = markupItem.ItemSpec;

            XamlBuildTaskServices.PopulateModifiers(codeDomProvider);

            XamlNodeList xamlNodes = ReadXamlNodes(markupItemFileName);

            if (xamlNodes == null)
            {
                return(false);
            }

            ClassData classData = ReadClassData(xamlNodes, markupItemFileName);

            string outputFileName = GetFileName(markupItemFileName);
            string codeFileName   = Path.ChangeExtension(outputFileName, GetGeneratedSourceExtension(codeDomProvider));
            string markupFileName = Path.ChangeExtension(outputFileName, GeneratedSourceExtension + XamlBuildTaskServices.XamlExtension);

            classData.EmbeddedResourceFileName = Path.GetFileName(markupFileName);
            classData.HelperClassFullName      = this.HelperClassFullName;

            // Check if code file with partial class exists
            classData.SourceFileExists = UserProvidedFileExists(markupItemFileName, codeDomProvider);

            // Store the full type name as metadata on the markup item
            string rootNamespacePrefix = null;
            string namespacePrefix     = null;
            string typeFullName        = null;

            if (this.Language.Equals("VB") && !String.IsNullOrWhiteSpace(classData.RootNamespace))
            {
                rootNamespacePrefix = classData.RootNamespace + ".";
            }

            if (!String.IsNullOrWhiteSpace(classData.Namespace))
            {
                namespacePrefix = classData.Namespace + ".";
            }

            if (rootNamespacePrefix != null)
            {
                if (namespacePrefix != null)
                {
                    typeFullName = rootNamespacePrefix + namespacePrefix + classData.Name;
                }
                else
                {
                    typeFullName = rootNamespacePrefix + classData.Name;
                }
            }
            else
            {
                if (namespacePrefix != null)
                {
                    typeFullName = namespacePrefix + classData.Name;
                }
                else
                {
                    typeFullName = classData.Name;
                }
            }

            markupItem.SetMetadata("typeName", typeFullName);

            // Execute extensions here to give them a chance to mutate the ClassData before we generate code.
            if (this.SupportExtensions)
            {
                if (!ExecuteExtensions(classData, markupItem))
                {
                    return(false);
                }
            }

            // Generate code file
            CodeCompileUnit codeUnit = new ClassGenerator(this.BuildLogger, codeDomProvider, this.Language).Generate(classData);

            WriteCode(codeDomProvider, codeUnit, codeFileName);
            this.GeneratedCodeFiles.Add(codeFileName);

            // Generate resource file
            if (!string.IsNullOrEmpty(this.AssemblyName))
            {
                // Generate xaml "implementation" file
                XmlWriterSettings xmlSettings = new XmlWriterSettings {
                    Indent = true, IndentChars = "  ", CloseOutput = true
                };
                using (XmlWriter xmlWriter = XmlWriter.Create(File.Open(markupFileName, FileMode.Create), xmlSettings))
                {
                    XamlXmlWriterSettings xamlSettings = new XamlXmlWriterSettings()
                    {
                        CloseOutput = true
                    };

                    // Process EmbeddedResourceXaml to remove xml:space="preserve"
                    // due to a



                    RemoveXamlSpaceAttribute(classData);

                    using (XamlReader reader = classData.EmbeddedResourceXaml.GetReader())
                    {
                        using (XamlXmlWriter xamlWriter = new XamlXmlWriter(xmlWriter, reader.SchemaContext, xamlSettings))
                        {
                            XamlServices.Transform(reader, xamlWriter);
                        }
                    }
                }
                this.GeneratedResources.Add(markupFileName);
            }

            if (classData.RequiresCompilationPass2)
            {
                this.RequiresCompilationPass2 = true;
            }
            else
            {
                if (!this.SupportExtensions)
                {
                    if (!ValidateXaml(xamlNodes, markupItemFileName))
                    {
                        this.RequiresCompilationPass2 = true;
                    }
                }
                else
                {
                    // skip validation if we are doing in-proc compile
                    // OR if we have pass 2 extensions hooked up
                    // as we anyway need to run pass 2 in that case
                    if (!this.IsInProcessXamlMarkupCompile && !this.MarkupCompilePass2ExtensionsPresent)
                    {
                        if (!ValidateXaml(xamlNodes, markupItemFileName))
                        {
                            this.RequiresCompilationPass2 = true;
                        }
                    }
                }
            }
            return(true);
        }
        bool UserProvidedFileExists(string markupItemPath, CodeDomProvider codeDomProvider)
        {
            string desiredSourceFilePath = Path.ChangeExtension(markupItemPath, "xaml." + codeDomProvider.FileExtension);

            return(SourceFilePaths.Contains(desiredSourceFilePath));
        }
Example #33
0
        private static String ConstructGeneratorCode(TemplateItem ti, Boolean lineNumbers, String namespaceName, CodeDomProvider provider)
        {
            // 准备类名和命名空间
            var codeNamespace = new CodeNamespace(namespaceName);

            // 加入引用的命名空间
            foreach (var str in ti.Imports)
            {
                if (!String.IsNullOrEmpty(str))
                {
                    codeNamespace.Imports.Add(new CodeNamespaceImport(str));
                }
            }
            var typeDec = new CodeTypeDeclaration(ti.ClassName);

            typeDec.IsClass = true;
            codeNamespace.Types.Add(typeDec);

            // 基类
            if (!String.IsNullOrEmpty(ti.BaseClassName))
            {
                typeDec.BaseTypes.Add(new CodeTypeReference(ti.BaseClassName));
            }
            else if (!String.IsNullOrEmpty(BaseClassName))
            {
                typeDec.BaseTypes.Add(new CodeTypeReference(BaseClassName));
            }
            else
            {
                typeDec.BaseTypes.Add(new CodeTypeReference(typeof(TemplateBase)));
            }

            if (!String.IsNullOrEmpty(ti.Name))
            {
                typeDec.LinePragma = new CodeLinePragma(ti.Name, 1);
            }

            // Render方法
            CreateRenderMethod(ti.Blocks, lineNumbers, typeDec);

            // 代码生成选项
            var options = new CodeGeneratorOptions();

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

            // 其它类成员代码块
            var firstMemberFound = false;

            foreach (var block in ti.Blocks)
            {
                firstMemberFound = GenerateMemberForBlock(block, typeDec, lineNumbers, provider, options, firstMemberFound);
            }

            // 模版变量
            if (ti.Vars != null && ti.Vars.Count > 0)
            {
                // 构建静态构造函数,初始化静态属性Vars
                CreateCctorMethod(typeDec, ti.Vars);

                //public Int32 VarName
                //{
                //    get { return (Int32)GetData("VarName"); }
                //    set { Data["VarName"] = value; }
                //}
                foreach (var v in ti.Vars)
                {
                    //var vtype = TypeX.Create(v.Value);
                    var codeName = v.Value.GetName(true);

                    var sb = new StringBuilder();
                    sb.AppendLine();
                    sb.AppendFormat("public {0} {1}", codeName, v.Key);
                    sb.AppendLine("{");
                    sb.AppendFormat("    get {{ return GetData<{0}>(\"{1}\"); }}", codeName, v.Key);
                    sb.AppendLine();
                    sb.AppendFormat("    set {{ Data[\"{0}\"] = value; }}", v.Key);
                    sb.AppendLine();
                    sb.AppendLine("}");

                    typeDec.Members.Add(new CodeSnippetTypeMember(sb.ToString()));
                }
            }

            // 输出
            using (var writer = new StringWriter())
            {
                provider.GenerateCodeFromNamespace(codeNamespace, new IndentedTextWriter(writer), options);
                return(writer.ToString());
            }
        }
Example #34
0
        private static void GenerateEnumNamesCode(EnumNameTypeAsset enumNameTypeAsset, string targetFolder)
        {
            var targetUnit      = new CodeCompileUnit();
            var targetNamespace = new CodeNamespace(enumNameTypeAsset.namespaceName);

            // targetNamespace.Imports.Add(new CodeNamespaceImport("System"));

            var targetClass = new CodeTypeDeclaration(enumNameTypeAsset.className)
            {
                TypeAttributes = TypeAttributes.Public
            };

            for (var i = 0; i < enumNameTypeAsset.types.Count; i++)
            {
                var type = enumNameTypeAsset.types[i];

                var intValue = new CodeMemberField
                {
                    Attributes     = MemberAttributes.Public | MemberAttributes.Static,
                    Name           = type.name,
                    Type           = new CodeTypeReference(typeof(int)),
                    InitExpression = new CodeSnippetExpression($"1 << {i}")
                };

                targetClass.Members.Add(intValue);
            }

            for (var i = 0; i < enumNameTypeAsset.groupTypes.Count; i++)
            {
                var groupType = enumNameTypeAsset.groupTypes[i];
                var value     = enumNameTypeAsset.MaskToString(groupType.value);

                // var groupTypes = enumNameTypeAsset.GetMaskTypes(groupType.value);
                // var strings = groupTypes.Select(t => t.name).ToArray();
                // var value = string.Join(" | ", strings);

                var intValue = new CodeMemberField
                {
                    Attributes     = MemberAttributes.Public | MemberAttributes.Static,
                    Name           = groupType.name,
                    Type           = new CodeTypeReference(typeof(int)),
                    InitExpression = new CodeSnippetExpression(value)
                };

                targetClass.Members.Add(intValue);
            }

            targetClass.Members.Add(new CodeMemberMethod()
            {
                Name       = "MatchAny",
                Attributes = MemberAttributes.Public | MemberAttributes.Static,
                Parameters =
                {
                    new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "a"),
                    new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "b")
                },
                ReturnType = new CodeTypeReference(typeof(bool)),
                Statements =
                {
                    new CodeSnippetExpression("return (a & b) != 0")
                }
            });

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

            var provider = CodeDomProvider.CreateProvider("CSharp");
            var options  = new CodeGeneratorOptions
            {
                BlankLinesBetweenMembers = true,
                BracingStyle             = "C",
            };

            var generatedClassFile = $"{enumNameTypeAsset.className}.cs";

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

            using (var sourceWriter = new StreamWriter(Path.Combine(targetFolder, generatedClassFile)))
            {
                provider.GenerateCodeFromCompileUnit(targetUnit, sourceWriter, options);
            }

            AssetDatabase.Refresh();
        }
Example #35
0
        /* goodB2G1() - use badsource and goodsink by changing second PRIVATE_CONST_TRUE to PRIVATE_CONST_FALSE */
        private void GoodB2G1()
        {
            string data;

            if (PRIVATE_CONST_TRUE)
            {
                data = ""; /* Initialize data */
                {
                    /* read user input from console with ReadLine */
                    try
                    {
                        /* POTENTIAL FLAW: Read data from the console using ReadLine */
                        data = Console.ReadLine();
                    }
                    catch (IOException exceptIO)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
                    }
                }
            }
            else
            {
                /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
                 * but ensure data is inititialized before the Sink to avoid compiler errors */
                data = null;
            }
            if (PRIVATE_CONST_FALSE)
            {
                /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
                IO.WriteLine("Benign, fixed string");
            }
            else
            {
                int?parsedNum = null;
                /* FIX: Validate user input prior to compiling */
                try
                {
                    parsedNum = int.Parse(data);
                }
                catch (FormatException exceptNumberFormat)
                {
                    IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing number.");
                }
                if (parsedNum != null)
                {
                    StringBuilder sourceCode = new StringBuilder("");
                    sourceCode.Append("public class Calculator \n{\n");
                    sourceCode.Append("\tpublic int Sum()\n\t{\n");
                    sourceCode.Append("\t\treturn (10 + " + data.ToString() + ");\n");
                    sourceCode.Append("\t}\n");
                    sourceCode.Append("}\n");
                    CodeDomProvider    provider   = CodeDomProvider.CreateProvider("CSharp");
                    CompilerParameters cp         = new CompilerParameters();
                    CompilerResults    cr         = provider.CompileAssemblyFromSource(cp, sourceCode.ToString());
                    Assembly           a          = cr.CompiledAssembly;
                    object             calculator = a.CreateInstance("Calculator");
                    Type       calculatorType     = calculator.GetType();
                    MethodInfo mi = calculatorType.GetMethod("Sum");
                    int        s  = (int)mi.Invoke(calculator, new object[] {});
                    IO.WriteLine("Result: " + s.ToString());
                }
            }
        }
Example #36
0
        public string test()
        {
            List <Stream>             lsstream      = new List <Stream>();
            List <ServiceDescription> lsdescription = new List <ServiceDescription>();
            Dictionary <string, ServiceDescription> dicdescription = new Dictionary <string, ServiceDescription>();


            XmlDocument doc = new XmlDocument();

            doc.Load("DllConfig.xml");

            string ServerURL = ((XmlElement)doc.SelectSingleNode("AutoCreate").SelectSingleNode("URLAddres")).GetAttribute("URL");



            //CodeNamespace nmspace = new CodeNamespace();

            CodeCompileUnit unit = new CodeCompileUnit();

            //unit.Namespaces.Add(nmspace);

            foreach (XmlNode xn in doc.SelectSingleNode("AutoCreate").SelectSingleNode("FileList").ChildNodes)
            {
                string _temp = ((XmlElement)xn).GetAttribute("Name");
                if (!string.IsNullOrEmpty(_temp))
                {
                    //nmspace.Name = string.Format("WebServices.{0}", _temp.Split('.')[0]);
                    //unit.Namespaces.Add(nmspace);

                    dicdescription.Add(string.Format("WebServices.{0}", _temp.Split('.')[0]), ServiceDescription.Read(web.OpenRead(string.Format("{0}{1}?WSDL", ServerURL, _temp))));
                    //lsdescription.Add(ServiceDescription.Read(web.OpenRead(string.Format("{0}{1}?WSDL", ServerURL, _temp))));
                }
            }


            //int x = 0;
            //foreach (ServiceDescription description in lsdescription)
            //{
            //    ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
            //    importer.ProtocolName = "Soap";
            //    importer.Style = ServiceDescriptionImportStyle.Client;
            //    importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;

            //    importer.AddServiceDescription(description, null, null);

            //    //ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);
            //    ServiceDescriptionImportWarnings warning = importer.Import(unit.Namespaces[x], unit);
            //    x++;
            //}

            foreach (string str in dicdescription.Keys)
            {
                CodeNamespace nmspace = new CodeNamespace();
                ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
                importer.ProtocolName          = "Soap";
                importer.Style                 = ServiceDescriptionImportStyle.Client;
                importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;
                nmspace.Name = str;
                unit.Namespaces.Add(nmspace);
                importer.AddServiceDescription(dicdescription[str], null, null);
                ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);
            }



            CodeDomProvider    provider  = CodeDomProvider.CreateProvider("CSharp");
            CompilerParameters parameter = new CompilerParameters();

            parameter.GenerateExecutable = false;
            parameter.OutputAssembly     = "getWebServices.dll";
            parameter.ReferencedAssemblies.Add("System.dll");
            parameter.ReferencedAssemblies.Add("System.XML.dll");
            parameter.ReferencedAssemblies.Add("System.Web.Services.dll");
            parameter.ReferencedAssemblies.Add("System.Data.dll");

            CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit);
            StringBuilder   err    = new StringBuilder(50000);

            if (result.Errors.HasErrors)
            {
                for (int i = 0; i < result.Errors.Count; i++)
                {
                    err.AppendLine(result.Errors[i].ErrorText);
                }
            }

            return(err.ToString());
        }
Example #37
0
 public DOLScriptCompiler()
 {
     compiler = new CSharpCodeProvider(new Dictionary <string, string> {
         { "CompilerVersion", "v4.0" }
     });
 }
Example #38
0
        public void CreateAllPointEstimateEvalObjects(Dictionary <string, string> dicFunction, Dictionary <string, string> dicSetupVariables)
        {
            try
            {
                if (dicPointEstimateMethodInfo != null)
                {
                    dicPointEstimateMethodInfo.Clear();
                }
                else
                {
                    dicPointEstimateMethodInfo = new Dictionary <string, object>();
                }

                foreach (KeyValuePair <string, string> k in dicFunction)
                {
                    try
                    {
                        string strVariables = "";
                        int    i            = 0;
                        if (dicSetupVariables != null && dicSetupVariables.Count > 0 && dicSetupVariables.ContainsKey(k.Key))
                        {
                            while (i < dicSetupVariables.Count)
                            {
                                strVariables = dicSetupVariables.ToList()[i].Value; i++;
                            }
                        }

                        int icount = dicPointEstimateMethodInfo.Count;


                        CSharpCodeProvider csharpCodeProvider = new CSharpCodeProvider();
                        CodeDomProvider    provider           = CodeDomProvider.CreateProvider("CSharp");

                        CompilerParameters cp = new CompilerParameters();
                        cp.ReferencedAssemblies.Add("System.dll");
                        cp.CompilerOptions  = "/t:library";
                        cp.GenerateInMemory = true;
                        Random rm = new Random();
                        cp.OutputAssembly = CommonClass.DataFilePath + "\\Tmp\\" + System.DateTime.Now.Year + System.DateTime.Now.Month + System.DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute +
                                            DateTime.Now.Second + DateTime.Now.Millisecond + rm.Next(2000) + ".dll";
                        StringBuilder myCode = new StringBuilder();
                        myCode.Append("using System;");
                        myCode.Append("namespace CoustomEval{");
                        myCode.Append("class myLibPointEstimate" + k.Key + " { public double myPow(double a) { return Math.Pow(a,2);}  public double myMethod(double a, double b, double c, double beta, double deltaq, double q0, double q1, double incidence, double pop, double prevalence" + strVariables +
                                      "){ try{" + k.Value + "} catch (Exception ex) { return -999999999; }}}");
                        myCode.Append("}");
                        CompilerResults cr = csharpCodeProvider.CompileAssemblyFromSource(cp, myCode.ToString());

                        Assembly assembly = cr.CompiledAssembly;
                        Type[]   types    = new Type[] { typeof(double), typeof(double), typeof(double), typeof(double), typeof(double), typeof(double), typeof(double), typeof(double), typeof(double), typeof(double) };

                        object tmp = assembly.CreateInstance("CoustomEval.myLibPointEstimate" + k.Key);
                        dicPointEstimateMethodInfo.Add(k.Key, tmp);
                    }
                    catch
                    {
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
        public override bool RunTask()
        {
            // In Xamarin Studio, if the project name isn't a valid C# identifier
            // then $(RootNamespace) is not set, and the generated Activity is
            // placed into the "Application" namespace. VS just munges the project
            // name to be a valid C# identifier.
            // Use "Application" as the default namespace name to work with XS.
            Namespace = Namespace ?? "Application";

            if (!File.Exists(JavaResgenInputFile) && !UseManagedResourceGenerator)
            {
                return(true);
            }

            // ResourceDirectory may be a relative path, and
            // we need to compare it to absolute paths
            ResourceDirectory = Path.GetFullPath(ResourceDirectory);

            var javaPlatformDirectory = Path.GetDirectoryName(JavaPlatformJarPath);

            // Create our capitalization maps so we can support mixed case resources
            foreach (var item in Resources)
            {
                if (!item.ItemSpec.StartsWith(ResourceDirectory))
                {
                    continue;
                }

                var name         = item.ItemSpec.Substring(ResourceDirectory.Length);
                var logical_name = item.GetMetadata("LogicalName").Replace('\\', '/');

                AddRename(name.Replace('/', Path.DirectorySeparatorChar), logical_name.Replace('/', Path.DirectorySeparatorChar));
            }
            if (AdditionalResourceDirectories != null)
            {
                foreach (var additionalDir in AdditionalResourceDirectories)
                {
                    var file = Path.Combine(ProjectDir, Path.GetDirectoryName(additionalDir.ItemSpec), "__res_name_case_map.txt");
                    if (File.Exists(file))
                    {
                        foreach (var line in File.ReadAllLines(file).Where(l => !string.IsNullOrEmpty(l)))
                        {
                            string [] tok = line.Split(';');
                            AddRename(tok [1].Replace('/', Path.DirectorySeparatorChar), tok [0].Replace('/', Path.DirectorySeparatorChar));
                        }
                    }
                }
            }

            // Parse out the resources from the R.java file
            CodeTypeDeclaration resources;

            if (UseManagedResourceGenerator)
            {
                var parser = new ManagedResourceParser()
                {
                    Log = Log, JavaPlatformDirectory = javaPlatformDirectory, ResourceFlagFile = ResourceFlagFile
                };
                resources = parser.Parse(ResourceDirectory, AdditionalResourceDirectories?.Select(x => x.ItemSpec), IsApplication, resource_fixup);
            }
            else
            {
                var parser = new JavaResourceParser()
                {
                    Log = Log
                };
                resources = parser.Parse(JavaResgenInputFile, IsApplication, resource_fixup);
            }

            var  extension = Path.GetExtension(NetResgenOutputFile);
            var  language  = string.Compare(extension, ".fs", StringComparison.OrdinalIgnoreCase) == 0 ? "F#" : CodeDomProvider.GetLanguageFromExtension(extension);
            bool isVB      = string.Equals(extension, ".vb", StringComparison.OrdinalIgnoreCase);
            bool isFSharp  = string.Equals(language, "F#", StringComparison.OrdinalIgnoreCase);
            bool isCSharp  = string.Equals(language, "C#", StringComparison.OrdinalIgnoreCase);

            // Let VB put this in the default namespace
            if (isVB)
            {
                Namespace = string.Empty;
            }

            List <string> aliases = new List <string> ();

            // Create static resource overwrite methods for each Resource class in libraries.
            if (IsApplication && References != null && References.Length > 0)
            {
                var assemblies = new List <ITaskItem> (References.Length);
                foreach (var assembly in References)
                {
                    var assemblyPath = assembly.ItemSpec;
                    var fileName     = Path.GetFileName(assemblyPath);
                    if (MonoAndroidHelper.IsFrameworkAssembly(fileName) &&
                        !MonoAndroidHelper.FrameworkEmbeddedJarLookupTargets.Contains(fileName))
                    {
                        Log.LogDebugMessage($"Skipping framework assembly '{fileName}'.");
                        continue;
                    }
                    if (!File.Exists(assemblyPath))
                    {
                        Log.LogDebugMessage($"Skipping non-existent dependency '{assemblyPath}'.");
                        continue;
                    }
                    ITaskItem item = new TaskItem(assemblyPath);
                    assembly.CopyMetadataTo(item);
                    assemblies.Add(item);
                    string alias = assembly.GetMetadata("Aliases");
                    if (!string.IsNullOrEmpty(alias))
                    {
                        aliases.Add(alias);
                    }
                    Log.LogDebugMessage("Scan assembly {0} for resource generator", fileName);
                }
                new ResourceDesignerImportGenerator(Namespace, resources, Log)
                .CreateImportMethods(assemblies);
            }

            AdjustConstructor(isFSharp, resources);
            foreach (var member in resources.Members)
            {
                if (member is CodeTypeDeclaration)
                {
                    AdjustConstructor(isFSharp, (CodeTypeDeclaration)member);
                }
            }

            // Write out our Resources.Designer.cs file

            WriteFile(NetResgenOutputFile, resources, language, isFSharp, isCSharp, aliases);

            return(!Log.HasLoggedErrors);
        }
Example #40
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LuaFileCodeModel"/> class.
 /// </summary>
 /// <param name="dte">Global DTE instance.</param>
 /// <param name="provider">CodeDomProvider implementation.</param>
 /// <param name="parent">Parent ProjectItem of FileCodeModel.</param>
 /// <param name="filename">Code file name.</param>
 public LuaFileCodeModel(DTE dte, ProjectItem parent, CodeDomProvider provider, string filename)
     : base(dte, filename)
 {
     this.parent   = parent;
     this.provider = provider;
 }
        protected override string CreateProxyFile(DotNetProject dotNetProject, FilePath basePath, string proxyNamespace, string referenceName)
        {
            var ccu = new CodeCompileUnit();
            var 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;

            var generator = new ServiceContractGenerator(ccu);

            generator.Options = ServiceContractGenerationOptions.ChannelInterface | ServiceContractGenerationOptions.ClientClass;
            if (refGroup.ClientOptions.GenerateAsynchronousMethods || targetCoreClr)
            {
                generator.Options |= ServiceContractGenerationOptions.AsynchronousMethods;
            }
            if (refGroup.ClientOptions.GenerateEventBasedAsynchronousMethods)
            {
                generator.Options |= ServiceContractGenerationOptions.EventBasedAsynchronousMethods;
            }
#if NET_4_5
            if (refGroup.ClientOptions.GenerateTaskBasedAsynchronousMethod)
            {
                generator.Options |= ServiceContractGenerationOptions.TaskBasedAsynchronousMethod;
            }
#endif
            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;
            mset = protocol != null?ToMetadataSet(protocol) : metadata;

            CodeDomProvider code_provider = GetProvider(dotNetProject);

            var list = new List <IWsdlImportExtension> ();
            list.Add(new TransportBindingElementImporter());
            list.Add(new XmlSerializerMessageContractImporter());

            var 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 #42
0
        private static Assembly Compile(String outputAssembly, IEnumerable <String> references, CodeDomProvider provider, CompilerErrorCollection errors, Template tmp)
        {
            //String key = outputAssembly;
            //if (String.IsNullOrEmpty(key)) key = Hash(String.Join(Environment.NewLine, sources));

            var sb = new StringBuilder();

            foreach (var item in tmp.Templates)
            {
                if (item.Included)
                {
                    continue;
                }

                if (sb.Length > 0)
                {
                    sb.AppendLine();
                }
                sb.Append(item.Source);
            }
            String key = Hash(sb.ToString());

            Assembly assembly = null;

            if (asmCache.TryGetValue(key, out assembly))
            {
                return(assembly);
            }
            lock (asmCache)
            {
                if (asmCache.TryGetValue(key, out assembly))
                {
                    return(assembly);
                }
                foreach (var str in references)
                {
                    try
                    {
                        if (!String.IsNullOrEmpty(str) && File.Exists(str))
                        {
                            Assembly.LoadFrom(str);
                        }
                    }
                    catch { }
                }

                assembly = CompileInternal(outputAssembly, references, provider, errors, tmp);
                if (assembly != null)
                {
                    asmCache.Add(key, assembly);
                }

                return(assembly);
            }
        }
 public CSharpCompiler(CodeDomProvider codeDomProvider, IProviderOptions providerOptions = null)
     : base(codeDomProvider, providerOptions)
 {
 }
Example #44
0
        private static bool CompileAssembly(PlgxPluginInfo plgx,
                                            out CompilerResults cr, string strCompilerVersion)
        {
            cr = null;

            const string StrCoreRef = "System.Core";
            const string StrCoreDll = "System.Core.dll";
            bool         bHasCore = false, bCoreAdded = false;

            foreach (string strAsm in plgx.CompilerParameters.ReferencedAssemblies)
            {
                if (UrlUtil.AssemblyEquals(strAsm, StrCoreRef))
                {
                    bHasCore = true;
                    break;
                }
            }
            if ((strCompilerVersion != null) && strCompilerVersion.StartsWith(
                    "v", StrUtil.CaseIgnoreCmp))
            {
                ulong v = StrUtil.ParseVersion(strCompilerVersion.Substring(1));
                if (!bHasCore && (v >= 0x0003000500000000UL))
                {
                    plgx.CompilerParameters.ReferencedAssemblies.Add(StrCoreDll);
                    bCoreAdded = true;
                }
            }

            bool bResult = false;

            try
            {
                Dictionary <string, string> dictOpt = new Dictionary <string, string>();
                if (!string.IsNullOrEmpty(strCompilerVersion))
                {
                    dictOpt.Add("CompilerVersion", strCompilerVersion);
                }

                // Windows 98 only supports the parameterless constructor;
                // check must be separate from the instantiation method
                if (WinUtil.IsWindows9x)
                {
                    dictOpt.Clear();
                }

                CodeDomProvider cdp = null;
                if (plgx.ProjectType == PlgxProjectType.CSharp)
                {
                    cdp = ((dictOpt.Count == 0) ? new CSharpCodeProvider() :
                           CreateCscProvider(dictOpt));
                }
                // else if(plgx.ProjectType == PlgxProjectType.VisualBasic)
                //	cdp = ((dictOpt.Count == 0) ? new VBCodeProvider() :
                //		new VBCodeProvider(dictOpt));
                else
                {
                    throw new InvalidOperationException();
                }

                cr = cdp.CompileAssemblyFromFile(plgx.CompilerParameters,
                                                 plgx.SourceFiles.ToArray());

                bResult = ((cr.Errors == null) || !cr.Errors.HasErrors);
            }
            catch (Exception) { }

            if (bCoreAdded)
            {
                plgx.CompilerParameters.ReferencedAssemblies.Remove(StrCoreDll);
            }

            return(bResult);
        }
        public bool Execute()
        {
            try
            {
                if (this.ApplicationMarkup == null || this.ApplicationMarkup.Count == 0)
                {
                    return(true);
                }
                if (!CodeDomProvider.IsDefinedLanguage(this.Language))
                {
                    throw FxTrace.Exception.Argument("Language", SR.UnrecognizedLanguage(this.Language));
                }

                if (this.SupportExtensions)
                {
                    this.xamlBuildTypeGenerationExtensions = XamlBuildTaskServices.GetXamlBuildTaskExtensions <IXamlBuildTypeGenerationExtension>(
                        this.XamlBuildTaskTypeGenerationExtensionNames,
                        this.BuildLogger,
                        this.MSBuildProjectDirectory);
                }

                AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(XamlBuildTaskServices.ReflectionOnlyAssemblyResolve);
                bool retVal = true;
                // We load the assemblies for the real builds
                // For intellisense builds, we load them the first time only
                if (!IsInProcessXamlMarkupCompile || this.LoadedAssemblyList == null)
                {
                    if (this.References != null)
                    {
                        try
                        {
                            this.LoadedAssemblyList = XamlBuildTaskServices.Load(this.References, IsInProcessXamlMarkupCompile);
                        }
                        catch (FileNotFoundException e)
                        {
                            XamlBuildTaskServices.LogException(this.BuildLogger, e.Message, e.FileName, 0, 0);
                            retVal = false;
                        }
                    }
                }

                CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider(this.Language);

                ProcessHelperClassGeneration(codeDomProvider);
                foreach (ITaskItem app in ApplicationMarkup)
                {
                    string inputMarkupFile = app.ItemSpec;
                    try
                    {
                        retVal &= ProcessMarkupItem(app, codeDomProvider);
                    }
                    catch (LoggableException e)
                    {
                        if (Fx.IsFatal(e))
                        {
                            throw;
                        }
                        XamlBuildTaskServices.LogException(this.BuildLogger, e.Message, e.Source, e.LineNumber, e.LinePosition);
                        retVal = false;
                    }
                    catch (FileLoadException e)
                    {
                        if (Fx.IsFatal(e))
                        {
                            throw;
                        }

                        XamlBuildTaskServices.LogException(this.BuildLogger, SR.AssemblyCannotBeResolved(XamlBuildTaskServices.FileNotLoaded), inputMarkupFile, 0, 0);
                        retVal = false;
                    }
                    catch (Exception e)
                    {
                        if (Fx.IsFatal(e))
                        {
                            throw;
                        }
                        XamlBuildTaskServices.LogException(this.BuildLogger, e.Message, inputMarkupFile, 0, 0);
                        retVal = false;
                    }
                }

                // Add the files generated from extensions
                if (this.SupportExtensions)
                {
                    if (retVal)
                    {
                        foreach (string fileName in this.BuildContextForExtensions.GeneratedFiles)
                        {
                            this.GeneratedCodeFiles.Add(fileName);
                        }

                        foreach (string fileName in this.BuildContextForExtensions.GeneratedResourceFiles)
                        {
                            this.GeneratedResources.Add(fileName);
                        }
                    }
                }

                return(retVal);
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                // Log unknown errors that do not originate from the task.
                // Assumes that all known errors are logged when the exception is thrown.
                if (!(e is LoggableException))
                {
                    XamlBuildTaskServices.LogException(this.BuildLogger, e.Message);
                }
                return(false);
            }
        }
 public VsCodeDomLoader(DesignerLoader loader, IVsHierarchy hier, int itemid, CodeDomProvider provider, TextBuffer buffer, IDesignerLoaderHost host) : base(loader, provider, buffer, host)
 {
     this.vsHierarchy = hier;
     this.itemid      = itemid;
 }
Example #47
0
        private static Assembly CompileInternal(String outputAssembly, IEnumerable <String> references, CodeDomProvider provider, CompilerErrorCollection Errors, Template tmp)
        {
            var options = new CompilerParameters();

            foreach (var str in references)
            {
                options.ReferencedAssemblies.Add(str);
            }
            options.WarningLevel = 4;

            CompilerResults results = null;

            if (Debug)
            {
                //var sb = new StringBuilder();

                #region 调试状态,把生成的类文件和最终dll输出到XTemp目录下
                var tempPath = XTrace.TempPath;
                //if (!String.IsNullOrEmpty(outputAssembly)) tempPath = Path.Combine(tempPath, Path.GetFileNameWithoutExtension(outputAssembly));
                if (!String.IsNullOrEmpty(outputAssembly) && !outputAssembly.EqualIgnoreCase(".dll"))
                {
                    tempPath = Path.Combine(tempPath, Path.GetFileNameWithoutExtension(outputAssembly));
                }

                //if (!String.IsNullOrEmpty(tempPath) && !Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath);

                //var srcpath = tempPath.CombinePath("src").EnsureDirectory(false);

                var files = new List <String>();
                foreach (var item in tmp.Templates)
                {
                    // 输出模版内容,为了调试使用
                    File.WriteAllText(tempPath.CombinePath(item.Name), item.Content);
                    if (item.Included)
                    {
                        continue;
                    }

                    var name = item.Name.EndsWithIgnoreCase(".cs") ? item.Name : item.ClassName;
                    // 猜测后缀
                    Int32 p = name.LastIndexOf("_");
                    if (p > 0 && name.Length - p <= 5)
                    {
                        name = name.Substring(0, p) + "." + name.Substring(p + 1, name.Length - p - 1);
                    }
                    else if (!name.EndsWithIgnoreCase(".cs"))
                    {
                        name += ".cs";
                    }

                    //name = Path.Combine(tempPath, name);
                    //name = srcpath.CombinePath(name);
                    // 必须放在同一个目录,编译时会搜索源码所在目录
                    name = tempPath.CombinePath(Path.GetFileNameWithoutExtension(name) + "_src" + Path.GetExtension(name));
                    File.WriteAllText(name, item.Source);

                    //sb.AppendLine(item.Source);
                    files.Add(name);
                }
                #endregion

                if (!String.IsNullOrEmpty(outputAssembly) && !outputAssembly.EqualIgnoreCase(".dll"))
                {
                    options.TempFiles      = new TempFileCollection(tempPath, false);
                    options.OutputAssembly = Path.Combine(tempPath, outputAssembly);
                    //options.GenerateInMemory = true;
                    options.IncludeDebugInformation = true;
                }

                results = provider.CompileAssemblyFromFile(options, files.ToArray());
                // 必须从内存字符串编译,否则pdb会定向到最终源代码文件
                //results = provider.CompileAssemblyFromSource(options, new String[] { sb.ToString() });
            }
            else
            {
                options.GenerateInMemory = true;

                results = provider.CompileAssemblyFromSource(options, tmp.Templates.Where(e => !e.Included).Select(e => e.Source).ToArray());
            }

            #region 编译错误处理
            if (results.Errors.Count > 0)
            {
                Errors.AddRange(results.Errors);

                var           sb  = new StringBuilder();
                CompilerError err = null;
                foreach (CompilerError error in results.Errors)
                {
                    error.ErrorText = error.ErrorText;
                    //if (String.IsNullOrEmpty(error.FileName)) error.FileName = inputFile;

                    if (!error.IsWarning)
                    {
                        String msg = error.ToString();
                        if (sb.Length < 1)
                        {
                            String code = null;
                            // 屏蔽因为计算错误行而导致的二次错误
                            try
                            {
                                code = tmp.FindBlockCode(error.FileName, error.Line);
                            }
                            catch { }
                            if (code != null)
                            {
                                msg += Environment.NewLine;
                                msg += code;
                            }
                            err = error;
                        }
                        else
                        {
                            sb.AppendLine();
                        }

                        sb.Append(msg);
                    }
                }
                if (sb.Length > 0)
                {
                    var ex = new TemplateException(sb.ToString());
                    ex.Error = err;
                    throw ex;
                }
            }
            else
            {
                try
                {
                    options.TempFiles.Delete();
                }
                catch { }
            }
            #endregion

            if (!results.Errors.HasErrors)
            {
                try
                {
                    return(results.CompiledAssembly);
                }
                catch { }
            }
            return(null);
        }
Example #48
0
        private static void Json2Class(string fileName, string json, List <object> statements)
        {
            string structName = "";

            structName = Path.GetFileName(fileName).ToLower().Replace(".xlsx", "");

            //首字母大写
            structName = structName.Substring(0, 1).ToUpper() + structName.Substring(1);
            //输出目录控制
            string outputFile = Path.Combine(Application.dataPath, "Code/Game@hotfix/Table");

            if (Directory.Exists(outputFile) == false)
            {
                Directory.CreateDirectory(outputFile);
            }

            //输出目录
            outputFile = Path.Combine(outputFile, Path.GetFileName(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 wrapProxyClass = new CodeTypeDeclaration(structName);

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

            CodeAttributeDeclaration attr = new CodeAttributeDeclaration("Serializable");

            wrapProxyClass.CustomAttributes.Add(attr);
            //
            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)
                {
                    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);


                wrapProxyClass.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 #49
0
 public void SetToVisualBasicNet()
 {
     compiler = new VBCodeProvider();
 }
Example #50
0
        /// <summary>生成成员代码块</summary>
        /// <param name="block"></param>
        /// <param name="generatorType"></param>
        /// <param name="lineNumbers"></param>
        /// <param name="provider"></param>
        /// <param name="options"></param>
        /// <param name="firstMemberFound"></param>
        /// <returns></returns>
        private static Boolean GenerateMemberForBlock(Block block, CodeTypeDeclaration generatorType, Boolean lineNumbers, CodeDomProvider provider, CodeGeneratorOptions options, Boolean firstMemberFound)
        {
            CodeSnippetTypeMember member = null;

            if (!firstMemberFound)
            {
                // 发现第一个<#!后,认为是类成员代码的开始,直到下一个<#!作为结束
                if (block.Type == BlockType.Member)
                {
                    firstMemberFound = true;
                    if (!String.IsNullOrEmpty(block.Text))
                    {
                        member = new CodeSnippetTypeMember(block.Text);
                    }
                }
            }
            else
            {
                // 再次遇到<#!,此时,成员代码准备结束
                if (block.Type == BlockType.Member)
                {
                    firstMemberFound = false;
                    if (!String.IsNullOrEmpty(block.Text))
                    {
                        member = new CodeSnippetTypeMember(block.Text);
                    }
                }
                else if (block.Type == BlockType.Text)
                {
                    var expression = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "Write", new CodeExpression[] { new CodePrimitiveExpression(block.Text) });
                    var statement  = new CodeExpressionStatement(expression);
                    using (var writer = new StringWriter())
                    {
                        provider.GenerateCodeFromStatement(statement, writer, options);
                        member = new CodeSnippetTypeMember(writer.ToString());
                    }
                }
                else if (block.Type == BlockType.Expression)
                {
                    var expression = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "Write", new CodeExpression[] { new CodeArgumentReferenceExpression(block.Text.Trim()) });
                    var statement  = new CodeExpressionStatement(expression);
                    using (var writer = new StringWriter())
                    {
                        provider.GenerateCodeFromStatement(statement, writer, options);
                        member = new CodeSnippetTypeMember(writer.ToString());
                    }
                }
                else if (block.Type == BlockType.Statement)
                {
                    member = new CodeSnippetTypeMember(block.Text);
                }
            }
            if (member != null)
            {
                if (lineNumbers)
                {
                    var flag       = String.IsNullOrEmpty(block.Name);
                    var lineNumber = (block.StartLine > 0) ? block.StartLine : 1;
                    if (flag)
                    {
                        generatorType.Members.Add(new CodeSnippetTypeMember("#line " + lineNumber));
                    }
                    else
                    {
                        member.LinePragma = new CodeLinePragma(block.Name, lineNumber);
                    }
                    generatorType.Members.Add(member);
                    if (flag)
                    {
                        generatorType.Members.Add(new CodeSnippetTypeMember("#line default"));
                    }
                }
                else
                {
                    generatorType.Members.Add(member);
                }
            }
            return(firstMemberFound);
        }
Example #51
0
        public object ValuationEval(string cCharpCode, double a, double b, double c, double d, double allgoodsindex, double medicalcostindex, double wageindex, double lagadjustment, Dictionary <string, double> dicSetupVariables)
        {
            try
            {
                MethodInfo    mi       = null;
                object        tmp      = null;
                List <object> lstParam = new List <object>()
                {
                    a, b, c, d, allgoodsindex, medicalcostindex, wageindex, lagadjustment
                };
                if (dicSetupVariables != null && dicSetupVariables.Count > 0)
                {
                    int j = 0;
                    while (j < dicSetupVariables.Count)
                    {
                        lstParam.Add(dicSetupVariables.ToList()[j].Value);
                        j++;
                    }
                }
                if (!dicValuationMethodInfo.Keys.Contains(cCharpCode))
                {
                    string strVariables = "";
                    int    i            = 0;

                    if (dicSetupVariables != null && dicSetupVariables.Count > 0)
                    {
                        while (i < dicSetupVariables.Count)
                        {
                            strVariables = strVariables + ",double " + dicSetupVariables.ToList()[i].Key.ToLower();
                            i++;
                        }
                    }
                    if (a != 0)
                    {
                    }
                    _CharpCode = cCharpCode;
                    int icount = dicValuationMethodInfo.Count;
                    CSharpCodeProvider csharpCodeProvider = new CSharpCodeProvider();
                    CodeDomProvider    provider           = CodeDomProvider.CreateProvider("CSharp");

                    CompilerParameters cp = new CompilerParameters();
                    cp.ReferencedAssemblies.Add("system.dll");
                    cp.CompilerOptions  = "/t:library";
                    cp.GenerateInMemory = true;
                    Random rm = new Random();
                    cp.OutputAssembly = CommonClass.DataFilePath + "\\Tmp\\" + System.DateTime.Now.Year + System.DateTime.Now.Month + System.DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute +
                                        DateTime.Now.Second + DateTime.Now.Millisecond + rm.Next(2000) + ".dll";
                    StringBuilder myCode = new StringBuilder();
                    myCode.Append("using System;");
                    myCode.Append("namespace CoustomEval{");
                    myCode.Append("class myLibValuation" + icount + " {public double myPow(double a) { return Math.Pow(a,2);}   public double myMethod(double a, double b, double c, double d, double allgoodsindex, double medicalcostindex, double wageindex, double lagadjustment" + strVariables +
                                  "){ try{" + cCharpCode + "} catch (Exception ex) { return -999999999; }}}");
                    myCode.Append("}");
                    CompilerResults cr       = provider.CompileAssemblyFromSource(cp, myCode.ToString());
                    Assembly        assembly = cr.CompiledAssembly;
                    Type[]          types    = new Type[] { typeof(double), typeof(double), typeof(double), typeof(double), typeof(double), typeof(double), typeof(double), typeof(double), typeof(double), typeof(double) };

                    tmp = assembly.CreateInstance("CoustomEval.myLibValuation" + icount);
                    dicValuationMethodInfo.Add(cCharpCode, tmp);
                }
                else
                {
                    tmp = dicValuationMethodInfo[cCharpCode];
                }
                Type type = tmp.GetType();
                mi = type.GetMethod("myMethod");
                object result = mi.Invoke(tmp, lstParam.ToArray());
                return(result);
            }
            catch (Exception ex)
            {
                return(-999999999);
            }
        }
        public void GenerateCode()
        {
            // open the file for writing
            string       fileName = "FavSettings";
            Stream       s        = File.Open(fileName + ".cs", FileMode.Create);
            StreamWriter wrtr     = new StreamWriter(s);

            wrtr.WriteLine("// Dynamically created FavSettings class");
            wrtr.WriteLine("using System.ComponentModel;");
            wrtr.WriteLine("using NetCams;");

            // create the class
            string className = mSequenceNamed_sanitized + "_FavoriteSettings";

            wrtr.WriteLine("class {0} : NetCams.FavoriteSettings", className);
            wrtr.WriteLine("{");

            // create the method
            wrtr.WriteLine("\tpublic {0}(TestSequence seq)", className);
            wrtr.WriteLine("\t\t: base(seq)");
            wrtr.WriteLine("\t{");
            wrtr.Write(ctorBody);
            wrtr.WriteLine("\t}");
            wrtr.WriteLine("\t");
            //wrtr.WriteLine("\tpublic TestSequence mTestSequence;");
            //wrtr.WriteLine("\t");

            wrtr.Write(classBody);

            wrtr.WriteLine("}");    // end class

            // close the writer and the stream
            wrtr.Close();
            s.Close();

            /*
             * // Build the file
             * ProcessStartInfo psi = new ProcessStartInfo();
             *
             * psi.FileName = "cmd.exe";
             *
             * string compileString = "/c C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\csc /optimize+ ";
             * compileString += "/r:\"UVision.exe\" ";
             * compileString += "/target:library ";
             * compileString += "{0}.cs > compile.out";
             *
             * psi.Arguments = String.Format(compileString, fileName);
             *
             * psi.WindowStyle = ProcessWindowStyle.Minimized;
             *
             * Process proc = Process.Start(psi);
             *
             * proc.WaitForExit();   // wait at most 2 seconds
             *
             * // Open the file, and get a pointer to the method info
             * Assembly a = Assembly.LoadFrom(fileName + ".dll");
             * mTestSequence.mFavoriteSettings = (FavoriteSettings)a.CreateInstance(className);
             */

            CompilerParameters cp = new CompilerParameters();

            // Generate an executable instead of a class library.
            cp.GenerateExecutable = false;

            // Specify the assembly file name to generate.
            //cp.OutputAssembly = exeName;

            // Save the assembly as a physical file.
            cp.GenerateInMemory = true;

            // Set whether to treat all warnings as errors.
            cp.TreatWarningsAsErrors = false;

            // Add an assembly reference.
            cp.ReferencedAssemblies.Add("UVision.exe");
            cp.ReferencedAssemblies.Add("System.dll");
//            cp.ReferencedAssemblies.Add("System.ComponentModel.dll");// Copyright (c) 2004-2008 Userwise Solutions LLC.  All rights reserved.



            // Invoke compilation of the source file.
            string          sourceName = fileName + ".cs";
            CodeDomProvider provider   = CodeDomProvider.CreateProvider("CSharp");
            CompilerResults cr         = provider.CompileAssemblyFromFile(cp, sourceName);

            if (cr.Errors.Count > 0)
            {
                // Display compilation errors.
                Console.WriteLine("Errors building {0} into {1}", sourceName, cr.PathToAssembly);
                foreach (CompilerError ce in cr.Errors)
                {
                    Console.WriteLine("  {0}", ce.ToString());
                    Console.WriteLine();
                }
            }
            else
            {
                // Display a successful compilation message.
                Console.WriteLine("Source {0} built into {1} successfully.", sourceName, cr.PathToAssembly);

                Assembly a    = cr.CompiledAssembly;
                object[] args = { mTestSequence };
                mTestSequence.mFavoriteSettings = (FavoriteSettings)a.CreateInstance(className, false, BindingFlags.Default | BindingFlags.CreateInstance, null, args, null, null);
            }

            //File.Delete(fileName + ".cs"); // clean up
        }
Example #53
0
        public static ICodeTemplate CreateDefaultTemplate(TemplateType templateType, Session session, Type codeTemplateType, CodeDomProvider codeDomProvider)
        {
            var defaultTemplate = CodeTemplateQuery.FindDefaultTemplate(templateType, session, codeTemplateType, codeDomProvider);

            if (defaultTemplate == null)
            {
                defaultTemplate                 = (ICodeTemplate)ReflectionHelper.CreateObject(codeTemplateType, session);
                defaultTemplate.IsDefault       = true;
                defaultTemplate.TemplateType    = templateType;
                defaultTemplate.CodeDomProvider = codeDomProvider;
                defaultTemplate.SetDefaults();
            }
            return(defaultTemplate);
        }
        private void WriteFile(string file, CodeTypeDeclaration resources, string language, bool isFSharp, bool isCSharp, IEnumerable <string> aliases)
        {
            CodeDomProvider provider =
                isFSharp ? new FSharp.Compiler.CodeDom.FSharpCodeProvider() :
                CodeDomProvider.CreateProvider(language);

            string code = null;

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

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

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

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

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

                // Add Pragma to disable warnings about no Xml documentation
                if (isCSharp)
                {
                    foreach (var alias in aliases)
                    {
                        provider.GenerateCodeFromStatement(new CodeSnippetStatement($"extern alias {alias};"), o, options);
                    }
                    provider.GenerateCodeFromCompileUnit(new CodeSnippetCompileUnit("#pragma warning disable 1591"), o, options);
                }

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

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

                code = o.ToString();

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

            if (MonoAndroidHelper.CopyIfStringChanged(code, file))
            {
                Log.LogDebugMessage($"Writing to: {file}");
            }
        }
Example #55
0
        // Get a code generator for the specified language. language can either be a known abbreviation
        // for C#, VB or JScript. Or it can be a fully-qualified (with assembly) name for an ICodeGenerator
        // or a CodeDomProvider.
        void CreateCodeGenerator(string language, ref ICodeGenerator codeGen, ref string fileExtension)
        {
            CodeDomProvider codeProvider = null;

            if ((string.Compare(language, "CSharp", true) == 0) ||
                (string.Compare(language, "C#", true) == 0) ||
                (string.Compare(language, "CS", true) == 0))
            {
                codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
            }
            else if (string.Compare(language, "VB", true) == 0)
            {
                throw new Exception("VisualBasic not supported in the SSCLI");
            }
            else if ((string.Compare(language, "js", true) == 0) ||
                     (string.Compare(language, "jscript", true) == 0))
            {
                Type t = Type.GetType("Microsoft.JScript.JScriptCodeProvider, " + AssemblyRef.MicrosoftJScript);
                codeProvider = (CodeDomProvider)Activator.CreateInstance(t);
            }
            else
            {
                //try to reflect a custom code generator
                //ignore case when reflecting; language argument must specify the namespace
                Type t = Type.GetType(language, false, true);
                if (t == null)
                {
                    throw new InvalidOperationException(Res.GetString(Res.ErrLanguage, language));
                }
                object o = Activator.CreateInstance(t);
                if (o is CodeDomProvider)
                {
                    codeProvider = (CodeDomProvider)o;
                }
                else if (o is ICodeGenerator)
                {
                    codeGen = (ICodeGenerator)o;
                }
                else
                {
                    throw new InvalidOperationException(Res.GetString(Res.ErrLanguage, language));
                }
            }

            if (codeProvider != null)
            {
                codeGen       = codeProvider.CreateGenerator();
                fileExtension = codeProvider.FileExtension;
                if (fileExtension == null)
                {
                    fileExtension = string.Empty;
                }
                else if (fileExtension.Length > 0 && fileExtension[0] != '.')
                {
                    fileExtension = "." + fileExtension;
                }
            }
            else
            {
                fileExtension = ".src";
            }
        }
Example #56
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LuaFileCodeModel"/> class.
 /// </summary>
 /// <param name="dte">Global DTE instance.</param>
 /// <param name="buffer">IVsTextLines instance.</param>
 /// <param name="provider">CodeDomProvider implementation.</param>
 /// <param name="moniker">File moniker.</param>
 public LuaFileCodeModel(DTE dte, IVsTextLines buffer, CodeDomProvider provider, string moniker)
     : base(dte, moniker)
 {
     TextBuffer    = buffer;
     this.provider = provider;
 }
Example #57
0
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (CodeDomProvider.Expression != null)
            {
                targetCommand.AddParameter("CodeDomProvider", CodeDomProvider.Get(context));
            }

            if (CompilerParameters.Expression != null)
            {
                targetCommand.AddParameter("CompilerParameters", CompilerParameters.Get(context));
            }

            if (TypeDefinition.Expression != null)
            {
                targetCommand.AddParameter("TypeDefinition", TypeDefinition.Get(context));
            }

            if (Name.Expression != null)
            {
                targetCommand.AddParameter("Name", Name.Get(context));
            }

            if (MemberDefinition.Expression != null)
            {
                targetCommand.AddParameter("MemberDefinition", MemberDefinition.Get(context));
            }

            if (Namespace.Expression != null)
            {
                targetCommand.AddParameter("Namespace", Namespace.Get(context));
            }

            if (UsingNamespace.Expression != null)
            {
                targetCommand.AddParameter("UsingNamespace", UsingNamespace.Get(context));
            }

            if (Path.Expression != null)
            {
                targetCommand.AddParameter("Path", Path.Get(context));
            }

            if (LiteralPath.Expression != null)
            {
                targetCommand.AddParameter("LiteralPath", LiteralPath.Get(context));
            }

            if (AssemblyName.Expression != null)
            {
                targetCommand.AddParameter("AssemblyName", AssemblyName.Get(context));
            }

            if (Language.Expression != null)
            {
                targetCommand.AddParameter("Language", Language.Get(context));
            }

            if (ReferencedAssemblies.Expression != null)
            {
                targetCommand.AddParameter("ReferencedAssemblies", ReferencedAssemblies.Get(context));
            }

            if (OutputAssembly.Expression != null)
            {
                targetCommand.AddParameter("OutputAssembly", OutputAssembly.Get(context));
            }

            if (OutputType.Expression != null)
            {
                targetCommand.AddParameter("OutputType", OutputType.Get(context));
            }

            if (PassThru.Expression != null)
            {
                targetCommand.AddParameter("PassThru", PassThru.Get(context));
            }

            if (IgnoreWarnings.Expression != null)
            {
                targetCommand.AddParameter("IgnoreWarnings", IgnoreWarnings.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
Example #58
0
        private string GenerateCode(out string extension)
        {
            extension = null;
            bool haveGeneratedContent = false;

            CodeDomProvider provider;

            try
            {
                provider = CodeDomProvider.CreateProvider(Language);
            }
            catch (System.Configuration.ConfigurationException ex)
            {
                Log.LogErrorWithCodeFromResources("WriteCodeFragment.CouldNotCreateProvider", Language, ex.Message);
                return(null);
            }
            catch (SecurityException ex)
            {
                Log.LogErrorWithCodeFromResources("WriteCodeFragment.CouldNotCreateProvider", Language, ex.Message);
                return(null);
            }

            extension = provider.FileExtension;

            var unit = new CodeCompileUnit();

            var globalNamespace = new CodeNamespace();

            unit.Namespaces.Add(globalNamespace);

            // Declare authorship. Unfortunately CodeDOM puts this comment after the attributes.
            string comment = ResourceUtilities.GetResourceString("WriteCodeFragment.Comment");

            globalNamespace.Comments.Add(new CodeCommentStatement(comment));

            if (AssemblyAttributes == null)
            {
                return(String.Empty);
            }

            // For convenience, bring in the namespaces, where many assembly attributes lie
            globalNamespace.Imports.Add(new CodeNamespaceImport("System"));
            globalNamespace.Imports.Add(new CodeNamespaceImport("System.Reflection"));

            foreach (ITaskItem attributeItem in AssemblyAttributes)
            {
                var attribute = new CodeAttributeDeclaration(new CodeTypeReference(attributeItem.ItemSpec));

                // Some attributes only allow positional constructor arguments, or the user may just prefer them.
                // To set those, use metadata names like "_Parameter1", "_Parameter2" etc.
                // If a parameter index is skipped, it's an error.
                IDictionary customMetadata = attributeItem.CloneCustomMetadata();

                var orderedParameters = new List <CodeAttributeArgument>(new CodeAttributeArgument[customMetadata.Count + 1] /* max possible slots needed */);
                var namedParameters   = new List <CodeAttributeArgument>();

                foreach (DictionaryEntry entry in customMetadata)
                {
                    string name  = (string)entry.Key;
                    string value = (string)entry.Value;

                    if (name.StartsWith("_Parameter", StringComparison.OrdinalIgnoreCase))
                    {
                        if (!Int32.TryParse(name.Substring("_Parameter".Length), out int index))
                        {
                            Log.LogErrorWithCodeFromResources("General.InvalidValue", name, "WriteCodeFragment");
                            return(null);
                        }

                        if (index > orderedParameters.Count || index < 1)
                        {
                            Log.LogErrorWithCodeFromResources("WriteCodeFragment.SkippedNumberedParameter", index);
                            return(null);
                        }

                        // "_Parameter01" and "_Parameter1" would overwrite each other
                        orderedParameters[index - 1] = new CodeAttributeArgument(String.Empty, new CodePrimitiveExpression(value));
                    }
                    else
                    {
                        namedParameters.Add(new CodeAttributeArgument(name, new CodePrimitiveExpression(value)));
                    }
                }

                bool encounteredNull = false;
                for (int i = 0; i < orderedParameters.Count; i++)
                {
                    if (orderedParameters[i] == null)
                    {
                        // All subsequent args should be null, else a slot was missed
                        encounteredNull = true;
                        continue;
                    }

                    if (encounteredNull)
                    {
                        Log.LogErrorWithCodeFromResources("WriteCodeFragment.SkippedNumberedParameter", i + 1 /* back to 1 based */);
                        return(null);
                    }

                    attribute.Arguments.Add(orderedParameters[i]);
                }

                foreach (CodeAttributeArgument namedParameter in namedParameters)
                {
                    attribute.Arguments.Add(namedParameter);
                }

                unit.AssemblyCustomAttributes.Add(attribute);
                haveGeneratedContent = true;
            }

            var generatedCode = new StringBuilder();

            using (var writer = new StringWriter(generatedCode, CultureInfo.CurrentCulture))
            {
                provider.GenerateCodeFromCompileUnit(unit, writer, new CodeGeneratorOptions());
            }

            string code = generatedCode.ToString();

            // If we just generated infrastructure, don't bother returning anything
            // as there's no point writing the file
            return(haveGeneratedContent ? code : String.Empty);
        }
Example #59
0
 public Generator(CodeDomProvider codeProvider, string extension)
 {
     DefaultExtension = extension;
     CodeProvider     = codeProvider;
 }
 public override string ImportSchemaType(string name, string namespaceName, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider)
 {
     throw new NotImplementedException();
 }