Ejemplo n.º 1
0
        public void ResourceWithAttrSettings()
        {
            string source  = @"
[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")]
[assembly: System.Reflection.AssemblyFileVersion(""5.6.7.8"")]
[assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")] 
[assembly: System.Reflection.AssemblyDescription(""A classic of magical realist literature"")]
[assembly: System.Reflection.AssemblyCompany(""MossBrain"")]
[assembly: System.Reflection.AssemblyProduct(""Sound Cannon"")]
[assembly: System.Reflection.AssemblyCopyright(""circle C"")]
[assembly: System.Reflection.AssemblyTrademark(""circle R"")]
[assembly: System.Reflection.AssemblyInformationalVersion(""1.2.3garbage"")]

public class Maine
{
    public static void Main()
    {
    }
}
";
            var    c1      = CreateCompilationWithMscorlib(source, assemblyName: "Win32VerAttrs", options: TestOptions.ReleaseExe);
            var    exeFile = Temp.CreateFile();

            using (FileStream output = exeFile.Open())
            {
                c1.Emit(output, win32Resources: c1.CreateDefaultWin32Resources(true, false, null, null));
            }

            c1 = null;
            string versionData;

            //Open as data
            IntPtr lib = IntPtr.Zero;

            try
            {
                lib = LoadLibraryEx(exeFile.Path, IntPtr.Zero, 0x00000002);
                Assert.True(lib != IntPtr.Zero, String.Format("LoadLibrary failed with HResult: {0:X}", +Marshal.GetLastWin32Error()));

                //the manifest and version primitives are tested elsewhere. This is to test that the default
                //values are passed to the primitives that assemble the resources.

                uint   size;
                IntPtr versionRsrc = Win32Res.GetResource(lib, "#1", "#16", out size);
                versionData = Win32Res.VersionResourceToXml(versionRsrc);
            }
            finally
            {
                if (lib != IntPtr.Zero)
                {
                    FreeLibrary(lib);
                }
            }

            string expected =
                @"<?xml version=""1.0"" encoding=""utf-16""?>
<VersionResource Size=""964"">
  <VS_FIXEDFILEINFO FileVersionMS=""00050006"" FileVersionLS=""00070008"" ProductVersionMS=""00000000"" ProductVersionLS=""00000000"" />
  <KeyValuePair Key=""Comments"" Value=""A classic of magical realist literature"" />
  <KeyValuePair Key=""CompanyName"" Value=""MossBrain"" />
  <KeyValuePair Key=""FileDescription"" Value=""One Hundred Years of Solitude"" />
  <KeyValuePair Key=""FileVersion"" Value=""5.6.7.8"" />
  <KeyValuePair Key=""InternalName"" Value=""Win32VerAttrs.exe"" />
  <KeyValuePair Key=""LegalCopyright"" Value=""circle C"" />
  <KeyValuePair Key=""LegalTrademarks"" Value=""circle R"" />
  <KeyValuePair Key=""OriginalFilename"" Value=""Win32VerAttrs.exe"" />
  <KeyValuePair Key=""ProductName"" Value=""Sound Cannon"" />
  <KeyValuePair Key=""ProductVersion"" Value=""1.2.3garbage"" />
  <KeyValuePair Key=""Assembly Version"" Value=""1.2.3.4"" />
</VersionResource>";

            Assert.Equal(expected, versionData);
        }
Ejemplo n.º 2
0
        public async Task DefaultUsings()
        {
            var rspFile = Temp.CreateFile();

            rspFile.WriteAllText(
                @"
/r:System
/r:System.Core
/r:Microsoft.CSharp
/u:System
/u:System.IO
/u:System.Collections.Generic
/u:System.Diagnostics
/u:System.Dynamic
/u:System.Linq
/u:System.Linq.Expressions
/u:System.Text
/u:System.Threading.Tasks
"
                );
            await Host.ResetAsync(
                new InteractiveHostOptions(
                    Host.OptionsOpt !.HostPath,
                    rspFile.Path,
                    CultureInfo.InvariantCulture,
                    Host.OptionsOpt !.Platform
                    )
                );

            await Execute(
                @"
dynamic d = new ExpandoObject();
"
                );
            await Execute(
                @"
Process p = new Process();
"
                );
            await Execute(
                @"
Expression<Func<int>> e = () => 1;
"
                );
            await Execute(
                @"
var squares = from x in new[] { 1, 2, 3 } select x * x;
"
                );
            await Execute(
                @"
var sb = new StringBuilder();
"
                );
            await Execute(
                @"
var list = new List<int>();
"
                );
            await Execute(
                @"
var stream = new MemoryStream();
await Task.Delay(10);
p = new Process();

Console.Write(""OK"")
"
                );

            var error = await ReadErrorOutputToEnd();

            var output = await ReadOutputToEnd();

            AssertEx.AssertEqualToleratingWhitespaceDifferences("", error);
            AssertEx.AssertEqualToleratingWhitespaceDifferences(
                $@"{string.Format(InteractiveHostResources.Loading_context_from_0, Path.GetFileName(rspFile.Path))} 
OK
",
                output
                );
        }
Ejemplo n.º 3
0
        public void ResourcesInCoff()
        {
            //this is to test that resources coming from a COFF can be added to a binary.
            string source = @"
class C
{
}
";
            var    c1     = CreateCompilationWithMscorlib(source, assemblyName: "Win32WithCoff", options: TestOptions.ReleaseDll);
            var    exe    = Temp.CreateFile();

            using (FileStream output = exe.Open())
            {
                var memStream = new MemoryStream(TestResources.SymbolsTests.General.nativeCOFFResources);
                c1.Emit(output, win32Resources: memStream);
            }

            c1 = null;

            //Open as data
            IntPtr lib = IntPtr.Zero;
            string versionData;

            try
            {
                lib = LoadLibraryEx(exe.Path, IntPtr.Zero, 0x00000002);
                if (lib == IntPtr.Zero)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                //the manifest and version primitives are tested elsewhere. This is to test that the resources
                //we expect are present. Also need to check that the actual contents of at least one of the resources
                //is good. That tests our processing of the relocations.

                uint   size;
                IntPtr versionRsrc = Win32Res.GetResource(lib, "#1", "#16", out size);
                versionData = Win32Res.VersionResourceToXml(versionRsrc);

                uint   stringTableSize;
                IntPtr stringTable = Win32Res.GetResource(lib, "#1", "#6", out stringTableSize);
                Assert.NotNull(stringTable);

                uint   elevenSize;
                IntPtr elevenRsrc = Win32Res.GetResource(lib, "#1", "#11", out elevenSize);
                Assert.NotNull(elevenRsrc);

                uint   wevtSize;
                IntPtr wevtRsrc = Win32Res.GetResource(lib, "#1", "WEVT_TEMPLATE", out wevtSize);
                Assert.NotNull(wevtRsrc);
            }
            finally
            {
                if (lib != IntPtr.Zero)
                {
                    FreeLibrary(lib);
                }
            }

            string expected =
                @"<?xml version=""1.0"" encoding=""utf-16""?>
<VersionResource Size=""1104"">
  <VS_FIXEDFILEINFO FileVersionMS=""000b0000"" FileVersionLS=""eacc0000"" ProductVersionMS=""000b0000"" ProductVersionLS=""eacc0000"" />
  <KeyValuePair Key=""CompanyName"" Value=""Microsoft Corporation"" />
  <KeyValuePair Key=""FileDescription"" Value=""Team Foundation Server Object Model"" />
  <KeyValuePair Key=""FileVersion"" Value=""11.0.60108.0 built by: TOOLSET_ROSLYN(GNAMBOO-DEV-GNAMBOO)"" />
  <KeyValuePair Key=""InternalName"" Value=""Microsoft.TeamFoundation.Framework.Server.dll"" />
  <KeyValuePair Key=""LegalCopyright"" Value=""© Microsoft Corporation. All rights reserved."" />
  <KeyValuePair Key=""OriginalFilename"" Value=""Microsoft.TeamFoundation.Framework.Server.dll"" />
  <KeyValuePair Key=""ProductName"" Value=""Microsoft® Visual Studio® 2012"" />
  <KeyValuePair Key=""ProductVersion"" Value=""11.0.60108.0"" />
</VersionResource>";

            Assert.Equal(expected, versionData);

            //look at the same data through the FileVersion API.
            //If the codepage and resource language information is not
            //written correctly into the internal resource directory of
            //the PE, then GetVersionInfo will fail to find the FileVersionInfo.
            //Once upon a time in Roslyn, the codepage and lang info was not written correctly.
            var fileVer = FileVersionInfo.GetVersionInfo(exe.Path);

            Assert.Equal("Microsoft Corporation", fileVer.CompanyName);
        }
Ejemplo n.º 4
0
        public void DefaultVersionResource()
        {
            string source = @"
public class Maine
{
    public static void Main()
    {
    }
}
";
            var    c1     = CreateCompilationWithMscorlib(source, assemblyName: "Win32VerNoAttrs", options: TestOptions.ReleaseExe);
            var    exe    = Temp.CreateFile();

            using (FileStream output = exe.Open())
            {
                c1.Emit(output, win32Resources: c1.CreateDefaultWin32Resources(true, false, null, null));
            }

            c1 = null;

            //Open as data
            IntPtr lib = IntPtr.Zero;
            string versionData;
            string mftData;

            try
            {
                lib = LoadLibraryEx(exe.Path, IntPtr.Zero, 0x00000002);
                if (lib == IntPtr.Zero)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                //the manifest and version primitives are tested elsewhere. This is to test that the default
                //values are passed to the primitives that assemble the resources.

                uint   size;
                IntPtr versionRsrc = Win32Res.GetResource(lib, "#1", "#16", out size);
                versionData = Win32Res.VersionResourceToXml(versionRsrc);

                uint   mftSize;
                IntPtr mftRsrc = Win32Res.GetResource(lib, "#1", "#24", out mftSize);
                mftData = Win32Res.ManifestResourceToXml(mftRsrc, mftSize);
            }
            finally
            {
                if (lib != IntPtr.Zero)
                {
                    FreeLibrary(lib);
                }
            }

            string expected =
                @"<?xml version=""1.0"" encoding=""utf-16""?>
<VersionResource Size=""612"">
  <VS_FIXEDFILEINFO FileVersionMS=""00000000"" FileVersionLS=""00000000"" ProductVersionMS=""00000000"" ProductVersionLS=""00000000"" />
  <KeyValuePair Key=""FileDescription"" Value="" "" />
  <KeyValuePair Key=""FileVersion"" Value=""0.0.0.0"" />
  <KeyValuePair Key=""InternalName"" Value=""Win32VerNoAttrs.exe"" />
  <KeyValuePair Key=""LegalCopyright"" Value="" "" />
  <KeyValuePair Key=""OriginalFilename"" Value=""Win32VerNoAttrs.exe"" />
  <KeyValuePair Key=""ProductVersion"" Value=""0.0.0.0"" />
  <KeyValuePair Key=""Assembly Version"" Value=""0.0.0.0"" />
</VersionResource>";

            Assert.Equal(expected, versionData);

            expected = @"<?xml version=""1.0"" encoding=""utf-16""?>
<ManifestResource Size=""490"">
  <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>

<assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0"">
  <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/>
  <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2"">
    <security>
      <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3"">
        <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/>
      </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>]]></Contents>
</ManifestResource>";

            Assert.Equal(expected, mftData);

            //look at the same data through the FileVersion API.
            //If the codepage and resource language information is not
            //written correctly into the internal resource directory of
            //the PE, then GetVersionInfo will fail to find the FileVersionInfo.
            //Once upon a time in Roslyn, the codepage and lang info was not written correctly.
            var fileVer = FileVersionInfo.GetVersionInfo(exe.Path);

            Assert.Equal(" ", fileVer.LegalCopyright);
        }
