public CompilerParameters ToCompilerParameters(string outputAssembly)
        {
            CompilerParameters cp = new CompilerParameters
            {
                GenerateExecutable      = false,
                GenerateInMemory        = false,
                WarningLevel            = WarningLevel,
                TreatWarningsAsErrors   = TreatWarningsAsErrors,
                IncludeDebugInformation = IncludeDebugInformation,
                CompilerOptions         = CompilerOptions,
                OutputAssembly          = outputAssembly,
                CoreAssemblyFileName    = CoreAssemblyFileName,
                Win32Resource           = Win32Resource
            };

            if (LinkedResources != null && LinkedResources.Count > 0)
            {
                cp.LinkedResources.AddRange(LinkedResources.ToArray());
            }

            if (EmbeddedResources != null && EmbeddedResources.Count > 0)
            {
                cp.EmbeddedResources.AddRange(EmbeddedResources.ToArray());
            }

            if (ReferencedAssemblies != null && ReferencedAssemblies.Count > 0)
            {
                cp.ReferencedAssemblies.AddRange(ReferencedAssemblies.ToArray());
            }

            return(cp);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 构造函数
        /// </summary>
        public ViewEngineCompilationOptions()
        {
            ReferencedAssemblies = DefaultReferencedAssemblies();
            MetadataReferences   = new HashSet <MetadataReference>();
            TemplateNamespace    = "TemplateNamespace";
            Inherits             = "ViewEngineCore.ViewEngineTemplateBase";
            DefaultUsings        = new HashSet <string>()
            {
                "System.Linq"
            };

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                if (RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework", StringComparison.OrdinalIgnoreCase))
                {
                    ReferencedAssemblies.Add(
                        Assembly.Load(
                            new AssemblyName(
                                "netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51")));
                }
                else
                {
                    ReferencedAssemblies.Add(Assembly.Load(new AssemblyName("netstandard")));
                }
            }
        }
        public CSharpScriptFile2()
        {
            ReferencedAssemblies.Add("Microsoft.CSharp.dll");
            ReferencedAssemblies.Add("System.dll");
            ReferencedAssemblies.Add("System.Core.dll");
            ReferencedAssemblies.Add("System.Data.dll");
            ReferencedAssemblies.Add("System.Linq.dll");
            ReferencedAssemblies.Add("System.Windows.Forms.dll");

            ScriptContent =
                "using System;" + Environment.NewLine +
                "using System.Collections.Generic; " + Environment.NewLine +
                "using System.Linq; " + Environment.NewLine +
                "using System.Text; " + Environment.NewLine +
                "using System.Threading.Tasks; " + Environment.NewLine +
                "using System.Windows.Forms; " + Environment.NewLine +
                "" + Environment.NewLine +
                "public class ScriptedClass" + Environment.NewLine +
                "{" + Environment.NewLine +
                "    public static object Execute(object obj)" + Environment.NewLine +
                "    {" + Environment.NewLine +
                "        return obj;" + Environment.NewLine +
                "    }" + Environment.NewLine +
                "}" + Environment.NewLine;
        }
        /// <summary>
        ///     Initializes a new instance of the <see cref="CSharpScriptFile" /> class.
        /// </summary>
        public CSharpScriptFile()
        {
            ReferencedAssemblies.Add("Microsoft.CSharp.dll");
            ReferencedAssemblies.Add("System.dll");
            ReferencedAssemblies.Add("System.Core.dll");
            ReferencedAssemblies.Add("System.Data.dll");
            ReferencedAssemblies.Add("System.Linq.dll");
            ReferencedAssemblies.Add("System.Windows.Forms.dll");

            ScriptContent =
                "using System;" + Environment.NewLine +
                "using System.Collections.Generic; " + Environment.NewLine +
                "using System.Linq; " + Environment.NewLine +
                "using System.Text; " + Environment.NewLine +
                "using System.Threading.Tasks; " + Environment.NewLine +
                "using System.Windows.Forms; " + Environment.NewLine +
                "" + Environment.NewLine +
                "public class ScriptedClass" + Environment.NewLine +
                "{" + Environment.NewLine +
                "    public static void Execute()" + Environment.NewLine +
                "    {" + Environment.NewLine +
                "        MessageBox.Show(\"Hello World! from script\");" + Environment.NewLine +
                "    }" + Environment.NewLine +
                "}" + Environment.NewLine;
        }
Ejemplo n.º 5
0
        protected override IEnumerable <string> GetValidationErrors()
        {
            try
            {
                var tree = (CSharpSyntaxTree)CSharpSyntaxTree.ParseText(Code);

                var portableExecutableReferences =
                    ReferencedAssemblies.Select(path => MetadataReference.CreateFromFile(path)).ToArray();
                var syntaxTrees = new[] { tree }.Concat(OtherCodeDependencies.Select(c => CSharpSyntaxTree.ParseText(c)));

                var compilation = CSharpCompilation.Create(
                    Guid.NewGuid().ToString(),
                    syntaxTrees,
                    portableExecutableReferences,
                    new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                    );

                var assembly = compilation.CompileToAssembly();
                var model    = compilation.GetSemanticModel(tree);

                var validationVisitor = new CSharpCodeSafetyVisitor(this, model);
                validationVisitor.Visit(tree.GetCompilationUnitRoot());
                Validator.Validate(compilation, tree, model, assembly);
                return(Enumerable.Empty <string>());
            }
            catch (CodeValidationException ex)
            {
                return(new[] { ex.Message });
            }
        }
Ejemplo n.º 6
0
        /// <devdoc>
        ///    <para>
        ///       Initializes a new instance of <see cref='Microsoft.CodeDom.Compiler.CompilerParameters'/> using the specified
        ///       assembly names, output name and a whether to include debug information flag.
        ///    </para>
        /// </devdoc>

        public CompilerParameters(string[] assemblyNames, string outputName, bool includeDebugInformation)
        {
            if (assemblyNames != null)
            {
                ReferencedAssemblies.AddRange(assemblyNames);
            }
            _outputName = outputName;
            _includeDebugInformation = includeDebugInformation;
        }
Ejemplo n.º 7
0
        private void LoadAssemblies()
        {
            _assemblies.Clear();
            _types.Clear();
            _allTypes.Clear();
            _legend.Clear();
            _referencedAssemblies.Clear();
            _currentGraph = null;
            ReferencedAssemblies?.Clear();
            AssemblyTypesSource?.Clear();
            Assemblies.SelectedItem = null;
            Types.SelectedItem      = null;
            Types.IsEnabled         = false;
            Dispatcher.Invoke(() => { Loading.Visibility = Visibility.Visible; MainGrid.IsEnabled = false; });
            var files = Directory.GetFiles(App.AssembliesPath, "*.dll");

            Task.Factory.StartNew(() =>
            {
                Parallel.ForEach(files, file =>
                {
                    try
                    {
                        Assembly assembly;
                        using (Stream stream = File.OpenRead(file))
                        {
                            byte[] rawAssembly = new byte[stream.Length];
                            stream.Read(rawAssembly, 0, (int)stream.Length);
                            assembly = Assembly.Load(rawAssembly);
                        }

                        var types = GetLoadableTypes(assembly).Where(x => _nameCheck.IsMatch(x.Name)).OrderBy(x => x.Name).ToList();
                        _allTypes.AddRange(types.Except(_allTypes));

                        _assemblies.Add(assembly.GetName().Name, assembly);
                        _types.Add(assembly.GetName().Name, types.OrderBy(x => x.Name).Select(x => new ComboBoxItem {
                            Content = x.Name, Tag = x
                        }));
                    }
                    catch (Exception)
                    {
                    }
                });

                _assemblies = _assemblies.OrderBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value);
                Dispatcher.Invoke(() =>
                {
                    Assemblies.IsEnabled = true;
                    Zoom.Visibility      = Visibility.Visible;
                    OnPropertyChanged(nameof(AllAssemblies));
                    OnPropertyChanged(nameof(AllTypes));
                    OnPropertyChanged(nameof(GraphItem));
                    OnPropertyChanged(nameof(TotalVertices));
                });
                Dispatcher.Invoke(() => { Loading.Visibility = Visibility.Collapsed; MainGrid.IsEnabled = true; });
            });
        }
