コード例 #1
0
        public async Task TestInitialize()
        {
            logger     = new Logger(new TestContextWrapper(TestContext));
            _VSHandler = new VSHandler(logger, delayMultiplier: 10);

            await _VSHandler.StartVSAsync(memSpectModeFlags : MemSpectModeFlags.MemSpectModeFull);

            logger.LogMessage($"TestInit starting VS pid= {_VSHandler.vsProc.Id}");
        }
コード例 #2
0
        public async Task TestInitialize()
        {
            logger     = new Logger(new TestContextWrapper(TestContext));
            _VSHandler = new VSHandler(logger);

            await _VSHandler.StartVSAsync();

            logger.LogMessage($"TestInit starting VS pid= {_VSHandler.vsProc.Id}");
            await _VSHandler.EnsureGotDTE(TimeSpan.FromSeconds(60));

            await _VSHandler.DteExecuteCommand("View.ErrorList");
        }
コード例 #3
0
        public async Task TestInitialize()
        {
            await Task.Yield();

            logger     = new Logger(new TestContextWrapper(TestContext));
            _VSHandler = new VSHandler(logger);
            logger.LogMessage($"Computername=" + Environment.GetEnvironmentVariable("Computername"));
            logger.LogMessage($"TEMP=" + Environment.GetEnvironmentVariable("TEMP"));
            logger.LogMessage($"LOCALAPPDATA=" + Environment.GetEnvironmentVariable("LOCALAPPDATA"));

            logger.LogMessage($"Username="******"Username"));
            logger.LogMessage($"UserDomain=" + Environment.GetEnvironmentVariable("userdomain"));
            logger.LogMessage($"ProgramFiles(x86)=" + Environment.GetEnvironmentVariable("ProgramFiles(x86)"));
            logger.LogMessage($"Path=" + Environment.GetEnvironmentVariable("path"));
            logger.LogMessage($"VS Path={VSHandler.GetVSFullPath()}");

            /*
             *
             * TestContext Messages:
             * 09:01:11:287  5 Computername=fv-az683
             * 09:01:11:287  5 TEMP=C:\Users\VSSADM~1\AppData\Local\Temp
             * 09:01:11:287  5 LOCALAPPDATA=C:\Users\VssAdministrator\AppData\Local
             * 09:01:11:287  5 Username=VssAdministrator
             * 09:01:11:287  5 UserDomain=fv-az683
             * 09:01:11:287  5 ProgramFiles(x86)=C:\Program Files (x86)
             * 09:01:11:287  5 Path=C:\agents\2.162.0\externals\git\cmd;C:/hostedtoolcache/windows\Python\3.6.8\x64;C:/hostedtoolcache/windows\Python\3.6.8\x64\Scripts;C:\Program Files\Mercurial\;C:\ProgramData\kind;C:\vcpkg;C:\cf-cli;C:\Program Files (x86)\NSIS\;C:\Program Files\Mercurial\;C:\Program Files\Boost\1.69.0;C:\Program Files\dotnet;C:\mysql-5.7.21-winx64\bin;C:\Program Files\Java\zulu-8-azure-jdk_8.40.0.25-8.0.222-win_x64\bin;C:\npm\prefix;C:\Program Files (x86)\sbt\bin;C:\Rust\.cargo\bin;C:\hostedtoolcache\windows\Ruby\2.5.5\x64\bin;C:\Go1.12.7\bin;C:\Program Files\Git\bin;C:\Program Files\Git\usr\bin;C:\Program Files\Git\mingw64\bin;C:\hostedtoolcache\windows\Python\3.7.5\x64\Scripts;C:\hostedtoolcache\windows\Python\3.7.5\x64;C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\windows\System32\OpenSSH\;C:\ProgramData\Chocolatey\bin;C:\Program Files\Docker;C:\Program Files\PowerShell\6\;C:\Program Files (x86)\Windows Kits\10\Windows Performance Toolkit\;C:\Program Files\dotnet\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\;C:\Program Files\Microsoft Service Fabric\bin\Fabric\Fabric.Code;C:\Program Files\Microsoft SDKs\Service Fabric\Tools\ServiceFabricLocalClusterManager;C:\Program Files\Git\cmd;C:\Program Files\Git\mingw64\bin;C:\Program Files\Git\usr\bin;c:\tools\php;C:\Program Files (x86)\sbt\bin;C:\Program Files (x86)\Subversion\bin;C:\Program Files\nodejs\;C:\ProgramData\chocolatey\lib\maven\apache-maven-3.6.2\bin;C:\Program Files\CMake\bin;C:\Strawberry\c\bin;C:\Strawberry\perl\site\bin;C:\Strawberry\perl\bin;C:\Program Files\OpenSSL\bin;C:\Users\VssAdministrator\.dotnet\tools;C:\Program Fil
             * 09:01:11:303  5 VS Path=C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\devenv.exe
             * 09:01:11:318  5 # of devenv = 0
             * 09:01:11:318  5 StartVSAsync
             * 09:01:13:104  5 Started VS PID= 7132
             * 09:01:13:104 10 EnsureGotDTE
             * 09:01:13:104 10 Latest devenv PID= 7132 starttime = 12/12/2019 9:01:12 PM
             * 09:01:43:454 10 Couldn't get DTE in 30 secs             */


            var vsprocs = Process.GetProcessesByName("devenv");

            logger.LogMessage($"# of devenv = {vsprocs.Length}");
            foreach (var devenv in vsprocs)
            {
                logger.LogMessage($" {devenv.MainModule.FileName}");
            }

            await _VSHandler.StartVSAsync();

            logger.LogMessage($"TestInit starting VS pid= {_VSHandler.vsProc.Id}");
        }
