Exemplo n.º 1
0
        static async void testc()
        {
            var srcfile = System.IO.Path.Combine("D:\\git\\nel\\SmartContractBrowser\\SmartContractBrowser\\sample_contract", "sample_contract" + ".csproj");

            try
            {
                DateTime t01 = DateTime.Now;
                Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace workspace = Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create();

                DateTime t02  = DateTime.Now;
                var      proj = await workspace.OpenProjectAsync(srcfile);

                DateTime t03 = DateTime.Now;

                var com = await proj.GetCompilationAsync();

                DateTime t04 = DateTime.Now;

                var ms    = new System.IO.MemoryStream();
                var mspdb = new System.IO.MemoryStream();
                com.Emit(ms, mspdb);
                DateTime t05 = DateTime.Now;
                Console.WriteLine("init rosyln time=" + (t02 - t01).TotalMilliseconds);
                Console.WriteLine("open project time=" + (t03 - t02).TotalMilliseconds);
                Console.WriteLine("build time=" + (t04 - t03).TotalMilliseconds);
                Console.WriteLine("gen dll & pdb time=" + (t05 - t04).TotalMilliseconds);
                List <string> errinfo  = new List <string>();
                var           bytes    = ms.ToArray();
                var           bytespdb = mspdb.ToArray();
                var           b        = BuildNeon(new System.IO.MemoryStream(bytes), new System.IO.MemoryStream(bytespdb), errinfo);
            }
            catch (Exception err)
            {
            }
        }
Exemplo n.º 2
0
        public static async Task <bool> Build2(List <string> errorinfo)
        {
            var srcfile = System.IO.Path.Combine(BuildPath, "sample_contract" + ".csproj");

            try
            {
                Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace workspace = Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create();
                var proj = await workspace.OpenProjectAsync(srcfile);

                var com = await proj.GetCompilationAsync();
            }
            catch (Exception err)
            {
            }

            return(true);
        }
Exemplo n.º 3
0
        public static void Rename(ILogger _logger, string solutionPath, string projectPath, List <PreRenameData> lstRenames, CancellationToken cancellationToken)
        {
            using (Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace workspace = Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create())
            {
                // Open the solution within the workspace.
                Microsoft.CodeAnalysis.Solution solution = workspace.OpenSolutionAsync(solutionPath).Result;
                bool isProjectFound = false;
                foreach (Microsoft.CodeAnalysis.ProjectId projectId in solution.ProjectIds)
                {
                    // Look up the snapshot for the original project in the latest forked solution.
                    Microsoft.CodeAnalysis.Project project = solution.GetProject(projectId);
                    if (project.FilePath == projectPath)
                    {
                        isProjectFound = true;
                        foreach (Microsoft.CodeAnalysis.DocumentId documentId in project.DocumentIds)
                        {
                            // Look up the snapshot for the original document in the latest forked solution.
                            Microsoft.CodeAnalysis.Document document = solution.GetDocument(documentId);
                            //tg.RelativePathToGeneratedFile

                            // only in 'main' declaration files
                            //TODO implement based on knowledge of generated file ???
                            if (Path.GetDirectoryName(document.FilePath).EndsWith("ViewModels"))
                            {
                                if (Path.GetExtension(document.FilePath) == "cs")
                                {
                                    CodeAnalysisCSharp.Rename(_logger, solution, document, lstRenames, cancellationToken).Wait();
                                }
                                else if (Path.GetExtension(document.FilePath) == "vb")
                                {
                                    CodeAnalysisVisualBasic.Rename(solution, document, lstRenames, cancellationToken).Wait();
                                }
                                else
                                {
                                    throw new NotSupportedException();
                                }
                            }
                        }
                    }
                }
                if (!isProjectFound)
                {
                    throw new Exception("Project not found");
                }
            }
        }