Ejemplo n.º 5
0
        public void AllAssemblyLevelAttributesMustBeBound()
        {
            var snkPath = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey).Path;

            var signing = Parse(
                @"
using System.Reflection;

[assembly: AssemblyVersion(""1.2.3.4"")]
[assembly: AssemblyKeyFile(@"""
                + snkPath
                + @""")]
"
                );

            var ivtCompilation = CreateCompilation(
                assemblyName: "IVT",
                options: TestOptions.ReleaseDll.WithStrongNameProvider(
                    new DesktopStrongNameProvider()
                    ),
                source: new[]
            {
                Parse(
                    @"
using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo(""Lib, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]

namespace NamespaceContainingInternalsOnly
{
    internal static class Extensions
    {
        internal static void Goo(this int x) {}
    }
}
"
                    ),
                signing
            }
                );

            var libCompilation = CreateCompilation(
                assemblyName: "Lib",
                options: TestOptions.ReleaseDll.WithStrongNameProvider(
                    new DesktopStrongNameProvider()
                    ),
                references: new[] { ivtCompilation.ToMetadataReference() },
                source: new[]
            {
                Parse(
                    @"
using NamespaceContainingInternalsOnly;

public class C
{
    internal static void F(int x)
    {
        x.Goo();
    }
}
"
                    ),
                signing
            }
                );

            libCompilation.VerifyDiagnostics();
        }
        public void WhenGivenAValidSlnFileItReadsAndVerifiesContents()
        {
            var tmpFile = Temp.CreateFile();

            tmpFile.WriteAllText(SolutionWithAppAndLibProjects);

            SlnFile slnFile = SlnFile.Read(tmpFile.Path);

            Console.WriteLine(new
            {
                slnFile_FormatVersion              = slnFile.FormatVersion,
                slnFile_ProductDescription         = slnFile.ProductDescription,
                slnFile_VisualStudioVersion        = slnFile.VisualStudioVersion,
                slnFile_MinimumVisualStudioVersion = slnFile.MinimumVisualStudioVersion,
                slnFile_BaseDirectory              = slnFile.BaseDirectory,
                slnFile_FullPath = slnFile.FullPath,
                tmpFilePath      = tmpFile.Path
            }.ToString());

            slnFile.FormatVersion.Should().Be("12.00");
            slnFile.ProductDescription.Should().Be("Visual Studio 15");
            slnFile.VisualStudioVersion.Should().Be("15.0.26006.2");
            slnFile.MinimumVisualStudioVersion.Should().Be("10.0.40219.1");
            slnFile.BaseDirectory.Should().Be(Path.GetDirectoryName(tmpFile.Path));
            slnFile.FullPath.Should().Be(Path.GetFullPath(tmpFile.Path));

            slnFile.Projects.Count.Should().Be(2);
            var project = slnFile.Projects[0];

            project.Id.Should().Be("{7072A694-548F-4CAE-A58F-12D257D5F486}");
            project.TypeGuid.Should().Be("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}");
            project.Name.Should().Be("App");
            project.FilePath.Should().Be(Path.Combine("App", "App.csproj"));
            project = slnFile.Projects[1];
            project.Id.Should().Be("{21D9159F-60E6-4F65-BC6B-D01B71B15FFC}");
            project.TypeGuid.Should().Be("{13B669BE-BB05-4DDF-9536-439F39A36129}");
            project.Name.Should().Be("Lib");
            project.FilePath.Should().Be(Path.Combine("..", "Lib", "Lib.csproj"));

            slnFile.SolutionConfigurationsSection.Count.Should().Be(6);
            slnFile.SolutionConfigurationsSection
            .GetValue("Debug|Any CPU", string.Empty)
            .Should().Be("Debug|Any CPU");
            slnFile.SolutionConfigurationsSection
            .GetValue("Debug|x64", string.Empty)
            .Should().Be("Debug|x64");
            slnFile.SolutionConfigurationsSection
            .GetValue("Debug|x86", string.Empty)
            .Should().Be("Debug|x86");
            slnFile.SolutionConfigurationsSection
            .GetValue("Release|Any CPU", string.Empty)
            .Should().Be("Release|Any CPU");
            slnFile.SolutionConfigurationsSection
            .GetValue("Release|x64", string.Empty)
            .Should().Be("Release|x64");
            slnFile.SolutionConfigurationsSection
            .GetValue("Release|x86", string.Empty)
            .Should().Be("Release|x86");

            slnFile.ProjectConfigurationsSection.Count.Should().Be(2);
            var projectConfigSection = slnFile
                                       .ProjectConfigurationsSection
                                       .GetPropertySet("{7072A694-548F-4CAE-A58F-12D257D5F486}");

            projectConfigSection.Count.Should().Be(12);
            projectConfigSection
            .GetValue("Debug|Any CPU.ActiveCfg", string.Empty)
            .Should().Be("Debug|Any CPU");
            projectConfigSection
            .GetValue("Debug|Any CPU.Build.0", string.Empty)
            .Should().Be("Debug|Any CPU");
            projectConfigSection
            .GetValue("Debug|x64.ActiveCfg", string.Empty)
            .Should().Be("Debug|x64");
            projectConfigSection
            .GetValue("Debug|x64.Build.0", string.Empty)
            .Should().Be("Debug|x64");
            projectConfigSection
            .GetValue("Debug|x86.ActiveCfg", string.Empty)
            .Should().Be("Debug|x86");
            projectConfigSection
            .GetValue("Debug|x86.Build.0", string.Empty)
            .Should().Be("Debug|x86");
            projectConfigSection
            .GetValue("Release|Any CPU.ActiveCfg", string.Empty)
            .Should().Be("Release|Any CPU");
            projectConfigSection
            .GetValue("Release|Any CPU.Build.0", string.Empty)
            .Should().Be("Release|Any CPU");
            projectConfigSection
            .GetValue("Release|x64.ActiveCfg", string.Empty)
            .Should().Be("Release|x64");
            projectConfigSection
            .GetValue("Release|x64.Build.0", string.Empty)
            .Should().Be("Release|x64");
            projectConfigSection
            .GetValue("Release|x86.ActiveCfg", string.Empty)
            .Should().Be("Release|x86");
            projectConfigSection
            .GetValue("Release|x86.Build.0", string.Empty)
            .Should().Be("Release|x86");
            projectConfigSection = slnFile
                                   .ProjectConfigurationsSection
                                   .GetPropertySet("{21D9159F-60E6-4F65-BC6B-D01B71B15FFC}");
            projectConfigSection.Count.Should().Be(12);
            projectConfigSection
            .GetValue("Debug|Any CPU.ActiveCfg", string.Empty)
            .Should().Be("Debug|Any CPU");
            projectConfigSection
            .GetValue("Debug|Any CPU.Build.0", string.Empty)
            .Should().Be("Debug|Any CPU");
            projectConfigSection
            .GetValue("Debug|x64.ActiveCfg", string.Empty)
            .Should().Be("Debug|x64");
            projectConfigSection
            .GetValue("Debug|x64.Build.0", string.Empty)
            .Should().Be("Debug|x64");
            projectConfigSection
            .GetValue("Debug|x86.ActiveCfg", string.Empty)
            .Should().Be("Debug|x86");
            projectConfigSection
            .GetValue("Debug|x86.Build.0", string.Empty)
            .Should().Be("Debug|x86");
            projectConfigSection
            .GetValue("Release|Any CPU.ActiveCfg", string.Empty)
            .Should().Be("Release|Any CPU");
            projectConfigSection
            .GetValue("Release|Any CPU.Build.0", string.Empty)
            .Should().Be("Release|Any CPU");
            projectConfigSection
            .GetValue("Release|x64.ActiveCfg", string.Empty)
            .Should().Be("Release|x64");
            projectConfigSection
            .GetValue("Release|x64.Build.0", string.Empty)
            .Should().Be("Release|x64");
            projectConfigSection
            .GetValue("Release|x86.ActiveCfg", string.Empty)
            .Should().Be("Release|x86");
            projectConfigSection
            .GetValue("Release|x86.Build.0", string.Empty)
            .Should().Be("Release|x86");

            slnFile.Sections.Count.Should().Be(3);
            var solutionPropertiesSection = slnFile.Sections.GetSection("SolutionProperties");

            solutionPropertiesSection.Properties.Count.Should().Be(1);
            solutionPropertiesSection.Properties
            .GetValue("HideSolutionNode", string.Empty)
            .Should().Be("FALSE");
        }
