コード例 #1
0
        /// <summary>
        /// Method for compiling the code for testing in admin panel
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static ResultCompiler ResultCompiledScript(string code)
        {
            var result             = new ResultCompiler();
            var sourceFileResolver = new SourceFileResolver(ImmutableArray <string> .Empty, AppContext.BaseDirectory);
            var opts        = ScriptOptions.Default.WithSourceResolver(sourceFileResolver);
            var script      = CSharpScript.Create(code, opts);
            var compilation = script.GetCompilation();

            using (var ms = new MemoryStream())
            {
                var compilationResult = compilation.Emit(ms);
                if (compilationResult.Success)
                {
                    result.IsCompiled = true;
                }
                else
                {
                    foreach (var diagnostic in compilationResult.Diagnostics)
                    {
                        result.ErrorInfo.Add(diagnostic.ToString());
                    }
                }
            }
            return(result);
        }
コード例 #2
0
        private static CSharpCompilationOptions CreateCSharpCompilationOptions()
        {
            string moduleName                        = null;
            string mainTypeName                      = null;
            string scriptClassName                   = null;
            IEnumerable <string> usings              = null;
            OptimizationLevel    optimizationLevel   = OptimizationLevel.Debug;
            bool             checkOverflow           = false;
            bool             allowUnsafe             = false;
            string           cryptoKeyContainer      = null;
            string           cryptoKeyFile           = null;
            bool?            delaySign               = null;
            Platform         platform                = 0;
            ReportDiagnostic generalDiagnosticOption = 0;
            int warningLevel = 0;
            IEnumerable <KeyValuePair <string, ReportDiagnostic> > specificDiagnosticOptions = null;
            bool concurrentBuild = false;
            bool extendedCustomDebugInformation                 = true;
            XmlReferenceResolver      xmlReferenceResolver      = new XmlFileResolver(null);
            SourceReferenceResolver   sourceReferenceResolver   = new SourceFileResolver(ImmutableArray <string> .Empty, null);
            MetadataReferenceResolver metadataReferenceResolver = new AssemblyReferenceResolver(new MetadataFileReferenceResolver(ImmutableArray <string> .Empty, null), MetadataFileReferenceProvider.Default);
            AssemblyIdentityComparer  assemblyIdentityComparer  = AssemblyIdentityComparer.Default;         // Currently uses reference equality
            StrongNameProvider        strongNameProvider        = new DesktopStrongNameProvider();
            MetadataImportOptions     metadataImportOptions     = 0;
            ImmutableArray <string>   features = ImmutableArray <string> .Empty;

            return(new CSharpCompilationOptions(OutputKind.ConsoleApplication, moduleName, mainTypeName, scriptClassName, usings,
                                                optimizationLevel, checkOverflow, allowUnsafe, cryptoKeyContainer, cryptoKeyFile, delaySign,
                                                platform, generalDiagnosticOption, warningLevel, specificDiagnosticOptions,
                                                concurrentBuild, extendedCustomDebugInformation, xmlReferenceResolver, sourceReferenceResolver, metadataReferenceResolver,
                                                assemblyIdentityComparer, strongNameProvider, metadataImportOptions, features));
        }
コード例 #3
0
        private static ScriptOptions CreateScriptOptions(string filename, IEnumerable <string> include_dirs, IEnumerable <string> metadata_dirs)
        {
            string        base_path     = Path.GetDirectoryName(typeof(EntryPoint).GetTypeInfo().Assembly.Location);
            List <string> resolve_paths = new List <string>
            {
                Directory.GetCurrentDirectory(),
                          base_path
            };

            if (filename != null)
            {
                resolve_paths.Add(Path.GetDirectoryName(filename));
            }

            Type template_type = typeof(FixedProxyTemplate);
            SourceFileResolver     resolver          = new SourceFileResolver(include_dirs.Concat(resolve_paths), base_path);
            ScriptMetadataResolver metadata_resolver = ScriptMetadataResolver.Default
                                                       .WithBaseDirectory(base_path)
                                                       .WithSearchPaths(metadata_dirs.Concat(resolve_paths));

            return(ScriptOptions.Default.WithImports(template_type.Namespace, "CANAPE", "System",
                                                     "CANAPE.Utils", "CANAPE.Nodes", "CANAPE.Net.Utils",
                                                     "CANAPE.DataFrames", "CANAPE.Net.Templates.Factories",
                                                     "CANAPE.Net.Templates", "CANAPE.Security.Cryptography.X509Certificates")
                   .WithReferences(template_type.GetTypeInfo().Assembly,
                                   typeof(EntryPoint).GetTypeInfo().Assembly)
                   .WithSourceResolver(resolver)
                   .WithMetadataResolver(metadata_resolver));
        }