Exemplo n.º 4
0
        public static void Compile(ILogger _logger, string solutionPath, CancellationToken cancellationToken)
        {
            //var lstBuilds = Microsoft.Build.Locator.MSBuildLocator.QueryVisualStudioInstances().ToList();
            //var build = lstBuilds[0];
            //Microsoft.Build.Locator.MSBuildLocator.RegisterInstance(build);
            //Microsoft.Build.Locator.VisualStudioInstanceQueryOptions.Default = new Microsoft.Build.Locator.VisualStudioInstanceQueryOptions() { DiscoveryType = Microsoft.Build.Locator.DiscoveryType.DotNetSdk };
            //Microsoft.Build.Locator.MSBuildLocator.RegisterDefaults();
            var properties = new Dictionary <string, string>
            {
                //{ "Configuration", "Release" },
                // Use the latest language version to force the full set of available analyzers to run on the project.
                { "LangVersion", "latest" },
            };

            using (Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace workspace = Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create(properties))
            //https://gist.github.com/DustinCampbell/32cd69d04ea1c08a16ae5c4cd21dd3a3
            //using (Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace workspace = Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create())
            {
                _logger.LogInformation("Compiling solution {0}".FilePos(), solutionPath);
                Microsoft.CodeAnalysis.Solution solution = workspace.OpenSolutionAsync(solutionPath).Result;
                if (workspace.Diagnostics.Count > 0)
                {
                    var en = workspace.Diagnostics.GetEnumerator();
                    en.MoveNext();
                    if (en.Current.Kind == Microsoft.CodeAnalysis.WorkspaceDiagnosticKind.Failure)
                    {
                        throw new Exception(en.Current.Message);
                    }
                }
                foreach (var project in solution.Projects)
                {
                    var compilation = project.GetCompilationAsync().Result;
                    var diag        = compilation.GetDiagnostics();
                    var lst         = from p in diag where p.Severity == Microsoft.CodeAnalysis.DiagnosticSeverity.Error select p;
                    if (lst.Count() > 0)
                    {
                        throw new Exception("Compilation errors are found.\nSolution: " + solutionPath + "\nProject: " + project.FilePath);
                    }
                }
            }
        }
Exemplo n.º 5
0
        private static int MainInner(string[] args)
        {
            Timing timing = new Timing();

            while (args.Length != 0)
            {
                const int NumArgs = 3;

                if (args.Length < NumArgs)
                {
                    throw new ArgumentException();
                }

                string solutionBasePath          = args[0];
                string interfacesProjectBasePath = args[1];
                string targetProjectName         = args[2];

                Array.Copy(args, NumArgs, args, 0, args.Length - NumArgs);
                Array.Resize(ref args, args.Length - NumArgs);

                string targetSolutionFilePath = FindFirstFile(solutionBasePath, ".sln");

                string interfacesProjectName      = Path.GetFileName(interfacesProjectBasePath);
                string interfacesSolutionFilePath = FindFirstFile(Path.GetDirectoryName(interfacesProjectBasePath), ".sln");

                string templateProjectBasePath = Path.Combine(solutionBasePath, "Template"); // TODO: hardcoded

                string[] doNotUnload;
                string[] imports;
                Config[] configs = Config.LoadConfigs(Path.Combine(solutionBasePath, targetProjectName, "transform.xml"), out doNotUnload, out imports);



                timing.Mark("Init/Load");

                Solution interfacesSolution, targetSolution;
                Project  interfacesProject, targetProject;
                {
                    Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace workspace = Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create();

                    // load interface project
                    interfacesSolution = workspace.OpenSolutionAsync(interfacesSolutionFilePath).Result;
                    interfacesProject  = interfacesSolution.Projects.First(delegate(Project p) { return(String.Equals(p.Name, interfacesProjectName)); });

                    // load target project
                    targetSolution = workspace.OpenSolutionAsync(targetSolutionFilePath).Result;
                    targetProject  = targetSolution.Projects.First(delegate(Project p) { return(String.Equals(p.Name, targetProjectName)); });

                    // remove all preexisting specializations since we'll be regenerating them and don't want multiply-defined errors
                    foreach (DocumentId documentId in targetProject.DocumentIds)
                    {
                        if (Array.IndexOf(doNotUnload, targetProject.GetDocument(documentId).Name) < 0)
                        {
                            targetProject = targetProject.RemoveDocument(documentId);
                        }
                    }
                }



                Compilation targetCompilation     = null;
                Compilation interfacesCompilation = null;

                foreach (Config config in configs)
                {
                    string templateSourceFilePath = Path.Combine(templateProjectBasePath, Path.ChangeExtension(config.templateClassName, ".cs"));
                    string targetFilePath         = Path.Combine(solutionBasePath, targetProjectName, "Generated", Path.ChangeExtension(config.targetClassName, ".cs"));

                    ConsoleColor oldColor = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine(config.targetClassName);
                    Console.ForegroundColor = oldColor;

                    // lazy init
                    if (targetCompilation == null)
                    {
                        Task <Compilation> targetCompiling     = targetProject.GetCompilationAsync();
                        Task <Compilation> interfacesCompiling = interfacesProject.GetCompilationAsync();
                        Task.WaitAll(targetCompiling, interfacesCompiling);
                        targetCompilation     = targetCompiling.Result;
                        interfacesCompilation = interfacesCompiling.Result;
                    }

                    Generate(config, targetCompilation, templateSourceFilePath, targetFilePath, interfacesCompilation, timing);
                }

                if (Debugger.IsAttached) // report after each command line argument group
                {
                    timing.Finish();

                    timing.WriteReport();
                }
            }

            timing.Finish();

            timing.WriteReport();



            Console.WriteLine("Finished");
            if (Debugger.IsAttached)
            {
                Console.ReadLine();
            }
            return(0);
        }
