Example #1
0
        private void ListSupportedLanguages()
        {
            // Loop through information about all compilers.
            CompilerInfo[] compiler_infos =
                CodeDomProvider.GetAllCompilerInfo();
            foreach (CompilerInfo info in compiler_infos)
            {
                if (info.IsCodeDomProviderTypeValid)
                {
                    // Get information about this compiler.
                    CodeDomProvider provider = info.CreateProvider();

                    //string extensions = "";
                    string default_extension = provider.FileExtension;
                    if (default_extension[0] != '.')
                    {
                        default_extension = '.' + default_extension;
                    }

                    string default_language =
                        CodeDomProvider.GetLanguageFromExtension(default_extension);

                    toolStripComboBoxLang.Items.Add(default_language);
                }
            }
            if (toolStripComboBoxLang.Items.Count > 0)
            {
                toolStripComboBoxLang.SelectedIndex = 0;
            }
        }
Example #2
0
        private CompilerResults CompileScript(string filePath)
        {
            if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
            {
                return(null);
            }

            var language = CodeDomProvider.GetLanguageFromExtension(Path.GetExtension(filePath));
            //var codeDomProvider = CodeDomProvider.CreateProvider(language);
            var codeDomProvider = new CSharpCodeProvider(new Dictionary <string, string> {
                { "CompilerVersion", "v4.0" }
            });

            var compilerParams = new CompilerParameters
            {
                GenerateExecutable      = false,
                GenerateInMemory        = true,
                IncludeDebugInformation = false,
                CompilerOptions         = "/optimize"
            };

            Log.Info("Scripting", "Compiling :" + filePath);
            foreach (AssemblyName an in Assembly.GetExecutingAssembly().GetReferencedAssemblies())
            {
                compilerParams.ReferencedAssemblies.Add(an.Name + ".dll");
            }
            compilerParams.ReferencedAssemblies.Add("WorldServer.exe");

            return(codeDomProvider.CompileAssemblyFromFile(compilerParams, filePath));
        }
        // Quick and dirty compile to probe for metadata.
        private Assembly CompileTextToAssembly(string script)
        {
            bool   VB       = script.IndexOf("Imports System") != -1;
            string Language = CodeDomProvider.GetLanguageFromExtension(".cs");

            if (VB)
            {
                Language = CodeDomProvider.GetLanguageFromExtension(".vb");
            }

            CodeDomProvider    Provider = CodeDomProvider.CreateProvider(Language);
            CompilerParameters Params   = new CompilerParameters();

            Params.GenerateInMemory      = true; //Assembly is created in memory
            Params.TempFiles             = new TempFileCollection(Path.GetTempPath(), false);
            Params.TreatWarningsAsErrors = false;
            Params.WarningLevel          = 2;
            Params.ReferencedAssemblies.Add("System.dll");
            Params.ReferencedAssemblies.Add("System.Xml.dll");
            Params.ReferencedAssemblies.Add("System.Core.dll");
            Params.ReferencedAssemblies.Add("System.Data.Linq.dll");
            Params.ReferencedAssemblies.Add(Path.Combine(Configuration.ApsimBinDirectory(), "CSDotNetComponentInterface.dll"));
            Params.ReferencedAssemblies.Add(Path.Combine(Configuration.ApsimBinDirectory(), "DotNetProxies.dll"));
            Params.ReferencedAssemblies.Add(Path.Combine(Configuration.ApsimBinDirectory(), "CMPServices.dll"));
            Params.ReferencedAssemblies.Add(Path.Combine(Configuration.ApsimBinDirectory(), "CSGeneral.dll"));
            Params.TempFiles           = new TempFileCollection(".");
            Params.TempFiles.KeepFiles = false;

            CompilerResults results = Provider.CompileAssemblyFromSource(Params, new string [] { script });

            return(results.CompiledAssembly);
        }
Example #4
0
        /// <summary>
        /// Compile the specified 'code' into an executable assembly. If 'assemblyFileName'
        /// is null then compile to an in-memory assembly.
        /// </summary>
        /// <param name="code">The code to compile.</param>
        /// <param name="referencedAssemblies">Any referenced assemblies.</param>
        /// <returns>Any compile errors or null if compile was successful.</returns>
        private CompilerResults CompileTextToAssembly(string code, IEnumerable <string> referencedAssemblies = null)
        {
            if (provider == null)
            {
                provider = CodeDomProvider.CreateProvider(CodeDomProvider.GetLanguageFromExtension(".cs"));
            }

            var assemblyFileNameToCreate = Path.ChangeExtension(Path.Combine(Path.GetTempPath(), tempFileNamePrefix + Guid.NewGuid().ToString()), ".dll");

            CompilerParameters parameters = new CompilerParameters
            {
                GenerateInMemory = false,
                OutputAssembly   = assemblyFileNameToCreate
            };
            string sourceFileName = Path.ChangeExtension(assemblyFileNameToCreate, ".cs");

            File.WriteAllText(sourceFileName, code);

            parameters.OutputAssembly          = Path.ChangeExtension(assemblyFileNameToCreate, ".dll");
            parameters.TreatWarningsAsErrors   = false;
            parameters.IncludeDebugInformation = true;
            parameters.WarningLevel            = 2;
            foreach (var referencedAssembly in referencedAssemblies)
            {
                parameters.ReferencedAssemblies.Add(referencedAssembly);
            }
            parameters.TempFiles           = new TempFileCollection(Path.GetTempPath()); // ensure that any temp files are in a writeable area
            parameters.TempFiles.KeepFiles = false;
            return(provider.CompileAssemblyFromFile(parameters, new string[] { sourceFileName }));
        }