Ejemplo n.º 7
0
        public void SimpleCompilerDiagnostics()
        {
            var source       = @"
public class C
{
    private int x;
}";
            var sourceFile   = Temp.CreateFile().WriteAllText(source).Path;
            var errorLogDir  = Temp.CreateDirectory();
            var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt");

            var cmd = new MockCSharpCompiler(null, _baseDirectory, new[] {
                "/nologo", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}"
            });
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);

            var exitCode            = cmd.Run(outWriter);
            var actualConsoleOutput = outWriter.ToString().Trim();

            Assert.Contains("CS0169", actualConsoleOutput);
            Assert.Contains("CS5001", actualConsoleOutput);
            Assert.NotEqual(0, exitCode);

            var actualOutput = File.ReadAllText(errorLogFile).Trim();

            var expectedHeader = GetExpectedErrorLogHeader(actualOutput, cmd);
            var expectedIssues = string.Format(@"
      ""results"": [
        {{
          ""ruleId"": ""CS0169"",
          ""level"": ""warning"",
          ""message"": ""The field 'C.x' is never used"",
          ""locations"": [
            {{
              ""resultFile"": {{
                ""uri"": ""{0}"",
                ""region"": {{
                  ""startLine"": 4,
                  ""startColumn"": 17,
                  ""endLine"": 4,
                  ""endColumn"": 18
                }}
              }}
            }}
          ],
          ""properties"": {{
            ""warningLevel"": 3
          }}
        }},
        {{
          ""ruleId"": ""CS5001"",
          ""level"": ""error"",
          ""message"": ""Program does not contain a static 'Main' method suitable for an entry point""
        }}
      ],
      ""rules"": {{
        ""CS0169"": {{
          ""id"": ""CS0169"",
          ""shortDescription"": ""Field is never used"",
          ""defaultLevel"": ""warning"",
          ""properties"": {{
            ""category"": ""Compiler"",
            ""isEnabledByDefault"": true,
            ""tags"": [
              ""Compiler"",
              ""Telemetry""
            ]
          }}
        }},
        ""CS5001"": {{
          ""id"": ""CS5001"",
          ""defaultLevel"": ""error"",
          ""properties"": {{
            ""category"": ""Compiler"",
            ""isEnabledByDefault"": true,
            ""tags"": [
              ""Compiler"",
              ""Telemetry"",
              ""NotConfigurable""
            ]
          }}
        }}
      }}
    }}
  ]
}}", AnalyzerForErrorLogTest.GetUriForPath(sourceFile));

            var expectedText = expectedHeader + expectedIssues;

            Assert.Equal(expectedText, actualOutput);

            CleanupAllGeneratedFiles(sourceFile);
            CleanupAllGeneratedFiles(errorLogFile);
        }