コード例 #4
0
ファイル: ScriptOptions.cs プロジェクト: kvainexx/roslyn
        /// <summary>
        /// Creates a new <see cref="ScriptOptions"/> with <see cref="SourceResolver"/> set to the default source resolver for the current platform.
        /// </summary>
        /// <param name="searchPaths">Directories to be used by the default resolver when resolving script file names.</param>
        /// <remarks>
        /// The default resolver looks up scripts in specified <paramref name="searchPaths"/> and in NuGet packages.
        /// </remarks>
        public ScriptOptions WithDefaultSourceResolution(ImmutableArray <string> searchPaths)
        {
            var resolver = new SourceFileResolver(
                ToImmutableArrayChecked(searchPaths, nameof(searchPaths)),
                baseDirectory: null);

            return(new ScriptOptions(this)
            {
                SourceResolver = resolver
            });
        }
コード例 #5
0
        void EnsureBaseDirectory()
        {
            var currentBaseDirectory = dependencyResolver.BaseDirectory;

            if (currentBaseDirectory != baseDirectory || sourceFileResolver == null)
            {
                baseDirectory      = currentBaseDirectory;
                sourceFileResolver = new SourceFileResolver(
                    ImmutableArray <string> .Empty,
                    baseDirectory);
            }
        }
コード例 #6
0
        private static CSharpCompilationOptions CreateCSharpCompilationOptions()
        {
            string moduleName                        = null;
            string mainTypeName                      = null;
            string scriptClassName                   = null;
            IEnumerable <string> usings              = null;
            OptimizationLevel    optimizationLevel   = OptimizationLevel.Debug;
            bool   checkOverflow                     = false;
            bool   allowUnsafe                       = false;
            string cryptoKeyContainer                = null;
            string cryptoKeyFile                     = null;
            ImmutableArray <byte> cryptoPublicKey    = default(ImmutableArray <byte>);
            bool?            delaySign               = null;
            Platform         platform                = 0;
            ReportDiagnostic generalDiagnosticOption = 0;
            int warningLevel = 0;
            IEnumerable <KeyValuePair <string, ReportDiagnostic> > specificDiagnosticOptions = null;
            bool                      concurrentBuild                  = false;
            bool                      deterministic                    = false;
            DateTime                  currentLocalTime                 = default(DateTime);
            bool                      debugPlusMode                    = false;
            XmlReferenceResolver      xmlReferenceResolver             = new XmlFileResolver(null);
            SourceReferenceResolver   sourceReferenceResolver          = new SourceFileResolver(ImmutableArray <string> .Empty, null);
            SyntaxTreeOptionsProvider syntaxTreeOptionsProvider        = null;
            MetadataReferenceResolver metadataReferenceResolver        = new MetadataReferenceResolverWithEquality();
            AssemblyIdentityComparer  assemblyIdentityComparer         = AssemblyIdentityComparer.Default;  // Currently uses reference equality
            StrongNameProvider        strongNameProvider               = new DesktopStrongNameProvider();
            MetadataImportOptions     metadataImportOptions            = 0;
            bool                      referencesSupersedeLowerVersions = false;
            bool                      reportSuppressedDiagnostics      = false;
            var topLevelBinderFlags = BinderFlags.None;
            var publicSign          = false;
            NullableContextOptions nullableContextOptions = NullableContextOptions.Disable;

            return(new CSharpCompilationOptions(OutputKind.ConsoleApplication,
                                                reportSuppressedDiagnostics, moduleName, mainTypeName, scriptClassName, usings,
                                                optimizationLevel, checkOverflow, allowUnsafe, cryptoKeyContainer, cryptoKeyFile,
                                                cryptoPublicKey, delaySign, platform, generalDiagnosticOption, warningLevel,
                                                specificDiagnosticOptions, concurrentBuild, deterministic, currentLocalTime,
                                                debugPlusMode, xmlReferenceResolver, sourceReferenceResolver,
                                                syntaxTreeOptionsProvider, metadataReferenceResolver, assemblyIdentityComparer,
                                                strongNameProvider, metadataImportOptions, referencesSupersedeLowerVersions,
                                                publicSign, topLevelBinderFlags, nullableContextOptions));
        }