Example #5
0
        internal static IDictionary <string, string> GetProviderOptionsCollection(string fileExt)
        {
            Dictionary <string, string> opts = new Dictionary <string, string>();

            if (!CodeDomProvider.IsDefinedExtension(fileExt))
            {
                return(new ReadOnlyDictionary <string, string>(opts));
            }

            CompilerInfo ci = CodeDomProvider.GetCompilerInfo(CodeDomProvider.GetLanguageFromExtension(fileExt));

            if (ci == null)
            {
                return(new ReadOnlyDictionary <string, string>(opts));
            }

            // There is a fun little comment about this property in the framework code about making it
            // public after 3.5. Guess that didn't happen. Oh well. :)
            PropertyInfo pi = ci.GetType().GetProperty("ProviderOptions",
                                                       BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance);

            if (pi == null)
            {
                return(new ReadOnlyDictionary <string, string>(opts));
            }

            return(new ReadOnlyDictionary <string, string>((IDictionary <string, string>)pi.GetValue(ci, null)));
        }
Example #6
0
        internal CompilerType GetCompilerInfoFromExtension(string extension, bool throwOnFail)
        {
            CompilerType compilerTypeInternal;

            this.EnsureCompilerCacheInit();
            object   obj2     = this._compilerExtensions[extension];
            Compiler compiler = obj2 as Compiler;

            if (compiler != null)
            {
                compilerTypeInternal = compiler.CompilerTypeInternal;
                this._compilerExtensions[extension] = compilerTypeInternal;
            }
            else
            {
                compilerTypeInternal = obj2 as CompilerType;
            }
            if ((compilerTypeInternal == null) && CodeDomProvider.IsDefinedExtension(extension))
            {
                CompilerInfo compilerInfo = CodeDomProvider.GetCompilerInfo(CodeDomProvider.GetLanguageFromExtension(extension));
                compilerTypeInternal = new CompilerType(compilerInfo.CodeDomProviderType, compilerInfo.CreateDefaultCompilerParameters());
                this._compilerExtensions[extension] = compilerTypeInternal;
            }
            if (compilerTypeInternal == null)
            {
                if (throwOnFail)
                {
                    throw new HttpException(System.Web.SR.GetString("Invalid_lang_extension", new object[] { extension }));
                }
                return(null);
            }
            compilerTypeInternal = compilerTypeInternal.Clone();
            compilerTypeInternal.CompilerParameters.IncludeDebugInformation = this.Debug;
            return(compilerTypeInternal);
        }
        public static Task CreateIn(CodeGeneratorContext context, string directoryFullName)
        {
            CodeGeneration_Story.CreateProjectFile(context);
            if (!context.RequestHandlers.ContainsKey("AMAZON.StopIntent"))
            {
                CodeGeneration_Interaction.AddIntent(context, new List <string> {
                    "stop"
                }, new CodeStatementCollection());
            }

            UpdatePipeline((CodeCompileUnit)context.OtherFiles["Pipeline.cs"], context.RequestHandlers.Keys.ToArray());
            CodeGeneration_Fallback.Ensure(context);

            var json = JsonSerializer.Create(new JsonSerializerSettings {
                Formatting = Newtonsoft.Json.Formatting.Indented
            });

            using (var csharp = CodeDomProvider.CreateProvider(CodeDomProvider.GetLanguageFromExtension(".cs")))
            {
                var sceneFileDirectory   = Path.Combine(directoryFullName, "Scenes");
                var handlerFileDirectory = Path.Combine(directoryFullName, "RequestHandlers");
                Directory.CreateDirectory(sceneFileDirectory);
                Directory.CreateDirectory(handlerFileDirectory);

                return(Task.WhenAll(
                           OutputRootFiles(context.OtherFiles, csharp, json, directoryFullName),
                           OutputSkillManifest(context, json, directoryFullName),
                           OutputSceneFiles(context.SceneFiles, csharp, sceneFileDirectory),
                           OutputRequestHandlers(context.RequestHandlers, csharp, handlerFileDirectory)
                           ));
            }
        }
Example #8
0
        public void Roundtrip_Extension()
        {
            CodeDomProvider provider  = GetProvider();
            string          ext       = provider.FileExtension;
            CodeDomProvider provider2 = CodeDomProvider.CreateProvider(CodeDomProvider.GetLanguageFromExtension(ext));

            Assert.Equal(provider.GetType(), provider2.GetType());
        }