Ejemplo n.º 8
0
        public void ReferenceSearchPaths1()
        {
            var main = Temp.CreateFile(extension: ".csx")
                       .WriteAllText(
                @"
#r ""1.dll""
#r ""2.dll""
#r ""3.dll""
Print(new C1());
Print(new C2());
Print(new C3());
Print(new C4());
"
                );

            var dir1 = Temp.CreateDirectory();

            dir1.CreateFile("1.dll")
            .WriteAllBytes(
                CreateCSharpCompilationWithCorlib("public class C1 {}", "1").EmitToArray()
                );

            var dir2 = Temp.CreateDirectory();

            dir2.CreateFile("2.dll")
            .WriteAllBytes(
                CreateCSharpCompilationWithCorlib("public class C2 {}", "2").EmitToArray()
                );

            var dir3 = Temp.CreateDirectory();

            dir3.CreateFile("3.dll")
            .WriteAllBytes(
                CreateCSharpCompilationWithCorlib("public class C3 {}", "3").EmitToArray()
                );

            var dir4 = Temp.CreateDirectory();

            dir4.CreateFile("4.dll")
            .WriteAllBytes(
                CreateCSharpCompilationWithCorlib("public class C4 {}", "4").EmitToArray()
                );

            var runner = CreateRunner(
                new[]
            {
                "/r:4.dll",
                $"/lib:{dir1.Path}",
                $"/libpath:{dir2.Path}",
                $"/libpaths:{dir3.Path};{dir4.Path}",
                main.Path
            }
                );

            runner.RunInteractive();

            AssertEx.AssertEqualToleratingWhitespaceDifferences(
                @"
C1 { }
C2 { }
C3 { }
C4 { }
",
                runner.Console.Out.ToString()
                );
        }