コード例 #7
0
        public CSharpCompilationOptions CreateCSharpCompilationOptions()
        {
            string moduleName                        = null;
            string mainTypeName                      = null;
            string scriptClassName                   = null;
            IEnumerable <string> usings              = null;
            OptimizationLevel    optimizationLevel   = OptimizationLevel.Debug;
            bool             checkOverflow           = false;
            bool             allowUnsafe             = false;
            string           cryptoKeyContainer      = null;
            string           cryptoKeyFile           = null;
            bool?            delaySign               = null;
            int              fileAlignment           = 0;
            ulong            baseAddress             = 0;
            Platform         platform                = 0;
            ReportDiagnostic generalDiagnosticOption = 0;
            int              warningLevel            = 0;
            IEnumerable <KeyValuePair <string, ReportDiagnostic> > specificDiagnosticOptions = null;
            bool                      highEntropyVirtualAddressSpace = false;
            SubsystemVersion          subsystemVersion          = default(SubsystemVersion);
            string                    runtimeMetadataVersion    = null;
            bool                      concurrentBuild           = false;
            XmlReferenceResolver      xmlReferenceResolver      = new XmlFileResolver(null);
            SourceReferenceResolver   sourceReferenceResolver   = new SourceFileResolver(ImmutableArray <string> .Empty, null);
            MetadataReferenceResolver metadataReferenceResolver = new MetadataFileReferenceResolver(ImmutableArray <string> .Empty, null);
            MetadataReferenceProvider metadataReferenceProvider = MetadataFileReferenceProvider.Default;    // Currently uses reference equality
            AssemblyIdentityComparer  assemblyIdentityComparer  = AssemblyIdentityComparer.Default;         // Currently uses reference equality
            StrongNameProvider        strongNameProvider        = new DesktopStrongNameProvider();
            MetadataImportOptions     metadataImportOptions     = 0;
            ImmutableArray <string>   features = ImmutableArray <string> .Empty;

            return(new CSharpCompilationOptions(OutputKind.ConsoleApplication, moduleName, mainTypeName, scriptClassName, usings,
                                                optimizationLevel, checkOverflow, allowUnsafe, cryptoKeyContainer, cryptoKeyFile, delaySign, fileAlignment, baseAddress,
                                                platform, generalDiagnosticOption, warningLevel, specificDiagnosticOptions, highEntropyVirtualAddressSpace,
                                                subsystemVersion, runtimeMetadataVersion, concurrentBuild, xmlReferenceResolver, sourceReferenceResolver, metadataReferenceResolver, metadataReferenceProvider,
                                                assemblyIdentityComparer, strongNameProvider, metadataImportOptions, features));
        }