Example #9
0
    public static void CompileProxyDLL()
    {
        // Go open the proxy source file and read it's contents.
        StreamReader In       = new StreamReader(WriteableBaseProxyFileName);
        string       Contents = In.ReadToEnd();

        In.Close();

        In = new StreamReader(Path.Combine(Configuration.ApsimBinDirectory(), "DotNetProxies", "Properties", "AssemblyInfo.cs"));
        string AssemblyInfoContents = In.ReadToEnd();

        In.Close();

        In = new StreamReader(Path.Combine(Configuration.ApsimBinDirectory(), "Build", "VersionInfo.cs"));
        string VersionInfoContents = In.ReadToEnd();

        In.Close();

        string          language = CodeDomProvider.GetLanguageFromExtension(".cs");
        CodeDomProvider provider = CodeDomProvider.CreateProvider(language);

        if (provider != null)
        {
            CompilerParameters Params = new CompilerParameters();
            Params.GenerateInMemory        = false;
            Params.CompilerOptions         = "/platform:AnyCPU";
            Params.OutputAssembly          = Path.Combine(Configuration.ApsimBinDirectory(), "DotNetProxies.dll");
            Params.TreatWarningsAsErrors   = false;
            Params.WarningLevel            = 2;
            Params.IncludeDebugInformation = true;
            Params.ReferencedAssemblies.Add("System.dll");
            Params.ReferencedAssemblies.Add(Path.Combine(Configuration.ApsimBinDirectory(), "CSDotNetComponentInterface.dll"));
            Params.ReferencedAssemblies.Add(Path.Combine(Configuration.ApsimBinDirectory(), "CSGeneral.dll"));
            Params.ReferencedAssemblies.Add(Path.Combine(Configuration.ApsimBinDirectory(), "ApsimFile.dll"));
            String[] Source = new String[3];
            Source[0] = Contents;
            Source[1] = AssemblyInfoContents;
            Source[2] = VersionInfoContents;

            CompilerResults Results = provider.CompileAssemblyFromSource(Params, Source);

            string Errors = "";
            foreach (CompilerError err in Results.Errors)
            {
                if (Errors != "")
                {
                    Errors += "\r\n";
                }

                Errors += err.ErrorText + ". Line number: " + err.Line.ToString();
            }
            if (Errors != "")
            {
                throw new Exception(Errors);
            }
        }
    }
 protected virtual CodeDomProvider GetCodeDomProvider(IArtifactLink link)
 {
     if (link is ArtifactLink)
     {
         return(CodeDomProvider.CreateProvider(
                    CodeDomProvider.GetLanguageFromExtension(((ArtifactLink)link).DefaultExtension)));
     }
     return(new CSharp.CSharpCodeProvider());
 }
Example #11
0
 public static CodeDomProvider GetCodeDomProvider(EnvDTE.Project project)
 {
     if (project != null)
     {
         return
             (CodeDomProvider.CreateProvider(CodeDomProvider.GetLanguageFromExtension(GetDefaultExtension(project))));
     }
     return(CodeDomProvider.CreateProvider("C#"));
 }
        protected byte[] EnsureSilverlighCompatibility(byte[] generatedCodeBytes, CodeCompileUnit codeCompileUnit)
        {
            if (null == generatedCodeBytes)
            {
                throw new ArgumentNullException("generatedCodeBytes");
            }

            if (null == codeCompileUnit)
            {
                throw new ArgumentNullException("codeCompileUnit");
            }

            StringBuilder generatedCode = new StringBuilder(Encoding.UTF8.GetString(generatedCodeBytes));

            string compilerlanguage = CodeDomProvider.GetLanguageFromExtension(this.CodeProvider.FileExtension);

            switch (compilerlanguage)
            {
            case "c#":
            case "cs":
            case "csharp":
                Match csMatch = Regex.Match(generatedCode.ToString(), CSharpObfuscationAttributeFinderRegex);
                if ((null != csMatch) && csMatch.Success)
                {
                    generatedCode.Insert(csMatch.Index, CSharpCompilationDirectiveStart);
                    generatedCode.Insert(csMatch.Index + CSharpCompilationDirectiveStart.Length +
                                         csMatch.Length, CSharpCompilationDirectiveEnd);
                }
                break;

            case "vb":
            case "visualbasic":
                string className = codeCompileUnit.Namespaces[0].Types[0].Name;
                Match  vbMatch   = Regex.Match(generatedCode.ToString(), string.Format(VBClassAttributesFinderRegexTemplate, className));
                if ((null != vbMatch) && vbMatch.Success)
                {
                    string fullClassAttributesAndDeclaration = vbMatch.Value;
                    Match  obfuscationAttributeMatch         = Regex.Match(fullClassAttributesAndDeclaration, VBObfuscationAttributeFinderRegex);
                    if ((null != obfuscationAttributeMatch) && obfuscationAttributeMatch.Success)
                    {
                        string silverlightClassAttributesAndDeclaration = fullClassAttributesAndDeclaration.Remove(obfuscationAttributeMatch.Index,
                                                                                                                   obfuscationAttributeMatch.Length);
                        generatedCode.Insert(vbMatch.Index, VBCompilationDirectiveStart);
                        string elseDirectiveAndSilverlightAttributes = VBCompilationDirectiveElse + silverlightClassAttributesAndDeclaration +
                                                                       VBCompilationDirectiveEndIf;
                        generatedCode.Insert(vbMatch.Index + VBCompilationDirectiveStart.Length + vbMatch.Length, elseDirectiveAndSilverlightAttributes);
                    }
                }
                break;

            default:
                throw new ApplicationException(string.Format("The '{0}' language is not currently supported by the resource generator."));
            }

            return(Encoding.UTF8.GetBytes(generatedCode.ToString()));
        }