Ejemplo n.º 9
0
        public void BadImageFormat()
        {
            var invalidModuleName = Temp.CreateFile().WriteAllBytes(TestResources.MetadataTests.Invalid.InvalidModuleName);

            Assert.Throws <BadImageFormatException>(() => AssemblyMetadata.CreateFromFile(invalidModuleName.Path));
        }
Ejemplo n.º 10
0
        public void SimpleCompilerDiagnostics_Suppressed()
        {
            var source       = @"
public class C
{
#pragma warning disable CS0169
    private int x;
#pragma warning restore CS0169
}";
            var sourceFile   = Temp.CreateFile().WriteAllText(source).Path;
            var errorLogDir  = Temp.CreateDirectory();
            var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt");

            var cmd = new MockCSharpCompiler(null, _baseDirectory, new[] {
                "/nologo", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}"
            });
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);

            var exitCode            = cmd.Run(outWriter);
            var actualConsoleOutput = outWriter.ToString().Trim();

            // Suppressed diagnostics are only report in the error log, not the console output.
            Assert.DoesNotContain("CS0169", actualConsoleOutput);
            Assert.Contains("CS5001", actualConsoleOutput);
            Assert.NotEqual(0, exitCode);

            var actualOutput = File.ReadAllText(errorLogFile).Trim();

            var expectedHeader = GetExpectedErrorLogHeader(actualOutput, cmd);
            var expectedIssues = string.Format(@"
      ""issues"": [
        {{
          ""ruleId"": ""CS0169"",
          ""locations"": [
            {{
              ""analysisTarget"": [
                {{
                  ""uri"": ""{0}"",
                  ""region"": {{
                    ""startLine"": 5,
                    ""startColumn"": 17,
                    ""endLine"": 5,
                    ""endColumn"": 18
                  }}
                }}
              ]
            }}
          ],
          ""fullMessage"": ""The field 'C.x' is never used"",
          ""properties"": {{
            ""severity"": ""Warning"",
            ""warningLevel"": ""3"",
            ""defaultSeverity"": ""Warning"",
            ""title"": ""Field is never used"",
            ""category"": ""Compiler"",
            ""isEnabledByDefault"": ""True"",
            ""isSuppressedInSource"": ""True"",
            ""customTags"": ""Compiler;Telemetry""
          }}
        }},
        {{
          ""ruleId"": ""CS5001"",
          ""locations"": [
          ],
          ""fullMessage"": ""Program does not contain a static 'Main' method suitable for an entry point"",
          ""properties"": {{
            ""severity"": ""Error"",
            ""defaultSeverity"": ""Error"",
            ""category"": ""Compiler"",
            ""isEnabledByDefault"": ""True"",
            ""isSuppressedInSource"": ""False"",
            ""customTags"": ""Compiler;Telemetry;NotConfigurable""
          }}
        }}
      ]
    }}
  ]
}}", AnalyzerForErrorLogTest.GetEscapedUriForPath(sourceFile));

            var expectedText = expectedHeader + expectedIssues;

            Assert.Equal(expectedText, actualOutput);

            CleanupAllGeneratedFiles(sourceFile);
            CleanupAllGeneratedFiles(errorLogFile);
        }