コード例 #8
0
        public BuildControl(Build build, string logFilePath)
        {
            DataContext = build;

            InitializeComponent();

            UpdateWatermark();

            searchLogControl.ExecuteSearch = (searchText, maxResults, cancellationToken) =>
            {
                var search  = new Search(new[] { Build }, Build.StringTable.Instances, maxResults, SettingsService.MarkResultsInTree);
                var results = search.FindNodes(searchText, cancellationToken);
                return(results);
            };
            searchLogControl.ResultsTreeBuilder  = BuildResultTree;
            searchLogControl.WatermarkDisplayed += () =>
            {
                Search.ClearSearchResults(Build);
                UpdateWatermark();
            };

            findInFilesControl.ExecuteSearch      = FindInFiles;
            findInFilesControl.ResultsTreeBuilder = BuildFindResults;

            Build = build;

            LogFilePath = logFilePath;

            if (build.SourceFilesArchive != null)
            {
                // first try to see if the source archive was embedded in the log
                sourceFileResolver = new SourceFileResolver(build.SourceFiles.Values);
            }
            else
            {
                // otherwise try to read from the .zip file on disk if present
                sourceFileResolver = new SourceFileResolver(logFilePath);
            }

            sharedTreeContextMenu = new ContextMenu();
            copyAllItem           = new MenuItem()
            {
                Header = "Copy All"
            };
            copyAllItem.Click += (s, a) => CopyAll();
            sharedTreeContextMenu.AddItem(copyAllItem);

            var contextMenu = new ContextMenu();

            // TODO
            //contextMenu.Opened += ContextMenu_Opened;
            copyItem = new MenuItem()
            {
                Header = "Copy"
            };
            copySubtreeItem = new MenuItem()
            {
                Header = "Copy subtree"
            };
            sortChildrenItem = new MenuItem()
            {
                Header = "Sort children"
            };
            copyNameItem = new MenuItem()
            {
                Header = "Copy name"
            };
            copyValueItem = new MenuItem()
            {
                Header = "Copy value"
            };
            viewItem = new MenuItem()
            {
                Header = "View"
            };
            preprocessItem = new MenuItem()
            {
                Header = "Preprocess"
            };
            hideItem = new MenuItem()
            {
                Header = "Hide"
            };
            copyItem.Click         += (s, a) => Copy();
            copySubtreeItem.Click  += (s, a) => CopySubtree();
            sortChildrenItem.Click += (s, a) => SortChildren();
            copyNameItem.Click     += (s, a) => CopyName();
            copyValueItem.Click    += (s, a) => CopyValue();
            viewItem.Click         += (s, a) => Invoke(treeView.SelectedItem as BaseNode);
            preprocessItem.Click   += (s, a) => Preprocess(treeView.SelectedItem as IPreprocessable);
            hideItem.Click         += (s, a) => Delete();
            contextMenu.AddItem(viewItem);
            contextMenu.AddItem(preprocessItem);
            contextMenu.AddItem(copyItem);
            contextMenu.AddItem(copySubtreeItem);
            contextMenu.AddItem(sortChildrenItem);
            contextMenu.AddItem(copyNameItem);
            contextMenu.AddItem(copyValueItem);
            contextMenu.AddItem(hideItem);

            var treeViewItemStyle = new Style(s => s.OfType <TreeViewItem>())
            {
                Setters = new ISetter[]
                {
                    new Setter(TreeViewItem.IsExpandedProperty, new Binding("IsExpanded")
                    {
                        Mode = BindingMode.TwoWay
                    }),
                    new Setter(TreeViewItem.IsSelectedProperty, new Binding("IsSelected")
                    {
                        Mode = BindingMode.TwoWay
                    }),
                    new Setter(IsVisibleProperty, new Binding("IsVisible")
                    {
                        Mode = BindingMode.TwoWay
                    })
                }
            };

            treeView.ContextMenu = contextMenu;
            treeView.Styles.Add(treeViewItemStyle);
            RegisterTreeViewHandlers(treeView);
            treeView.KeyDown         += TreeView_KeyDown;
            treeView.PropertyChanged += TreeView_SelectedItemChanged;
            treeView.GotFocus        += (s, a) => ActiveTreeView = treeView;

            ActiveTreeView = treeView;

            searchLogControl.ResultsList.Styles.Add(treeViewItemStyle);
            RegisterTreeViewHandlers(searchLogControl.ResultsList);
            searchLogControl.ResultsList.SelectionChanged += ResultsList_SelectionChanged;
            searchLogControl.ResultsList.GotFocus         += (s, a) => ActiveTreeView = searchLogControl.ResultsList;
            searchLogControl.ResultsList.ContextMenu       = sharedTreeContextMenu;

            findInFilesControl.GotFocus += (s, a) => ActiveTreeView = findInFilesControl.ResultsList;
            findInFilesControl.ResultsList.Styles.Add(treeViewItemStyle);
            RegisterTreeViewHandlers(findInFilesControl.ResultsList);
            findInFilesControl.ResultsList.GotFocus   += (s, a) => ActiveTreeView = findInFilesControl.ResultsList;
            findInFilesControl.ResultsList.ContextMenu = sharedTreeContextMenu;

            if (archiveFile != null)
            {
                filesTab.IsVisible       = true;
                findInFilesTab.IsVisible = true;
                PopulateFilesTab();
                filesTree.Styles.Add(treeViewItemStyle);
                RegisterTreeViewHandlers(filesTree);

                var text =
                    @"This log contains the full text of projects and imported files used during the build.
You can use the 'Files' tab in the bottom left to view these files and the 'Find in Files' tab for full-text search.
For many nodes in the tree (Targets, Tasks, Errors, Projects, etc) pressing SPACE or ENTER or double-clicking 
on the node will navigate to the corresponding source code associated with the node.

More functionality is available from the right-click context menu for each node.
Right-clicking a project node may show the 'Preprocess' option if the version of MSBuild was at least 15.3.";
                build.Unseal();
                build.AddChild(new Note {
                    Text = text
                });
                build.Seal();
            }

            breadCrumb.SelectionChanged += BreadCrumb_SelectionChanged;

            TemplateApplied += BuildControl_Loaded;

            preprocessedFileManager              = new PreprocessedFileManager(Build, sourceFileResolver);
            preprocessedFileManager.DisplayFile += path => DisplayFile(path);

            //PopulateTimeline();
        }