Example #13
0
        /*
         * Return a CompilerType that a extension maps to.
         */
        internal CompilerType GetCompilerInfoFromExtension(string extension, bool throwOnFail)
        {
            EnsureCompilerCacheInit();

            // First, try the cache (i.e. old <compilers> section)
            CompilerType compilerType;
            object       obj      = _compilerExtensions[extension];
            Compiler     compiler = obj as Compiler;

            if (compiler != null)
            {
                compilerType = compiler.CompilerTypeInternal;
                _compilerExtensions[extension] = compilerType;
            }
            else
            {
                compilerType = obj as CompilerType;
            }

            if (compilerType == null)
            {
                // If not, try the <codedom> section

                if (CodeDomProvider.IsDefinedExtension(extension))
                {
                    string language = CodeDomProvider.GetLanguageFromExtension(extension);

                    CompilerInfo ci = CodeDomProvider.GetCompilerInfo(language);

                    compilerType = new CompilerType(
                        ci.CodeDomProviderType, ci.CreateDefaultCompilerParameters());

                    // Cache it
                    _compilerExtensions[extension] = compilerType;
                }
            }

            if (compilerType == null)
            {
                if (!throwOnFail)
                {
                    return(null);
                }

                // Unsupported extension: throw an exception
                throw new HttpException(SR.GetString(SR.Invalid_lang_extension, extension));
            }

            // Clone it so the original is not modified
            compilerType = compilerType.Clone();

            // Set the value of the debug flag in the copy
            compilerType.CompilerParameters.IncludeDebugInformation = Debug;

            return(compilerType);
        }
Example #14
0
        internal static IDictionary <string, string> GetProviderOptions(Type codeDomProviderType)
        {
            CodeDomProvider provider      = (CodeDomProvider)Activator.CreateInstance(codeDomProviderType);
            string          fileExtension = provider.FileExtension;

            if (CodeDomProvider.IsDefinedExtension(fileExtension))
            {
                return(GetProviderOptions(CodeDomProvider.GetCompilerInfo(CodeDomProvider.GetLanguageFromExtension(fileExtension))));
            }
            return(null);
        }
Example #15
0
        static void DisplayAllCompilerInfo()
        {
            // <Snippet8>
            CompilerInfo [] allCompilerInfo = CodeDomProvider.GetAllCompilerInfo();
            foreach (CompilerInfo info in allCompilerInfo)
            {
                String defaultLanguage;
                String defaultExtension;

                CodeDomProvider provider = info.CreateProvider();

                // Display information about this configured provider.

                Console.WriteLine("Language provider:  {0}",
                                  provider.ToString());
                Console.WriteLine();

                Console.WriteLine("  Supported file extension(s):");
                foreach (String extension in info.GetExtensions())
                {
                    Console.WriteLine("    {0}", extension);
                }

                defaultExtension = provider.FileExtension;
                if (defaultExtension[0] != '.')
                {
                    defaultExtension = "." + defaultExtension;
                }
                Console.WriteLine("  Default file extension:  {0}",
                                  defaultExtension);
                Console.WriteLine();

                Console.WriteLine("  Supported language(s):");
                foreach (String language in info.GetLanguages())
                {
                    Console.WriteLine("    {0}", language);
                }

                defaultLanguage = CodeDomProvider.GetLanguageFromExtension(defaultExtension);
                Console.WriteLine("  Default language:        {0}",
                                  defaultLanguage);
                Console.WriteLine();

                // Get the compiler settings for this provider.
                CompilerParameters langCompilerConfig = info.CreateDefaultCompilerParameters();

                Console.WriteLine("  Compiler options:        {0}",
                                  langCompilerConfig.CompilerOptions);
                Console.WriteLine("  Compiler warning level:  {0}",
                                  langCompilerConfig.WarningLevel);
                Console.WriteLine();
            }
            // </Snippet8>
        }