Ejemplo n.º 8
0
 public static void AddAssemblies(params string[] assemblies)
 {
     foreach (string item in assemblies)
     {
         if (!ReferencedAssemblies.Contains(item))
         {
             ReferencedAssemblies.Add(item);
         }
     }
 }
Ejemplo n.º 9
0
 public CompilerParameters(String[] assemblyNames, String outputName,
                           bool includeDebugInformation)
 {
     this.outputName = outputName;
     this.includeDebugInformation = includeDebugInformation;
     this.warningLevel            = -1;
     if (assemblyNames != null)
     {
         ReferencedAssemblies.AddRange(assemblyNames);
     }
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Stock implementation of RenderTemplate that doesn't allow for
        /// any sort of assembly caching. Instead it creates and re-renders
        /// templates read from the reader each time.
        ///
        /// Custom implementations of RenderTemplate should be created that
        /// allow for caching by examing a filename or string hash to determine
        /// whether a template needs to be re-generated and compiled before
        /// rendering.
        /// </summary>
        /// <param name="reader">TextReader that points at the template to compile</param>
        /// <param name="context">Optional context to pass to template</param>
        /// <param name="writer">TextReader passed in that receives output</param>
        /// <returns></returns>
        public bool RenderTemplate(TextReader reader, object context, TextWriter writer)
        {
            var assemblyId = Engine.ParseAndCompileTemplate(ReferencedAssemblies.ToArray(), reader);

            if (assemblyId == null)
            {
                ErrorMessage = Engine.ErrorMessage;
                return(false);
            }

            return(RenderTemplateFromAssembly(assemblyId, context, writer));
        }
 // we need to use CompileEngine (which is slower but supports multiple file compilation
 public void compileExtraSourceCodeReferencesAndUpdateReferencedAssemblies()
 {
     if (ExtraSourceCodeFilesToCompile.size() > 0)
     {
         var assembly = new CompileEngine().compileSourceFiles(ExtraSourceCodeFilesToCompile);
         if (assembly != null)
         {
             ReferencedAssemblies.Add(assembly.Location);
             generateDebugSymbols = true;                // if there are extra assemblies we can't generate the assembly in memory
         }
     }
 }
Ejemplo n.º 12
0
        public override bool Execute( )
        {
            if (Language == null || string.IsNullOrEmpty(Language.ItemSpec))
            {
                Log.LogError("Missing Language PropertyItem definition in project to specify which CodeDomProvider to use.  e.g. <Language>C#</Language>");
                return(false);
            }

            // System.Diagnostics.Debugger.Launch ( );

            var provider = CreateCodeDomProvider(Language.ItemSpec);

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

            var hasLinguist             = ReferencedAssemblies.Any(reference => Path.GetFileName(reference.ItemSpec) == "Linguist.dll");
            var hasLinguistWPF          = ReferencedAssemblies.Any(reference => Path.GetFileName(reference.ItemSpec) == "Linguist.WPF.dll");
            var hasLinguistXamarinForms = ReferencedAssemblies.Any(reference => Path.GetFileName(reference.ItemSpec) == "Linguist.Xamarin.Forms.dll");

            var compile           = new List <ITaskItem> ( );
            var embeddedResources = new List <ITaskItem> ( );

            foreach (var localization in Localizations)
            {
                if (localization == null || string.IsNullOrEmpty(localization.ItemSpec))
                {
                    continue;
                }

                var resourceSet = Generator.ResourceExtractor.ExtractResources(localization.ItemSpec);
                var code        = GenerateCode(provider, RootNamespace.ItemSpec, localization.ItemSpec, resourceSet, hasLinguist, hasLinguistWPF, hasLinguistXamarinForms, out var baseName, out var manifestPath);
                var resources   = Path.Combine(IntermediateOutputPath.ItemSpec, manifestPath + "." + baseName + ".resources");

                GenerateEmbeddedResource(resources, resourceSet);

                var codeItem      = new TaskItem(code);
                var resourcesItem = new TaskItem(resources);

                resourcesItem.SetMetadata("ManifestResourceName", resources);

                compile.Add(codeItem);
                embeddedResources.Add(resourcesItem);
            }

            Compile           = compile.ToArray( );
            EmbeddedResources = embeddedResources.ToArray( );

            return(true);
        }
Ejemplo n.º 13
0
 // we need to use CompileEngine (which is slower but supports multiple file compilation
 public void compileExtraSourceCodeReferencesAndUpdateReferencedAssemblies()
 {
     if (ExtraSourceCodeFilesToCompile.size() > 0)
     {
         "[CSharp Compiler] Compiling provided {0} external source code references".info(ExtraSourceCodeFilesToCompile.size());
         var assembly = new CompileEngine(UseCachedAssemblyIfAvailable).compileSourceFiles(ExtraSourceCodeFilesToCompile);
         if (assembly != null)
         {
             ReferencedAssemblies.Add(assembly.Location);
             CompileEngine.setCachedCompiledAssembly(ExtraSourceCodeFilesToCompile, assembly);
             generateDebugSymbols = true;                // if there are extra assemblies we can't generate the assembly in memory
         }
     }
 }
Ejemplo n.º 14
0
        private void RecordReferencedNamespaceAndAssembly(string nspace, string assembly)
        {
            if (!String.IsNullOrEmpty((nspace)))
            {
                if (!ReferencedNamespaces.Contains(nspace) && ReferencedNamespace.Name != nspace)
                {
                    ReferencedNamespaces.Add(nspace);
                }
            }

            if (!ReferencedAssemblies.Contains(assembly) && grainAssembly.GetName().Name + "Client" != assembly)
            {
                ReferencedAssemblies.Add(assembly);
            }
        }
Ejemplo n.º 15
0
    //Execute
    public static void Execute(string sourceCode, string className, string methodName)
    {
        var compParms = new CompilerParameters {
            // True - exe file generation, false - dll file generation
            GenerateExecutable = true,
            // True - memory generation, false - external file generation
            GenerateInMemory = true,
            //OutputAssembly = exeName,
            TreatWarningsAsErrors = false,
            ReferencedAssemblies.Add("System");
        };

        //Add references
        var assemblies = AppDomain.CurrentDomain
                         .GetAssemblies()
                         .Where(a => !a.IsDynamic)
                         .Select(a => a.Location);

        compParms.ReferencedAssemblies.AddRange(assemblies.ToArray());

        //compile
        var             csProvider      = new CSharpCodeProvider();
        CompilerResults compilerResults = csProvider.CompileAssemblyFromSource(compParms, sourceCode);

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

        //Execute
        object     typeInstance = compilerResults.CompiledAssembly.CreateInstance(className);
        MethodInfo mi           = typeInstance.GetType().GetMethod(methodName);

        mi.Invoke(typeInstance, null);
    }
Ejemplo n.º 16
0
        public override bool Execute()
        {
            var frameworks = new List <ITaskItem> ();

            Directory.CreateDirectory(Path.Combine(IntermediateOutputPath, "Frameworks"));

            foreach (var assemblyPath in ReferencedAssemblies.Distinct().Where(x => !IsFrameworkItem(x)))
            {
                var assembly = AssemblyDefinition.ReadAssembly(assemblyPath.ItemSpec);

                // We should only get the embedded resources that ends with .framework
                var embeddedFrameworks = assembly.MainModule.Resources.Where(x => Path.GetExtension(x.Name) == ".framework");

                foreach (var resource in embeddedFrameworks)
                {
                    var embeddedFramework = resource as EmbeddedResource;

                    if (embeddedFramework == null)
                    {
                        continue;
                    }

                    var frameworkPath    = Path.Combine(IntermediateOutputPath, "Frameworks", embeddedFramework.Name);
                    var frameworkZipPath = frameworkPath + ".zip";

                    // The frameworks are embedded as zip files
                    using (var fileStream = File.OpenWrite(frameworkZipPath)) {
                        embeddedFramework.GetResourceStream().CopyTo(fileStream);
                    }

                    // Unzip the framework
                    using (var zipFile = ZipFile.Read(frameworkZipPath)) {
                        zipFile.ExtractAll(frameworkPath, ExtractExistingFileAction.OverwriteSilently);
                    }

                    File.Delete(frameworkZipPath);

                    var taskItem = new TaskItem(frameworkPath);

                    frameworks.Add(taskItem);
                }
            }

            Frameworks = frameworks.ToArray();

            return(true);
        }
        /// <summary>
        /// Internally tries to retrieve a previously compiled template from cache
        /// if not found compiles a template into an assembly
        /// always returns an assembly id as a string.
        /// </summary>
        /// <param name="templateText">The text to parse</param>
        /// <returns>assembly id as a string or null on error</returns>
        protected virtual CompiledAssemblyItem GetAssemblyFromStringAndCache(string templateText)
        {
            var hash = templateText.GetHashCode();

            CompiledAssemblyItem item;

            LoadedAssemblies.TryGetValue(hash, out item);

            string assemblyId = null;

            // Check for cached instance
            if (item != null)
            {
                assemblyId = item.AssemblyId;
            }
            else
            {
                item = new CompiledAssemblyItem();
            }

            // No cached instance - create assembly and cache
            if (assemblyId == null)
            {
                var safeClassName = GetSafeClassName(null);
                using (var reader = new StringReader(templateText))
                {
                    var refAssemblies = ReferencedAssemblies.ToArray();
                    assemblyId = Engine.ParseAndCompileTemplate(refAssemblies, reader, GeneratedNamespace, safeClassName);
                }

                if (assemblyId == null)
                {
                    ErrorMessage = Engine.ErrorMessage;
                    return(null);
                }

                item.AssemblyId     = assemblyId;
                item.CompileTimeUtc = DateTime.UtcNow;
                item.SafeClassName  = safeClassName;

                LoadedAssemblies[hash] = item;
            }

            return(item);
        }
Ejemplo n.º 18
0
 public XCodeCompileUnit(CodeCompileUnit source) : base()
 {
     if (source != null)
     {
         Namespaces.AddRange(source.Namespaces);
         EndDirectives.AddRange(source.EndDirectives);
         StartDirectives.AddRange(source.StartDirectives);
         AssemblyCustomAttributes.AddRange(source.AssemblyCustomAttributes);
         foreach (string name in source.ReferencedAssemblies)
         {
             ReferencedAssemblies.Add(name);
         }
         foreach (DictionaryEntry item in source.UserData)
         {
             UserData.Add(item.Key, item.Value);
         }
     }
 }
Ejemplo n.º 19
0
        private void FilterByAssemblies(DependencyGraph newGraph)
        {
            var matchingEdges = _currentGraph.Edges.Where(x => ReferencedAssemblies.Any(y => y.ShouldShow && x.Source.Assembly == y.AssemblyName) && ReferencedAssemblies.Any(y => y.ShouldShow && x.Target.Assembly == y.AssemblyName));

            foreach (var edge in matchingEdges)
            {
                if (!newGraph.Vertices.Contains(edge.Source))
                {
                    newGraph.AddVertex(edge.Source);
                }

                if (!newGraph.Vertices.Contains(edge.Target))
                {
                    newGraph.AddVertex(edge.Target);
                }

                newGraph.AddEdge(edge);
            }
        }
Ejemplo n.º 20
0
        public static void Initialize()
        {
            // for some reason, netstandard is missing from BuildManager.ReferencedAssemblies and yet, is part of
            // the references that CSharpCompiler receives - in some cases eg when building views - but not when
            // using BuildManager to build the PureLive models - where is it coming from? cannot figure it out

            // so... cheating here

            // this is equivalent to adding
            //         <add assembly="netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" />
            // to web.config system.web/compilation/assemblies

            var netStandard = ReferencedAssemblies.GetNetStandardAssembly();

            if (netStandard != null)
            {
                BuildManager.AddReferencedAssembly(netStandard);
            }
        }
Ejemplo n.º 21
0
        private void setReferencedAssemblies()
        {
            _compilerParams.ReferencedAssemblies.Add("System.dll");
            _compilerParams.ReferencedAssemblies.Add("System.Data.dll");
            _compilerParams.ReferencedAssemblies.Add("System.XML.dll");
            _compilerParams.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            _compilerParams.ReferencedAssemblies.Add("System.Drawing.dll");
            _compilerParams.ReferencedAssemblies.Add("System.Core.dll");
            _compilerParams.ReferencedAssemblies.Add("System.ComponentModel.DataAnnotations.dll");

            if (ReferencedAssemblies == null || !ReferencedAssemblies.Any())
            {
                return;
            }
            foreach (var asm in ReferencedAssemblies)
            {
                _compilerParams.ReferencedAssemblies.Add(asm);
            }
        }
Ejemplo n.º 22
0
        // ******************************************************************
        private void AddReferencedAssemblyFor(AssemblyDetails assemblyDetailsReferer, AssemblyName assemblyName)
        {
            var existingReferencedAsm = ReferencedAssemblies.FirstOrDefault(refAsm => refAsm.UniqueName == ReferencedAssembly.GetUniqueNameFromAssemblyName(assemblyName));

            if (existingReferencedAsm == null)
            {
                existingReferencedAsm = new ReferencedAssembly(assemblyName);

                object o1 = assemblyName.ProcessorArchitecture;
                object o2 = assemblyName.Flags;

                //string asmPath = Path.Combine(DirectoryPath, assemblyName.Name + ".dll");
                //if (File.Exists(asmPath))
                //{
                //	Assembly asm = Assembly.ReflectionOnlyLoadFrom(asmPath);
                //}

                this.ReferencedAssemblies.Add(existingReferencedAsm);
            }

            existingReferencedAsm.Referers.Add(assemblyDetailsReferer);
        }
        /// <summary>
        ///     Initializes a new instance of the <see cref="RuleFile" /> class.
        /// </summary>
        public RuleFile()
        {
            // Add the Rule Engine and all the other stuff ...
            ReferencedAssemblies.Add("Microsoft.CSharp.dll");
            ReferencedAssemblies.Add("System.dll");
            ReferencedAssemblies.Add("System.Core.dll");
            ReferencedAssemblies.Add("System.Data.dll");
            ReferencedAssemblies.Add("System.Linq.dll");

            ReferencedAssemblies.Add("NRules.dll");

            ScriptContent =
                @"
                using NRules.Fluent.Dsl;

                public class PreferredCustomerDiscountRule : Rule
                {
                    public override void Define()
                    {
                        Customer customer = null;
                        IEnumerable<Order> orders = null;

                        When()
                            .Match<Customer>(() => customer, c => c.IsPreferred)
                            .Query(() => orders, x => x
                                .Match<Order>(
                                    o => o.Customer == customer,
                                    o => !o.IsDiscounted)
                                .Collect()
                                .Where(c => c.Any()));

                        Then()
                            .Do(ctx => orders.ToList().ForEach(o => o.ApplyDiscount(10.0)))
                            .Do(ctx => orders.ToList().ForEach(ctx.Update));
                    }
                }
                ";
        }
Ejemplo n.º 24
0
 /// <summary>
 /// Add assembly references to the list of assemblies to
 /// include when compiling the code
 /// </summary>
 protected override void AddReferencedAssemblies()
 {
     if (!ReferencedAssemblies.Contains("System.dll"))
     {
         ReferencedAssemblies.Add("System.dll");
     }
     if (!ReferencedAssemblies.Contains("mscorlib.dll"))
     {
         ReferencedAssemblies.Add("mscorlib.dll");
     }
     if (!ReferencedAssemblies.Contains("system.xml.dll"))
     {
         ReferencedAssemblies.Add("system.xml.dll");
     }
     if (!ReferencedAssemblies.Contains(Assembly.GetExecutingAssembly().Location))
     {
         ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
     }
     if (!ReferencedAssemblies.Contains("System.Drawing.dll"))
     {
         ReferencedAssemblies.Add("System.Drawing.dll");
     }
 }
Ejemplo n.º 25
0
        //public string ProxyServer
        //{
        //    get { return m_proxyServer; }
        //    set { m_proxyServer = value; }
        //}

        #endregion

        #region utility
        protected override void AddReferencedAssemblies()
        {
            if (!ReferencedAssemblies.Contains("System.dll"))
            {
                ReferencedAssemblies.Add("System.dll");
            }
            if (!ReferencedAssemblies.Contains("mscorlib.dll"))
            {
                ReferencedAssemblies.Add("mscorlib.dll");
            }
            if (!ReferencedAssemblies.Contains("System.Xml.dll"))
            {
                ReferencedAssemblies.Add("System.Xml.dll");
            }
            if (!ReferencedAssemblies.Contains("System.Web.Services.dll"))
            {
                ReferencedAssemblies.Add("System.Web.Services.dll");
            }
            if (!ReferencedAssemblies.Contains("System.Data.dll"))
            {
                ReferencedAssemblies.Add("System.Data.dll");
            }
        }
        public static Assembly CompileCode(string code, string FileName, out CompilerResults result, string[] resourceFilePaths = null)
        {
            Microsoft.CSharp.CSharpCodeProvider csProvider = new Microsoft.CSharp.CSharpCodeProvider();

            CompilerParameters options = new CompilerParameters();

            options.GenerateExecutable = false; // we want a Dll (or "Class Library" as its called in .Net)

            if (FileName != null)
            {
                options.OutputAssembly = FileName;
            }
            else
            {
                options.GenerateInMemory = true;
            }

            // Add any references you want the users to be able to access, be warned that giving them access to some classes can allow
            // harmful code to be written and executed. I recommend that you write your own Class library that is the only reference it allows
            // thus they can only do the things you want them to.
            // (though things like "System.Xml.dll" can be useful, just need to provide a way users can read a file to pass in to it)
            // Just to avoid bloating this example to much, we will just add THIS program to its references, that way we don't need another
            // project to store the interfaces that both this class and the other uses. Just remember, this will expose ALL public classes to
            // the "script"

            //var assemblies = AppDomain.CurrentDomain
            //                .GetAssemblies()
            //                .Where(a => !a.IsDynamic)
            //                .Select(a => a.Location);

            //options.ReferencedAssemblies.AddRange(assemblies.ToArray());

            options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
            ReferencedAssemblies.ForEach(x => options.ReferencedAssemblies.Add(x));
            //options.ReferencedAssemblies.Add("System.Data.dll");
            //options.ReferencedAssemblies.Add("System.dll");
            //options.ReferencedAssemblies.Add("System.Xml.dll");
            //options.ReferencedAssemblies.Add("System.Data.Linq.dll");
            //options.ReferencedAssemblies.Add("ChampionshipSolutions.DM.dll");
            //options.ReferencedAssemblies.Add("mscorlib.dll");
            //options.ReferencedAssemblies.Add("System.Core.dll");

            if (resourceFilePaths != null)
            {
                foreach (string filePath in resourceFilePaths)
                {
                    if (System.IO.File.Exists(filePath))
                    {
                        options.EmbeddedResources.Add(filePath);
                    }
                }
            }

            // Compile our code
            //CompilerResults result;
            result = csProvider.CompileAssemblyFromSource(options, code);

            if (result.Errors.HasErrors)
            {
                // TODO: report back to the user that the script has errored
                return(null);
            }

            if (result.Errors.HasWarnings)
            {
                // TODO: tell the user about the warnings, might want to prompt them if they want to continue
                // running the "script"
            }

            return(result.CompiledAssembly);
        }
Ejemplo n.º 27
0
        public MetadataAssembly(Assembly assembly, ImmutableArray <byte> assemblyBytes, ImmutableArray <IAssembly> dependencies)
        {
            _diagnostics   = new DiagnosticBag(this);
            _assembly      = assembly;
            _assemblyBytes = assemblyBytes;
            if (assembly.FullName is null)
            {
                _diagnostics.Add(new Diagnostic(
                                     new Location(),
                                     ErrorCode.InvalidMetadataAssembly,
                                     ImmutableArray.Create <object?>("Metadata Assembly has no name")));
            }

            var assemblyNameAttributes = assembly.GetAttributes <AssemblyNameAttribute>();

            if (assemblyNameAttributes.Length != 1)
            {
                _diagnostics.Add(new Diagnostic(
                                     new Location(),
                                     ErrorCode.InvalidMetadataAssembly,
                                     ImmutableArray.Create <object?>($"Metadata Assembly must have exactly one {nameof(AssemblyNameAttribute)}")));
                Name = new QualifiedName("");
            }
            else
            {
                Name = QualifiedName.Parse(assemblyNameAttributes[0].Name);
            }

            var assemblyFileVersionAttributes = assembly.GetAttributes <AssemblyFileVersionAttribute>();

            if (assemblyFileVersionAttributes.Length != 1)
            {
                _diagnostics.Add(new Diagnostic(
                                     new Location(),
                                     ErrorCode.InvalidMetadataAssembly,
                                     ImmutableArray.Create <object?>($"Metadata Assembly must have exactly one {nameof(AssemblyFileVersionAttribute)}")));
                Version = new Version(0, 0, 0);
            }
            else
            {
                var versionAttribute = assemblyFileVersionAttributes[0];
                if (!Version.TryParse(versionAttribute.Version, out var version))
                {
                    _diagnostics.Add(new Diagnostic(
                                         new Location(),
                                         ErrorCode.InvalidMetadataAssembly,
                                         ImmutableArray.Create <object?>($"Version `{version}` is invalid")));
                    Version = new Version(0, 0, 0);
                }
                else
                {
                    Version = version;
                }
            }

            _referencedAssemblies = new Lazy <ImmutableArray <IAssembly> >(
                () => ((IAssembly)this).CalculateReferencedAssemblies(dependencies, _diagnostics).ToImmutableArray());
            _referencedAssembliesAndSelf = new Lazy <ImmutableArray <IAssembly> >(
                () => ReferencedAssemblies.Add(this));

            _methodsByName    = new Lazy <IReadOnlyDictionary <QualifiedName, IMethod> >(GenerateMethods);
            _methods          = new Lazy <ImmutableArray <IMethod> >(() => _methodsByName.Value.Values.ToImmutableArray());
            _interfacesByName = new Lazy <IReadOnlyDictionary <QualifiedName, IInterface> >(GenerateInterfaces);
            _interfaces       = new Lazy <ImmutableArray <IInterface> >(() => _interfacesByName.Value.Values.ToImmutableArray());
            _allDiagnostics   = new Lazy <ImmutableArray <Diagnostic> >(() =>
            {
                _diagnostics.EnsureAllDiagnosticsCollectedForSymbol();
                return(_diagnostics.ToImmutableArray());
            });
        }
Ejemplo n.º 28
0
 public OptionSet CreateOptions()
 {
     return(new OptionSet {
         { "a|async",
           "Generate async methods.",
           v => GenerateAsync = v != null },
         { "config=",
           "Configuration file names to generate.",
           v => ConfigFiles.AddRange(v.Split(',')) },
         { "i|internal",
           "Generate types as internal.",
           v => GenerateTypesAsInternal = v != null },
         { "l|language=",
           "Specify target code {LANGUAGE}. Default is 'csharp'.",
           v => Language = v },
         { "monotouch",
           "Generate MonoTouch client. (This option may vanish)",
           v => GenerateMonoTouchProxy = v != null },
         { "moonlight",
           "Generate moonlight client. (This option may vanish)",
           v => GenerateMoonlightProxy = v != null },
         { "n|namespace=",
           "Code namespace name to generate.",
           v => Namespace = v },
         { "noConfig",
           "Do not generate config file.",
           v => NoConfig = v != null },
         { "noLogo",
           "Do not show tool logo.",
           v => NoLogo = v != null },
         { "o|out=",
           "Output code filename.",
           v => OutputFilename = v },
         { "r|reference=",
           "Referenced assembly files.",
           v => ReferencedAssemblies.AddRange(v.Split(',')) },
         { "tcv|targetClientVersion:",
           "Indicate target client version. Valid values:\n" +
           "  Version35",
           v => {
               if (v == null)
               {
                   return;
               }
               switch (v.ToLowerInvariant())
               {
               case "version35":
                   TargetClientVersion35 = true;
                   break;
               }
           } },
         { "tm|typedMessage",
           "Generate typed messages.",
           v => GenerateTypedMessages = v != null },
         { "usage",
           "Show usage syntax and exit.",
           v => Usage = v != null },
         { "V|version",
           "Display version and licensing information.",
           v => Version = v != null },
         { "h|?|help",
           "Show this help list.",
           v => Help = v != null },
     });
 }
Ejemplo n.º 29
0
 /// <summary>
 /// Adds an assembly to the referenced assemblies from an existing
 /// .NET Type.
 /// </summary>
 /// <param name="instance"></param>
 public void AddAssemblyFromType(Type instance)
 {
     ReferencedAssemblies.Add(instance.Assembly.Location);
 }
 protected override void ExecuteCore()
 {
     BizTalkAssemblies = ReferencedAssemblies
                         .Where(a => Assembly.LoadFrom(a.GetMetadata("Identity")).IsBizTalkAssembly())
                         .ToArray();
 }