Exemplo n.º 6
0
        public async Task <buildResult> buildSrc(string src, string temppath)
        {
            Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace workspace = Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create();
            var path = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location);
            //build proj
            var bts      = System.Text.Encoding.UTF8.GetBytes(src);
            var hashname = ToHexString(sha1.ComputeHash(bts));
            var outpath  = System.IO.Path.Combine(path, temppath, hashname);

            lock (lockobj)//不要同时搞目录
            {
                if (System.IO.Directory.Exists(outpath))
                {
                    System.IO.Directory.Delete(outpath, true);
                }
                if (System.IO.Directory.Exists(outpath) == false)
                {
                    System.IO.Directory.CreateDirectory(outpath);
                }
                System.IO.File.Copy(System.IO.Path.Combine(path, "sample_contract\\mscorlib.dll"), System.IO.Path.Combine(outpath, "mscorlib.dll"), true);
                System.IO.File.Copy(System.IO.Path.Combine(path, "sample_contract\\Neo.SmartContract.Framework.dll"), System.IO.Path.Combine(outpath, "Neo.SmartContract.Framework.dll"), true);
                System.IO.File.Copy(System.IO.Path.Combine(path, "sample_contract\\sample_contract.csproj"), System.IO.Path.Combine(outpath, "sample_contract.csproj"), true);
                System.IO.File.WriteAllText(System.IO.Path.Combine(outpath, "Contract.cs"), src);
            }
            //srcfile
            var     projfile = System.IO.Path.Combine(outpath, "sample_contract.csproj");
            Project proj     = null;

            try
            {
                proj = await workspace.OpenProjectAsync(projfile);

                var com = await proj.GetCompilationAsync();

                var         diag = com.GetDiagnostics();
                buildResult br   = new buildResult();

                foreach (var d in diag)
                {
                    if (d.Severity == DiagnosticSeverity.Warning)
                    {
                        Log item = new Log();
                        item.msg = d.GetMessage();
                        item.id  = d.Id;
                        if (d.Location.IsInSource)
                        {
                            var span = d.Location.GetLineSpan();
                            item.line = span.Span.Start.Line;
                            item.col  = span.Span.Start.Character;
                        }
                        //item.line =d.Location
                        br.warnings.Add(item);
                    }
                    else if (d.Severity == DiagnosticSeverity.Error)
                    {
                        Log item = new Log();
                        item.msg = d.GetMessage();
                        item.id  = d.Id;
                        if (d.Location.IsInSource)
                        {
                            var span = d.Location.GetLineSpan();
                            item.line = span.Span.Start.Line;
                            item.col  = span.Span.Start.Character;
                        }
                        br.errors.Add(item);
                    }
                }
                var ms    = new System.IO.MemoryStream();
                var mspdb = new System.IO.MemoryStream();
                com.Emit(ms, mspdb);
                br.dll = ms.ToArray();
                br.pdb = mspdb.ToArray();
                ms.Close();
                mspdb.Close();
                return(br);
            }
            catch (Exception err)
            {
                return(null);
            }
        }