Example #16
0
        internal static IDictionary <string, string> GetProviderOptions(Type codeDomProviderType)
        {
            // Using reflection to get the property for the time being.
            // This could simply return CompilerInfo.PropertyOptions if it goes public in future.
            CodeDomProvider provider  = (CodeDomProvider)Activator.CreateInstance(codeDomProviderType);
            string          extension = provider.FileExtension;

            if (CodeDomProvider.IsDefinedExtension(extension))
            {
                CompilerInfo ci = CodeDomProvider.GetCompilerInfo(CodeDomProvider.GetLanguageFromExtension(extension));
                return(GetProviderOptions(ci));
            }
            return(null);
        }
Example #17
0
        static void DisplayCompilerInfoUsingExtension(string fileExtension)
        {
            // <Snippet5>
            if (fileExtension[0] != '.')
            {
                fileExtension = "." + fileExtension;
            }

            // Get the language associated with the file extension.
            if (CodeDomProvider.IsDefinedExtension(fileExtension))
            {
                CodeDomProvider provider;
                String          language = CodeDomProvider.GetLanguageFromExtension(fileExtension);

                Console.WriteLine("The language \"{0}\" is associated with file extension \"{1}\"",
                                  language, fileExtension);
                Console.WriteLine();

                // Next, check for a corresponding language provider.

                if (CodeDomProvider.IsDefinedLanguage(language))
                {
                    provider = CodeDomProvider.CreateProvider(language);

                    // Display information about this language provider.

                    Console.WriteLine("Language provider:  {0}",
                                      provider.ToString());
                    Console.WriteLine();

                    // Get the compiler settings for this language.

                    CompilerInfo       langCompilerInfo   = CodeDomProvider.GetCompilerInfo(language);
                    CompilerParameters langCompilerConfig = langCompilerInfo.CreateDefaultCompilerParameters();

                    Console.WriteLine("  Compiler options:        {0}",
                                      langCompilerConfig.CompilerOptions);
                    Console.WriteLine("  Compiler warning level:  {0}",
                                      langCompilerConfig.WarningLevel);
                }
            }
            else
            {
                // Tell the user that the language provider was not found.
                Console.WriteLine("There is no language provider associated with input file extension \"{0}\".",
                                  fileExtension);
            }
            // </Snippet5>
        }
Example #18
0
        public static Language GetLanguage(this CodeDomProvider codeDomProvider)
        {
            switch (CodeDomProvider.GetLanguageFromExtension(codeDomProvider.FileExtension).ToLowerInvariant( ))
            {
            case "c#":
            case "cs":
            case "csharp":
                return(Language.CSharp);

            case "vb":
            case "visualbasic":
                return(Language.VisualBasic);

            default:
                return(Language.Unknown);
            }
        }
Example #19
0
        void GenerateSource(bool isSupportedVersion, string filePath, AssemblyBuilder assemblyBuilder, WorkflowService workflowService, out string codeFileName, out bool generatedSource, out string activityName)
        {
            // Get unique file and type name for the workflowservice
            codeFileName = assemblyBuilder.GetTempFilePhysicalPath(assemblyBuilder.CodeDomProvider.FileExtension);

            if (isSupportedVersion)
            {
                activityName = WorkflowServiceHostFactory.GetSupportedVersionGeneratedTypeName(filePath);
            }
            else
            {
                activityName = workflowService.Name.LocalName + "_" + Guid.NewGuid().ToString().Replace("-", "_");
            }

            TextExpressionCompilerSettings settings = new TextExpressionCompilerSettings
            {
                Activity               = workflowService.Body,
                ActivityName           = activityName,
                ActivityNamespace      = GeneratedNamespace,
                Language               = CodeDomProvider.GetLanguageFromExtension(assemblyBuilder.CodeDomProvider.FileExtension),
                GenerateAsPartialClass = false,
                AlwaysGenerateSource   = false,
                ForImplementation      = false
            };

            TextExpressionCompiler compiler = new TextExpressionCompiler(settings);

            generatedSource = false;
            using (StreamWriter fileStream = new StreamWriter(codeFileName))
            {
                try
                {
                    generatedSource = compiler.GenerateSource(fileStream);
                }
                catch (Exception ex)
                {
                    if (Fx.IsFatal(ex))
                    {
                        throw;
                    }

                    throw FxTrace.Exception.AsError(new HttpCompileException(SR.XamlBuildProviderExtensionException(ex.Message)));
                }
            }
        }
Example #20
0
        private CompilerResults CompileFile(string filepath)
        {
            string             language        = CodeDomProvider.GetLanguageFromExtension(Path.GetExtension(filepath));
            CodeDomProvider    codeDomProvider = CodeDomProvider.CreateProvider(language);
            CompilerParameters compilerParams  = new CompilerParameters
            {
                GenerateExecutable      = false,
                GenerateInMemory        = true,
                IncludeDebugInformation = false
            };

            compilerParams.ReferencedAssemblies.AddRange(
                Assembly.GetExecutingAssembly().GetReferencedAssemblies().Select(a => a.Name + ".dll").ToArray()
                );
            compilerParams.ReferencedAssemblies.Add("ActiveDirectory.Connector.dll");

            return(codeDomProvider.CompileAssemblyFromFile(compilerParams, filepath));
        }