コード例 #4
0
        public void TestVSHandlerSettingsForLeakDetection()
        {
            LogMessage(VSHandler.DoVSRegEdit("read local HKCU General DelayTimeThreshold dword"));

            LogMessage(VSHandler.DoVSRegEdit("read local HKCU General MaxNavigationHistoryDepth dword"));
        }
コード例 #5
0
 public void TestGetVSPath()
 {
     Assert.IsNotNull(VSHandler.GetVSFullPath());
 }
コード例 #6
0
            // can be done on backgroun thread
            public void CompileTheCode()
            {
                var lstFilesToCompile = new HashSet <string>();
                var IsCSharp          = true;

                if (Path.GetExtension(pathFileToExecute).ToLower() == ".vb")
                {
                    IsCSharp      = false;
                    CommentPrefix = "'";
                }
                else
                {
                    CommentPrefix = "//";
                    IsCSharp      = true;
                }
                var hashofCodeToExecute = 0;
                var GenerateInMemory    = true;
                var UseCSC = true;

                verbose = false;
                var showWarnings = false;

                //            _logger.LogMessage($"Compiling code");
                try
                {
                    _lstRefDirs.Clear();
                    //logger.LogMessage($"Main file= { Process.GetCurrentProcess().MainModule.FileName}"); //  C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\Common7\IDE\Extensions\TestPlatform\testhost.x86.exe
                    var curProcMainModule = Process.GetCurrentProcess().MainModule.FileName;
                    var ndxCommon7        = curProcMainModule.IndexOf("common7", StringComparison.OrdinalIgnoreCase);
                    if (ndxCommon7 <= 0)
                    {
                        throw new InvalidOperationException("Can't find VSRoot");
                    }
                    var vsRoot = curProcMainModule.Substring(0, ndxCommon7 - 1); //"C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview"
                                                                                 // this is old compiler. For new stuff: https://stackoverflow.com/questions/31639602/using-c-sharp-6-features-with-codedomprovider-roslyn

                    using (var cdProvider = CodeDomProvider.CreateProvider("C#"))
                    {
                        var compParams = new CompilerParameters();
                        _lstRefDirs = new HashSet <string>
                        {
                            Path.GetDirectoryName(pathFileToExecute)// add the dir of the source file as a ref dir
                        };
                        void AddFileToCompileList(string fileToCompile)
                        {
                            if (lstFilesToCompile.Contains(fileToCompile))
                            {
                                return;
                            }
                            lstFilesToCompile.Add(fileToCompile);
                            var strCodeToExecute = File.ReadAllText(fileToCompile);

                            hashofCodeToExecute += strCodeToExecute.GetHashCode();
                            var srcLines = strCodeToExecute.Split("\r\n".ToArray());

                            foreach (var srcline in srcLines.Where(
                                         s => s.StartsWith(refPathPrefix) ||
                                         s.StartsWith(pragmaPrefix) ||
                                         s.StartsWith(includePathPrefix)))
                            {
                                if (srcline.StartsWith(pragmaPrefix)) ////Pragma: GenerateInMemory=false
                                {
                                    var splitPragma = srcline.Substring(pragmaPrefix.Length).Split(new[] { '=', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                                    switch (splitPragma[0].ToLower())
                                    {
                                    case "generateinmemory":
                                        GenerateInMemory = bool.Parse(splitPragma[1]);
                                        if (verbose)
                                        {
                                            _logger.LogMessage($"Pragma {nameof(GenerateInMemory)}  = {GenerateInMemory} {Path.GetFileName(fileToCompile)}");
                                        }
                                        break;

                                    case "usecsc":
                                        UseCSC = bool.Parse(splitPragma[1]);
                                        if (verbose)
                                        {
                                            _logger.LogMessage($"Pragma {nameof(UseCSC)}  = {UseCSC} {Path.GetFileName(fileToCompile)}");
                                        }
                                        break;

                                    case "verbose":
                                        verbose = bool.Parse(splitPragma[1]);
                                        break;

                                    case "showwarnings":
                                        showWarnings = true;
                                        if (verbose)
                                        {
                                            _logger.LogMessage($"Pragma {nameof(showWarnings)} = {showWarnings} {Path.GetFileName(fileToCompile)}");
                                        }
                                        break;

                                    default:
                                        throw new InvalidOperationException($"Unknown Pragma {srcline}");
                                    }
                                }
                                else if (srcline.StartsWith(refPathPrefix))
                                {
                                    var refAsm = srcline.Replace(refPathPrefix, string.Empty).Trim();
                                    if (refAsm.StartsWith("\"") && refAsm.EndsWith("\""))
                                    {
                                        refAsm = refAsm.Replace("\"", string.Empty);
                                    }
                                    if (refAsm.Contains(progfiles86))// C:\Program Files (x86)\
                                    {
                                        var pfiles = Environment.GetEnvironmentVariable("ProgramFiles(x86)");
                                        refAsm = refAsm.Replace(progfiles86, pfiles);
                                    }
                                    if (refAsm == $"%{nameof(PerfGraphVSIX)}%")
                                    {
                                        refAsm = this.GetType().Assembly.Location;
                                        var dir = System.IO.Path.GetDirectoryName(refAsm);
                                        if (!_lstRefDirs.Contains(dir))
                                        {
                                            _lstRefDirs.Add(dir);
                                        }
                                        compParams.ReferencedAssemblies.Add(refAsm);
                                        refAsm = typeof(ILogger).Assembly.Location;
                                    }
                                    else
                                    {
                                        if (refAsm.Contains(VSRootSubstitution))
                                        {
                                            refAsm = refAsm.Replace(VSRootSubstitution, vsRoot);
                                        }
                                        var dir = System.IO.Path.GetDirectoryName(refAsm);
                                        if (string.IsNullOrEmpty(dir))
                                        {
                                            var temp = Path.Combine(Path.GetDirectoryName(pathFileToExecute), refAsm);
                                            if (File.Exists(temp))
                                            {
                                                refAsm = temp;
                                            }
                                        }
                                        //                                _logger.LogMessage($"AddRef {refAsm}");
                                        if (!string.IsNullOrEmpty(refAsm))
                                        {
                                            if (!System.IO.File.Exists(refAsm))
                                            {
                                                throw new System.IO.FileNotFoundException($"Couldn't find {refAsm}");
                                            }
                                            else
                                            {
                                                if (!_lstRefDirs.Contains(dir))
                                                {
                                                    _lstRefDirs.Add(dir);
                                                }
                                            }
                                        }
                                    }
                                    compParams.ReferencedAssemblies.Add(refAsm);
                                }
                                else if (srcline.StartsWith(includePathPrefix))
                                {
                                    var include = srcline.Replace(includePathPrefix, string.Empty).Trim();
                                    if (include.StartsWith("\"") && include.EndsWith("\""))
                                    {
                                        include = include.Replace("\"", string.Empty);
                                    }
                                    include = Path.Combine(Path.GetDirectoryName(fileToCompile), include);
                                    //_logger.LogMessage($"Adding Include file {include}");
                                    AddFileToCompileList(include);
                                }
                            }
                        }
                        AddFileToCompileList(pathFileToExecute);
                        if (_priorCompiledAssembly != null && _hashOfPriorCodeToExecute == hashofCodeToExecute) // if we can use prior compile results
                        {
                            _logger.LogMessage($"No Compilation required: Using prior compiled assembly for {pathFileToExecute}");
                            asmCompiled = _priorCompiledAssembly;
                        }
                        else
                        {
                            if (!UseCSC)
                            {
                                //                        compParams.ReferencedAssemblies.Add(typeof(DependencyObject).Assembly.Location); // C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\WindowsBase\v4.0_4.0.0.0__31bf3856ad364e35\WindowsBase.dll  c:\Windows\Microsoft.NET\Framework\v4.0.30319\WPF  c:\Windows\Microsoft.NET\Framework64\v4.0.30319\WPF
                                compParams.ReferencedAssemblies.Add(typeof(PerfGraphToolWindowControl).Assembly.Location);
                                if (GenerateInMemory)
                                {
                                    compParams.GenerateInMemory = true; // in memory cannot be unloaded
                                }
                                var resCompile = cdProvider.CompileAssemblyFromFile(compParams, lstFilesToCompile.ToArray());
                                if (resCompile.Errors.HasErrors || resCompile.Errors.HasWarnings)
                                {
                                    var strb    = new StringBuilder();
                                    int nErrors = 0;
                                    foreach (var err in resCompile.Errors)
                                    {
                                        strb.AppendLine(err.ToString());
                                        _logger.LogMessage(err.ToString());
                                        nErrors++;
                                    }
                                    strb.AppendLine($"# errors = {nErrors}");
                                    throw new InvalidOperationException(strb.ToString());
                                }
                                asmCompiled = resCompile.CompiledAssembly;
                            }
                            else
                            {// C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\MSBuild\Current\bin\Roslyn\csc.exe
                                var roslynExe = Path.Combine(vsRoot, @"MSBuild\Current\Bin\Roslyn", (IsCSharp ? "csc.exe" : "vbc.exe"));
                                if (!File.Exists(roslynExe))
                                {
                                    throw new FileNotFoundException(roslynExe);
                                }
                                var sb = new StringBuilder();
                                // Csc /target:library -out:asm.exe -r:<filelist>
                                var outfile = Path.ChangeExtension(Path.GetTempFileName(), ".dll");
                                var refs    = string.Empty;
                                if (compParams.ReferencedAssemblies?.Count > 0)
                                {
                                    foreach (var refd in compParams.ReferencedAssemblies)
                                    {
                                        refs += $@"-r:""{refd}"" ";
                                    }
                                }
                                var srcFiles = string.Empty;
                                foreach (var srcfile in lstFilesToCompile)
                                {
                                    // to support spaces in file paths, enclose them in quotes
                                    srcFiles += $@"""{srcfile}"" ";
                                }
                                // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/reference-compiler-option
                                var args = $@"{srcFiles}/target:library /nologo /out:""{outfile}"" {refs}";
                                if (verbose)
                                {
                                    _logger.LogMessage($@"Compile line: ""{roslynExe}"" " + args);
                                }
                                using (var proc = VSHandler.CreateProcess(roslynExe, args, sb))
                                {
                                    proc.Start();
                                    proc.BeginOutputReadLine();
                                    proc.BeginErrorReadLine();
                                    proc.WaitForExit();
                                }
                                //                            _logger.LogMessage("{0}", sb.ToString());
                                if (!File.Exists(outfile) || sb.ToString().Contains(": error"))
                                {
                                    throw new InvalidOperationException(sb.ToString());
                                }
                                if (showWarnings && sb.ToString().Contains("warning"))
                                {
                                    _logger.LogMessage(sb.ToString());
                                }
                                asmCompiled = Assembly.LoadFrom(outfile);
                            }
                        }
                    }
                    _hashOfPriorCodeToExecute = hashofCodeToExecute;
                    _priorCompiledAssembly    = asmCompiled;
                    if (verbose)
                    {
                        _logger.LogMessage($"Looking for Static Main");
                    }
                    var didGetMain = false;
                    if (!_fDidAddAssemblyResolver)
                    {
                        _fDidAddAssemblyResolver = true;
                        AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolver;
                    }
                    foreach (var clas in asmCompiled.GetExportedTypes())
                    {
                        mainMethod = clas.GetMethod(DoMain);
                        if (mainMethod != null)
                        {
                            if (!mainMethod.IsStatic)
                            {
                                throw new InvalidOperationException("DoMain must be static");
                            }

                            didGetMain = true;
                            //                        _logger.LogMessage($"mainmethod rettype = {mainMethod.ReturnType.Name}");
                            break;
                        }
                    }
                    if (!didGetMain)
                    {
                        throw new InvalidOperationException($"Couldn't find static {DoMain} in {pathFileToExecute}");
                    }
                }
                catch (Exception)
                {
                    _hashOfPriorCodeToExecute = 0;
                    _priorCompiledAssembly    = null;
                    throw;
                }
            }