コード例 #9
0
        public BuildControl(Build build, string logFilePath)
        {
            InitializeComponent();

            UpdateWatermark();

            searchLogControl.ExecuteSearch = searchText =>
            {
                var search  = new Search(Build);
                var results = search.FindNodes(searchText);
                return(results);
            };
            searchLogControl.ResultsTreeBuilder  = BuildResultTree;
            searchLogControl.WatermarkDisplayed += () => UpdateWatermark();

            findInFilesControl.ExecuteSearch      = FindInFiles;
            findInFilesControl.ResultsTreeBuilder = BuildFindResults;

            VirtualizingPanel.SetIsVirtualizing(treeView, SettingsService.EnableTreeViewVirtualization);

            DataContext = build;
            Build       = build;

            LogFilePath = logFilePath;

            if (build.SourceFilesArchive != null)
            {
                // first try to see if the source archive was embedded in the log
                sourceFileResolver = new SourceFileResolver(build.SourceFilesArchive);
            }
            else
            {
                // otherwise try to read from the .zip file on disk if present
                sourceFileResolver = new SourceFileResolver(logFilePath);
            }

            sharedTreeContextMenu = new ContextMenu();
            copyAllItem           = new MenuItem()
            {
                Header = "Copy All"
            };
            copyAllItem.Click += (s, a) => CopyAll();
            sharedTreeContextMenu.Items.Add(copyAllItem);

            var contextMenu = new ContextMenu();

            contextMenu.Opened += ContextMenu_Opened;
            copyItem            = new MenuItem()
            {
                Header = "Copy"
            };
            copySubtreeItem = new MenuItem()
            {
                Header = "Copy subtree"
            };
            sortChildrenItem = new MenuItem()
            {
                Header = "Sort children"
            };
            copyNameItem = new MenuItem()
            {
                Header = "Copy name"
            };
            copyValueItem = new MenuItem()
            {
                Header = "Copy value"
            };
            viewItem = new MenuItem()
            {
                Header = "View"
            };
            preprocessItem = new MenuItem()
            {
                Header = "Preprocess"
            };
            hideItem = new MenuItem()
            {
                Header = "Hide"
            };
            copyItem.Click         += (s, a) => Copy();
            copySubtreeItem.Click  += (s, a) => CopySubtree();
            sortChildrenItem.Click += (s, a) => SortChildren();
            copyNameItem.Click     += (s, a) => CopyName();
            copyValueItem.Click    += (s, a) => CopyValue();
            viewItem.Click         += (s, a) => Invoke(treeView.SelectedItem as ParentedNode);
            preprocessItem.Click   += (s, a) => Preprocess(treeView.SelectedItem as Project);
            hideItem.Click         += (s, a) => Delete();
            contextMenu.Items.Add(viewItem);
            contextMenu.Items.Add(preprocessItem);
            contextMenu.Items.Add(copyItem);
            contextMenu.Items.Add(copySubtreeItem);
            contextMenu.Items.Add(sortChildrenItem);
            contextMenu.Items.Add(copyNameItem);
            contextMenu.Items.Add(copyValueItem);
            contextMenu.Items.Add(hideItem);

            var existingTreeViewItemStyle = (Style)Application.Current.Resources[typeof(TreeViewItem)];
            var treeViewItemStyle         = new Style(typeof(TreeViewItem), existingTreeViewItemStyle);

            treeViewItemStyle.Setters.Add(new Setter(TreeViewItem.IsExpandedProperty, new Binding("IsExpanded")
            {
                Mode = BindingMode.TwoWay
            }));
            treeViewItemStyle.Setters.Add(new Setter(TreeViewItem.IsSelectedProperty, new Binding("IsSelected")
            {
                Mode = BindingMode.TwoWay
            }));
            treeViewItemStyle.Setters.Add(new Setter(TreeViewItem.VisibilityProperty, new Binding("IsVisible")
            {
                Mode = BindingMode.TwoWay, Converter = new BooleanToVisibilityConverter()
            }));
            treeViewItemStyle.Setters.Add(new EventSetter(MouseDoubleClickEvent, (MouseButtonEventHandler)OnItemDoubleClick));
            treeViewItemStyle.Setters.Add(new EventSetter(PreviewMouseRightButtonDownEvent, (MouseButtonEventHandler)OnPreviewMouseRightButtonDown));
            treeViewItemStyle.Setters.Add(new EventSetter(RequestBringIntoViewEvent, (RequestBringIntoViewEventHandler)TreeViewItem_RequestBringIntoView));
            treeViewItemStyle.Setters.Add(new EventSetter(KeyDownEvent, (KeyEventHandler)OnItemKeyDown));

            treeView.ContextMenu          = contextMenu;
            treeView.ItemContainerStyle   = treeViewItemStyle;
            treeView.KeyDown             += TreeView_KeyDown;
            treeView.SelectedItemChanged += TreeView_SelectedItemChanged;
            treeView.GotFocus            += (s, a) => ActiveTreeView = treeView;

            ActiveTreeView = treeView;

            searchLogControl.ResultsList.ItemContainerStyle   = treeViewItemStyle;
            searchLogControl.ResultsList.SelectedItemChanged += ResultsList_SelectionChanged;
            searchLogControl.ResultsList.GotFocus            += (s, a) => ActiveTreeView = searchLogControl.ResultsList;
            searchLogControl.ResultsList.ContextMenu          = sharedTreeContextMenu;

            findInFilesControl.GotFocus += (s, a) => ActiveTreeView = findInFilesControl.ResultsList;
            findInFilesControl.ResultsList.ItemContainerStyle = treeViewItemStyle;
            findInFilesControl.ResultsList.GotFocus          += (s, a) => ActiveTreeView = findInFilesControl.ResultsList;
            findInFilesControl.ResultsList.ContextMenu        = sharedTreeContextMenu;

            if (archiveFile != null)
            {
                filesTab.Visibility       = Visibility.Visible;
                findInFilesTab.Visibility = Visibility.Visible;
                PopulateFilesTab();
                filesTree.ItemContainerStyle = treeViewItemStyle;

                var filesNote = new TextBlock();
                var text      =
                    @"This log contains the full text of projects and imported files used during the build.
You can use the 'Files' tab in the bottom left to view these files and the 'Find in Files' tab for full-text search.
For many nodes in the tree (Targets, Tasks, Errors, Projects, etc) pressing SPACE or ENTER or double-clicking 
on the node will navigate to the corresponding source code associated with the node.

More functionality is available from the right-click context menu for each node.
Right-clicking a project node may show the 'Preprocess' option if the version of MSBuild was at least 15.3.";
                build.Unseal();
                build.AddChild(new Note {
                    Text = text
                });
                build.Seal();
            }

            breadCrumb.SelectionChanged += BreadCrumb_SelectionChanged;

            Loaded += BuildControl_Loaded;

            preprocessedFileManager = new PreprocessedFileManager(this, sourceFileResolver);
        }