Example #21
0
 private CodeTypeReference GlobalSelfReference(string type)
 {
     if (CodeDomProvider.GetLanguageFromExtension(_codeDomProvider.FileExtension) == "vb")
     {
         if (!string.IsNullOrEmpty(_rootNamespace))
         {
             return(new CodeTypeReference(string.Join(".", new string[] { _rootNamespace, type }), CodeTypeReferenceOptions.GlobalReference));
         }
         else
         {
             return(GlobalReference(type));
         }
     }
     else
     {
         return(GlobalReference(type));
     }
 }
Example #22
0
        public void Defaults()
        {
            cdp = new CodeDomProviderTest();              // execute ctor not a full trust
            Assert.AreEqual(String.Empty, cdp.FileExtension, "FileExtension");
            Assert.AreEqual(LanguageOptions.None, cdp.LanguageOptions, "LanguageOptions");
            Assert.IsNull(cdp.CreateCompiler(), "CreateCompiler");
            Assert.IsNull(cdp.CreateGenerator(), "CreateGenerator");
            Assert.IsNull(cdp.CreateGenerator(String.Empty), "CreateGenerator(string)");
            Assert.IsNull(cdp.CreateGenerator(writer), "CreateGenerator(TextWriter)");
            Assert.IsNull(cdp.CreateParser(), "CreateParser()");
            Assert.IsNotNull(cdp.GetConverter(typeof(string)), "GetConverter");
            Assert.IsNotNull(CodeDomProvider.GetAllCompilerInfo(), "GetAllCompilerInfo");

            // mono returns null (missing config?)
            CodeDomProvider.GetCompilerInfo("cs");
            CodeDomProvider.GetLanguageFromExtension("cs");

            Assert.IsFalse(CodeDomProvider.IsDefinedExtension(String.Empty), "String.Empty");
            Assert.IsFalse(CodeDomProvider.IsDefinedLanguage(String.Empty), "String.Empty");
        }
Example #23
0
        public Type[] GetScripts(string path)
        {
            string[] files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);

            string          language        = CodeDomProvider.GetLanguageFromExtension(Path.GetExtension(files[0]));
            CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider(language);

            var compilerParams = GetCompilerParameters();

            CompilerResults results = codeDomProvider.CompileAssemblyFromFile(compilerParams,
                                                                              files);

            if (NotifyErrors(results))
            {
                Console.Read();
                return(new Type[0]);
            }
            else
            {
                return(results.CompiledAssembly.GetTypes());
            }
        }
        public override bool Execute()
        {
            // 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";

            Log.LogDebugMessage("GenerateResourceDesigner Task");
            Log.LogDebugMessage("  NetResgenOutputFile: {0}", NetResgenOutputFile);
            Log.LogDebugMessage("  JavaResgenInputFile: {0}", JavaResgenInputFile);
            Log.LogDebugMessage("  Namespace: {0}", Namespace);
            Log.LogDebugMessage("  ResourceDirectory: {0}", ResourceDirectory);
            Log.LogDebugTaskItemsAndLogical("  AdditionalResourceDirectories:", AdditionalResourceDirectories);
            Log.LogDebugMessage("  IsApplication: {0}", IsApplication);
            Log.LogDebugMessage("  UseManagedResourceGenerator: {0}", UseManagedResourceGenerator);
            Log.LogDebugTaskItemsAndLogical("  Resources:", Resources);
            Log.LogDebugTaskItemsAndLogical("  References:", References);

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

            // 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
                };
                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;
            }

            // Create static resource overwrite methods for each Resource class in libraries.
            var assemblyNames = new List <string> ();

            if (IsApplication && References != null && References.Any())
            {
                // FIXME: should this be unified to some better code with ResolveLibraryProjectImports?
                using (var resolver = new DirectoryAssemblyResolver(this.CreateTaskLogger(), loadDebugSymbols: false)) {
                    foreach (var assemblyName in References)
                    {
                        var    suffix   = assemblyName.ItemSpec.EndsWith(".dll") ? String.Empty : ".dll";
                        string hintPath = assemblyName.GetMetadata("HintPath").Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
                        string fileName = assemblyName.ItemSpec + suffix;
                        string fullPath = Path.GetFullPath(assemblyName.ItemSpec);
                        // Skip non existing files in DesignTimeBuild
                        if (!File.Exists(fullPath) && DesignTimeBuild)
                        {
                            Log.LogDebugMessage("Skipping non existant dependancy '{0}' due to design time build.", fullPath);
                            continue;
                        }
                        resolver.Load(fullPath);
                        if (!String.IsNullOrEmpty(hintPath) && !File.Exists(hintPath))                           // ignore invalid HintPath
                        {
                            hintPath = null;
                        }
                        string assemblyPath = String.IsNullOrEmpty(hintPath) ? fileName : hintPath;
                        if (MonoAndroidHelper.IsFrameworkAssembly(fileName) && !MonoAndroidHelper.FrameworkEmbeddedJarLookupTargets.Contains(Path.GetFileName(fileName)))
                        {
                            continue;
                        }
                        Log.LogDebugMessage("Scan assembly {0} for resource generator", fileName);
                        assemblyNames.Add(assemblyPath);
                    }
                    var assemblies = assemblyNames.Select(assembly => resolver.GetAssembly(assembly));
                    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);

            return(!Log.HasLoggedErrors);
        }