Ejemplo n.º 11
0
        public void XmlDocumentFileCsc()
        {
            var sourcePath =
                Temp.CreateFile()
                .WriteAllText(
                    @"
/// <summary>
/// A subtype of <see cref=""object""/>.
/// </summary>
public class C { }"
                    ).Path;
            var xml         = Temp.CreateFile();
            var touchedDir  = Temp.CreateDirectory();
            var touchedBase = Path.Combine(touchedDir.Path, "touched");

            var cmd = CreateCSharpCompiler(
                new[]
            {
                "/nologo",
                "/target:library",
                "/doc:" + xml.Path,
                "/touchedfiles:" + touchedDir.Path + "\\touched",
                sourcePath
            }
                );

            // Build touched files
            List <string> expectedReads;
            List <string> expectedWrites;

            BuildTouchedFiles(
                cmd,
                Path.ChangeExtension(sourcePath, "dll"),
                out expectedReads,
                out expectedWrites
                );
            expectedWrites.Add(xml.Path);

            var writer   = new StringWriter(CultureInfo.InvariantCulture);
            var exitCode = cmd.Run(writer);

            Assert.Equal(string.Empty, writer.ToString().Trim());
            Assert.Equal(0, exitCode);
            Assert.Equal(
                string.Format(
                    @"
<?xml version=""1.0""?>
<doc>
    <assembly>
        <name>{0}</name>
    </assembly>
    <members>
        <member name=""T:C"">
            <summary>
            A subtype of <see cref=""T:System.Object""/>.
            </summary>
        </member>
    </members>
</doc>",
                    Path.GetFileNameWithoutExtension(sourcePath)
                    )
                .Trim(),
                xml.ReadAllText().Trim()
                );

            AssertTouchedFilesEqual(expectedReads, expectedWrites, touchedBase);

            CleanupAllGeneratedFiles(sourcePath);
        }