コード例 #10
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="InterceptDirectiveResolver"/> class.
 /// </summary>
 /// <param name="searchPaths">The search paths.</param>
 /// <param name="baseDirectory">The base directory.</param>
 public InterceptDirectiveResolver(ImmutableArray <string> searchPaths, string baseDirectory)
 {
     _sourceFileResolver = new SourceFileResolver(searchPaths, baseDirectory);
 }
コード例 #11
0
 public NavigationHelper(Build build, SourceFileResolver sourceFileResolver)
 {
     Build = build;
     SourceFileResolver = sourceFileResolver;
 }
コード例 #12
0
 public RemoteFileResolver(ImmutableArray <string> searchPaths, string baseDirectory)
 {
     _fileBasedResolver = new SourceFileResolver(searchPaths, baseDirectory);
 }
コード例 #13
0
        public static void Load(ApplicationPartManager applicationPartManager, AppConfig config)
        {
            if (applicationPartManager == null)
            {
                throw new ArgumentNullException(nameof(applicationPartManager));
            }

            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            if (!config.UseRoslynScripts)
            {
                return;
            }

            var referencedScripts = new List <ResultCompiler>();

            var roslynFolder = new DirectoryInfo(CommonPath.MapPath(ScriptPath));

            _shadowCopyScriptPath = new DirectoryInfo(CommonPath.MapPath(ShadowCopyScriptPath));
            Directory.CreateDirectory(_shadowCopyScriptPath.FullName);

            //clear bin files
            var binFiles = _shadowCopyScriptPath.GetFiles("*", SearchOption.AllDirectories);

            foreach (var f in binFiles)
            {
                try
                {
                    //ignore index.htm
                    var fileName = Path.GetFileName(f.FullName);
                    if (fileName.Equals("index.htm", StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    File.Delete(f.FullName);
                }
                catch (Exception exc)
                {
                    Debug.WriteLine("Error deleting file " + f.Name + ". Exception: " + exc);
                }
            }

            try
            {
                var ctxFiles = roslynFolder.GetFiles("*.csx", SearchOption.TopDirectoryOnly);
                foreach (var file in ctxFiles)
                {
                    var csxcript = new ResultCompiler
                    {
                        OriginalFile = file.FullName
                    };

                    string ctxCode            = File.ReadAllText(file.FullName);
                    var    sourceFileResolver = new SourceFileResolver(ImmutableArray <string> .Empty, AppContext.BaseDirectory);
                    var    opts        = ScriptOptions.Default.WithSourceResolver(sourceFileResolver);
                    var    script      = CSharpScript.Create(ctxCode, opts);
                    var    compilation = script.GetCompilation();
                    using (var ms = new MemoryStream())
                    {
                        var compilationResult = compilation.Emit(ms);

                        if (compilationResult.Success)
                        {
                            ms.Seek(0, SeekOrigin.Begin);
                            var shadowFileName = Path.Combine(_shadowCopyScriptPath.FullName, file.Name + "-" + Guid.NewGuid().ToString("D") + ".dll");
                            File.WriteAllBytes(shadowFileName, ms.ToArray());
                            Assembly shadowCopiedAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(shadowFileName);
                            csxcript.DLLAssemblyFile    = shadowFileName;
                            csxcript.ReferencedAssembly = shadowCopiedAssembly;
                            csxcript.IsCompiled         = true;
                            applicationPartManager.ApplicationParts.Add(new AssemblyPart(shadowCopiedAssembly));
                        }
                        else
                        {
                            foreach (var diagnostic in compilationResult.Diagnostics)
                            {
                                csxcript.ErrorInfo.Add(diagnostic.ToString());
                            }
                        }
                    }
                    referencedScripts.Add(csxcript);
                }
                ReferencedScripts = referencedScripts;
            }
            catch (Exception ex)
            {
                var msg = string.Format("Roslyn '{0}'", ex.Message);

                var fail = new Exception(msg, ex);
                throw fail;
            }
        }