Example #25
0
 static CompilerInfo GetCompilerInfo(string name)
 {
     return(CodeDomProvider.GetCompilerInfo(
                CodeDomProvider.GetLanguageFromExtension(Path.GetExtension(name))));
 }
Example #26
0
        /// <summary>
        /// Compile the specified 'code' into an executable assembly. If 'assemblyFileName'
        /// is null then compile to an in-memory assembly.
        /// </summary>
        public static Assembly CompileTextToAssembly(string code, string assemblyFileName)
        {
            // See if we've already compiled this code. If so then return the assembly.
            if (AssemblyCache.ContainsKey(code))
            {
                return(AssemblyCache[code]);
            }

            lock (AssemblyCache)
            {
                if (AssemblyCache.ContainsKey(code))
                {
                    return(AssemblyCache[code]);
                }
                bool   VB = code.IndexOf("Imports System") != -1;
                string Language;
                if (VB)
                {
                    Language = CodeDomProvider.GetLanguageFromExtension(".vb");
                }
                else
                {
                    Language = CodeDomProvider.GetLanguageFromExtension(".cs");
                }

                if (Language != null && CodeDomProvider.IsDefinedLanguage(Language))
                {
                    CodeDomProvider Provider = CodeDomProvider.CreateProvider(Language);
                    if (Provider != null)
                    {
                        CompilerParameters Params = new CompilerParameters();

                        string[] source = new string[1];
                        if (assemblyFileName == null)
                        {
                            Params.GenerateInMemory = true;
                            source[0] = code;
                        }
                        else
                        {
                            Params.GenerateInMemory = false;
                            Params.OutputAssembly   = assemblyFileName;
                            string sourceFileName;
                            if (VB)
                            {
                                sourceFileName = Path.ChangeExtension(assemblyFileName, ".vb");
                            }
                            else
                            {
                                sourceFileName = Path.ChangeExtension(assemblyFileName, ".cs");
                            }
                            File.WriteAllText(sourceFileName, code);
                            source[0] = sourceFileName;
                        }
                        Params.TreatWarningsAsErrors   = false;
                        Params.IncludeDebugInformation = true;
                        Params.WarningLevel            = 2;
                        Params.ReferencedAssemblies.Add("System.dll");
                        Params.ReferencedAssemblies.Add("System.Xml.dll");
                        Params.ReferencedAssemblies.Add("System.Windows.Forms.dll");
                        Params.ReferencedAssemblies.Add("System.Data.dll");
                        Params.ReferencedAssemblies.Add("System.Core.dll");
                        //Params.ReferencedAssemblies.Add("APSIM.Shared.dll");
                        Params.ReferencedAssemblies.Add(System.IO.Path.Combine(Assembly.GetExecutingAssembly().Location));

                        if (Assembly.GetCallingAssembly() != Assembly.GetExecutingAssembly())
                        {
                            Params.ReferencedAssemblies.Add(System.IO.Path.Combine(Assembly.GetCallingAssembly().Location));
                        }
                        Params.TempFiles           = new TempFileCollection(Path.GetTempPath()); // ensure that any temp files are in a writeable area
                        Params.TempFiles.KeepFiles = false;
                        CompilerResults results;
                        if (assemblyFileName == null)
                        {
                            results = Provider.CompileAssemblyFromSource(Params, source);
                        }
                        else
                        {
                            results = Provider.CompileAssemblyFromFile(Params, source);
                        }
                        string Errors = "";
                        foreach (CompilerError err in results.Errors)
                        {
                            if (Errors != "")
                            {
                                Errors += "\r\n";
                            }

                            Errors += err.ErrorText + ". Line number: " + err.Line.ToString();
                        }
                        if (Errors != "")
                        {
                            throw new Exception(Errors);
                        }

                        AssemblyCache.Add(code, results.CompiledAssembly);
                        return(results.CompiledAssembly);
                    }
                }
                throw new Exception("Cannot compile manager script to an assembly");
            }
        }
Example #27
0
        public Assembly Compile(bool debug, string languageOrExtension, params string[] sourceCode)
        {
            CodeDomProvider    provider;
            CompilerParameters parameters;
            CompilerResults    results;
            string             language = languageOrExtension;

            if (!CodeDomProvider.IsDefinedLanguage(languageOrExtension) && CodeDomProvider.IsDefinedExtension(languageOrExtension))
            {
                language = CodeDomProvider.GetLanguageFromExtension(languageOrExtension);
            }
            if (ConfigurationManager.GetSection("system.codedom") != null)
            {
                CompilerInfo compilerInfo = CodeDomProvider.GetCompilerInfo(language);
                provider   = compilerInfo.CreateProvider();
                parameters = compilerInfo.CreateDefaultCompilerParameters();
            }
            else
            {
                if ((!language.Equals("c#", StringComparison.OrdinalIgnoreCase) && !language.Equals("cs", StringComparison.OrdinalIgnoreCase)) && !language.Equals("csharp", StringComparison.OrdinalIgnoreCase))
                {
                    throw new CompilerException(string.Format("When running the {0} in an AppDomain without a system.codedom config section only the csharp language is supported. This happens if you are precompiling your views.", typeof(BatchCompiler).FullName));
                }
                string compilerVersion = GetCompilerVersion();
                Dictionary <string, string> dictionary2 = new Dictionary <string, string>();
                dictionary2.Add("CompilerVersion", compilerVersion);
                Dictionary <string, string> providerOptions = dictionary2;
                provider   = new CSharpCodeProvider(providerOptions);
                parameters = new CompilerParameters();
            }
            parameters.TreatWarningsAsErrors = false;
            string fileExtension = provider.FileExtension;

            foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                if (!assembly.IsDynamic())
                {
                    parameters.ReferencedAssemblies.Add(assembly.Location);
                }
            }
            string tempDir = AppDomain.CurrentDomain.SetupInformation.DynamicBase ?? Path.GetTempPath();

            parameters.TempFiles = new TempFileCollection(tempDir);
            if (debug)
            {
                parameters.IncludeDebugInformation = true;
                string        str5 = Path.Combine(tempDir, Guid.NewGuid().ToString("n"));
                List <string> list = new List <string>();
                int           num  = 0;
                foreach (string str6 in sourceCode)
                {
                    num++;
                    string path = string.Concat(new object[] { str5, "-", num, ".", fileExtension });
                    using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write))
                    {
                        using (StreamWriter writer = new StreamWriter(stream))
                        {
                            writer.Write(str6);
                        }
                    }
                    list.Add(path);
                }
                if (!string.IsNullOrEmpty(this.OutputAssembly))
                {
                    parameters.OutputAssembly = Path.Combine(tempDir, this.OutputAssembly);
                }
                else
                {
                    parameters.OutputAssembly = str5 + ".dll";
                }
                results = provider.CompileAssemblyFromFile(parameters, list.ToArray());
            }
            else
            {
                if (!string.IsNullOrEmpty(this.OutputAssembly))
                {
                    parameters.OutputAssembly = Path.Combine(tempDir, this.OutputAssembly);
                }
                else
                {
                    parameters.GenerateInMemory = true;
                }
                results = provider.CompileAssemblyFromSource(parameters, sourceCode);
            }
            if (!results.Errors.HasErrors)
            {
                return(results.CompiledAssembly);
            }
            StringBuilder builder = new StringBuilder();

            builder.AppendLine("Dynamic view compilation failed.");
            foreach (CompilerError error in results.Errors)
            {
                builder.AppendFormat("{4}({0},{1}): {2} {3}: ", new object[] { error.Line, error.Column, error.IsWarning ? "warning" : "error", error.ErrorNumber, error.FileName });
                builder.AppendLine(error.ErrorText);
            }
            builder.AppendLine();
            foreach (string str8 in sourceCode)
            {
                using (StringReader reader = new StringReader(str8))
                {
                    int num2 = 1;
                    while (true)
                    {
                        string str9 = reader.ReadLine();
                        if (str9 != null)
                        {
                            builder.Append(num2).Append(' ').AppendLine(str9);
                            num2++;
                        }
                    }
                }
            }
            throw new BatchCompilerException(builder.ToString(), results);
        }
        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);


            if (isFSharp)
            {
                language            = "C#";
                isCSharp            = true;
                NetResgenOutputFile = Path.ChangeExtension(NetResgenOutputFile, ".cs");
            }

            // 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 aliasMetaData = assembly.GetMetadata("Aliases");
                    if (!string.IsNullOrEmpty(aliasMetaData))
                    {
                        foreach (var alias in aliasMetaData.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            string aliasName = alias.Trim();
                            // don't emit an `extern alias global` as it is implicitly done.
                            if (string.Compare("global", aliasName, StringComparison.Ordinal) == 0)
                            {
                                continue;
                            }
                            aliases.Add(aliasName);
                            // only add the first alias for each reference.
                            break;
                        }
                    }
                    Log.LogDebugMessage("Scan assembly {0} for resource generator", fileName);
                }
                new ResourceDesignerImportGenerator(Namespace, resources, Log)
                .CreateImportMethods(assemblies);
            }

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

            // Write out our Resources.Designer.cs file

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

            return(!Log.HasLoggedErrors);
        }
 static CompilerInfo GetCSharpCompilerInfo()
 {
     return(CodeDomProvider.GetCompilerInfo(CodeDomProvider.GetLanguageFromExtension(".cs")));
 }
Example #30
0
 private static string GetLanguageFromExtension(string file)
 {
     return(CodeDomProvider.GetLanguageFromExtension(Path.GetExtension(file)));
 }