Given a list of assemblyFiles, determine the closure of all assemblyFiles that depend on those assemblyFiles including second and nth-order dependencies too.
Inheritance: Microsoft.Build.Tasks.TaskExtension
        private static void ResolveSDKFromRefereneAssemblyLocation(string referenceName, string expectedPath)
        {
            // Create the engine.
            MockEngine engine = new MockEngine();
            TaskItem taskItem = new TaskItem(referenceName);
            taskItem.SetMetadata("SDKName", "FakeSDK, Version=1.0");

            TaskItem resolvedSDK = new TaskItem(@"C:\FakeSDK");
            resolvedSDK.SetMetadata("SDKName", "FakeSDK, Version=1.0");
            resolvedSDK.SetMetadata("TargetedSDKConfiguration", "Debug");
            resolvedSDK.SetMetadata("TargetedSDKArchitecture", "X86");

            TaskItem[] assemblies = new TaskItem[] { taskItem };

            // Now, pass feed resolved primary references into ResolveAssemblyReference.
            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.BuildEngine = engine;
            t.Assemblies = assemblies;
            t.ResolvedSDKReferences = new ITaskItem[] { resolvedSDK };
            t.SearchPaths = new String[] { @"C:\SomeOtherPlace" };
            bool succeeded = Execute(t);

            Assert.True(succeeded);
            Assert.Equal(1, t.ResolvedFiles.Length);
            Assert.Equal(0, engine.Errors);
            Assert.Equal(0, engine.Warnings);
            Assert.True(t.ResolvedFiles[0].ItemSpec.Equals(expectedPath, StringComparison.OrdinalIgnoreCase));
        }
        public void IgnoreVersionBasic()
        {
            MockEngine e = new MockEngine();

            TaskItem item = new TaskItem("DependsOn9, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089");

            ITaskItem[] items = new ITaskItem[]
            {
                item
            };

            string redistString = "<FileList Redist='Microsoft-Windows-CLRCoreComp-Random' >" +
                                  "<File AssemblyName='DependsOn9' Version='9.0.0.0' PublicKeyToken='b17a5c561934e089' Culture='neutral' ProcessorArchitecture='MSIL' FileVersion='4.0.0.0' InGAC='true' />" +
                                  "</FileList >";

            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.IgnoreVersionForFrameworkReferences = true;
            ExecuteRAROnItemsAndRedist(t, e, items, redistString, true);


            Assert.Equal(0, e.Warnings); // "No warnings expected in this scenario."
            Assert.Equal(0, e.Errors); // "No errors expected in this scenario."
            Assert.Equal(1, t.ResolvedFiles.Length);
            Assert.True(ContainsItem(t.ResolvedFiles, @"c:\MyComponents\misc\DependsOn9.dll")); // "Expected to find assembly, but didn't."

            // Do the resolution without the metadata, expect it to not work since we should not be able to find Dependson9 version 10.0.0.0
            e = new MockEngine();

            item = new TaskItem("DependsOn9, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089");

            items = new ITaskItem[]
            {
                item
            };

            redistString = "<FileList Redist='Microsoft-Windows-CLRCoreComp-Random' >" +
                           "<File AssemblyName='DependsOn9' Version='9.0.0.0' PublicKeyToken='b17a5c561934e089' Culture='neutral' ProcessorArchitecture='MSIL' FileVersion='4.0.0.0' InGAC='true' />" +
                           "</FileList >";

            t = new ResolveAssemblyReference();

            ExecuteRAROnItemsAndRedist(t, e, items, redistString, true);

            Assert.Equal(1, e.Warnings); // "Expected one warning in this scenario."
            e.AssertLogContains("MSB3257");
            e.AssertLogContains("DependsOn9");
            Assert.Equal(0, t.ResolvedFiles.Length);
        }
示例#3
0
        public void Exists()
        {
            // This WriteLine is a hack.  On a slow machine, the Tasks unittest fails because remoting
            // times out the object used for remoting console writes.  Adding a write in the middle of
            // keeps remoting from timing out the object.
            Console.WriteLine("Performing VersioningAndUnification.Prerequisite.StronglyNamedDependency.Exists() test");

            // Create the engine.
            MockEngine engine = new MockEngine();

            ITaskItem[] assemblyNames = new TaskItem[]
            {
                new TaskItem("DependsOnEverettSystem, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=feedbeadbadcadbe")
            };

            // Now, pass feed resolved primary references into ResolveAssemblyReference.
            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.BuildEngine = engine;
            t.Assemblies = assemblyNames;
            t.SearchPaths = DefaultPaths;

            bool succeeded = Execute(t);

            Assert.True(succeeded);
            Assert.Equal(1, t.ResolvedDependencyFiles.Length);
            Assert.Equal(0, engine.Errors);
            Assert.Equal(0, engine.Warnings);
            AssertNoCase
                (
                    "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=" + AssemblyRef.EcmaPublicKey, t.ResolvedDependencyFiles[0].GetMetadata("FusionName")
                );

            engine.AssertLogContains
                (
                    String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByFrameworkRetarget"), "1.0.5000.0", @"C:\MyApp\v1.0\DependsOnEverettSystem.dll")
                );

            engine.AssertLogContains
                (
                    String.Format(AssemblyResources.GetString("ResolveAssemblyReference.NotCopyLocalBecausePrerequisite"))
                );

            AssertNoCase("false", t.ResolvedDependencyFiles[0].GetMetadata("CopyLocal"));
        }
示例#4
0
        public void Exists()
        {
            // This WriteLine is a hack.  On a slow machine, the Tasks unittest fails because remoting
            // times out the object used for remoting console writes.  Adding a write in the middle of
            // keeps remoting from timing out the object.
            Console.WriteLine("Performing VersioningAndUnification.Prerequisite.SpecificVersionPrimary.Exists() test");

            // Create the engine.
            MockEngine engine = new MockEngine();

            ITaskItem[] assemblyNames = new TaskItem[]
            {
                new TaskItem("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
            };
            assemblyNames[0].SetMetadata("SpecificVersion", "true");

            // Construct the app.config.
            string appConfigFile = WriteAppConfig
                (
                    "        <dependentAssembly>\n" +
                    "            <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
                    "            <bindingRedirect oldVersion='1.0.0.0' newVersion='2.0.0.0' />\n" +
                    "        </dependentAssembly>\n"
                );

            // Now, pass feed resolved primary references into ResolveAssemblyReference.
            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.BuildEngine = engine;
            t.Assemblies = assemblyNames;
            t.SearchPaths = DefaultPaths;
            t.AppConfigFile = appConfigFile;

            bool succeeded = Execute(t);

            Assert.True(succeeded);
            Assert.Equal(1, t.ResolvedFiles.Length);
            AssertNoCase("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, ProcessorArchitecture=MSIL", t.ResolvedFiles[0].GetMetadata("FusionName"));
            AssertNoCase(@"{Registry:Software\Microsoft\.NetFramework,v2.0,AssemblyFoldersEx}", t.ResolvedFiles[0].GetMetadata("ResolvedFrom"));

            // Cleanup.
            File.Delete(appConfigFile);
        }
        public void TargetCurrentTargetFramework()
        {
            MockEngine e = new MockEngine();

            ITaskItem[] items = new ITaskItem[]
            {
                new TaskItem("DependsOnOnlyv4Assemblies")
            };

            string redistString = "<FileList Redist='Microsoft-Windows-CLRCoreComp-Random' >" +
                                  "<File AssemblyName='System' Version='4.0.0.0' PublicKeyToken='b77a5c561934e089' Culture='neutral' ProcessorArchitecture='MSIL' FileVersion='4.0.0.0' InGAC='true' />" +
                                  "</FileList >";

            ResolveAssemblyReference t = new ResolveAssemblyReference();
            ExecuteRAROnItemsAndRedist(t, e, items, redistString, true);

            Assert.Equal(0, e.Warnings); // "No warnings expected in this scenario."
            Assert.Equal(0, e.Errors); // "No errors expected in this scenario."
            Assert.Equal(1, t.ResolvedFiles.Length);
            Assert.True(ContainsItem(t.ResolvedFiles, @"c:\MyComponents\misc\DependsOnOnlyv4Assemblies.dll")); // "Expected to find assembly, but didn't."
        }
        public void Exists()
        {
            // Create the engine.
            MockEngine engine = new MockEngine();

            ITaskItem[] assemblyNames = new TaskItem[]
            {
                new TaskItem("DependsOnUnified, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
            };

            // Construct the app.config.
            string appConfigFile = WriteAppConfig
                (
                    "        <dependentAssembly>\n" +
                    "            <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
                    "            <bindingRedirect oldVersion='1.0.0.0' newVersion='2.0.0.0' />\n" +
                    "        </dependentAssembly>\n"
                );

            // Now, pass feed resolved primary references into ResolveAssemblyReference.
            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.BuildEngine = engine;
            t.Assemblies = assemblyNames;
            t.SearchPaths = DefaultPaths;
            t.AppConfigFile = appConfigFile;

            bool succeeded = Execute(t);

            Assert.True(succeeded);
            Assert.Equal(1, t.ResolvedDependencyFiles.Length);
            AssertNoCase("UnifyMe, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", t.ResolvedDependencyFiles[0].GetMetadata("FusionName"));
            engine.AssertLogContains
                (
                    String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAppConfig"), "1.0.0.0", appConfigFile, @"C:\MyApp\v1.0\DependsOnUnified.dll")
                );

            // Cleanup.
            File.Delete(appConfigFile);
        }
        public void Exists()
        {
            // This WriteLine is a hack.  On a slow machine, the Tasks unittest fails because remoting
            // times out the object used for remoting console writes.  Adding a write in the middle of
            // keeps remoting from timing out the object.
            Console.WriteLine("Performing VersioningAndUnification.AutoUnify.StronglyNamedDependency.Exists() test");

            // Create the engine.
            MockEngine engine = new MockEngine();

            ITaskItem[] assemblyNames = new TaskItem[]
            {
                new TaskItem("DependsOnUnified, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"),
                new TaskItem("DependsOnUnified, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
            };

            // Now, pass feed resolved primary references into ResolveAssemblyReference.
            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.BuildEngine = engine;
            t.Assemblies = assemblyNames;
            t.SearchPaths = DefaultPaths;
            t.AutoUnify = true;

            bool succeeded = Execute(t);

            Assert.True(succeeded);
            AssertNoCase("UnifyMe, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", t.ResolvedDependencyFiles[0].GetMetadata("FusionName"));
            AssertNoCase(@"C:\MyComponents\v2.0\UnifyMe.dll", t.ResolvedDependencyFiles[0].ItemSpec);

            engine.AssertLogContains
                (
                    String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnifiedDependency"), "UniFYme, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
                );

            engine.AssertLogContains
                (
                    String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAutoUnify"), "1.0.0.0", @"C:\MyApp\v1.0\DependsOnUnified.dll")
                );
        }
        public void SameVersionSameFrameworkDirect()
        {
            MockEngine e = new MockEngine();

            ITaskItem[] items = new ITaskItem[]
            {
                new TaskItem("DependsOnFoo4Framework"),
            };

            ResolveAssemblyReference t = new ResolveAssemblyReference();
            t.BuildEngine = e;
            t.Assemblies = items;
            t.TargetFrameworkMoniker = "Foo, Version=4.0";
            t.TargetFrameworkMonikerDisplayName = "Foo";
            t.SearchPaths = new string[] { @"c:\Frameworks\" };
            Execute(t);

            Assert.Equal(0, e.Warnings); // "No warnings expected in this scenario."
            Assert.Equal(0, e.Errors); // "No errors expected in this scenario."
            Assert.Equal(1, t.ResolvedFiles.Length);
            Assert.True(ContainsItem(t.ResolvedFiles, @"c:\Frameworks\DependsOnFoo4Framework.dll")); // "Expected to find assembly, but didn't."
        }
        public void RemapAssemblyBasic()
        {
            MockEngine e = new MockEngine();

            ITaskItem[] items = new ITaskItem[]
            {
                new TaskItem("ReferenceVersion9"),
                new TaskItem("DependsOnOnlyv4Assemblies"),
                new TaskItem("AnotherOne")
            };

            string redistString = "<FileList Redist='Microsoft-Windows-CLRCoreComp-Random' >" +
                                  "<File AssemblyName='mscorlib' Version='4.0.0.0' PublicKeyToken='b77a5c561934e089' Culture='neutral' ProcessorArchitecture='MSIL' FileVersion='4.0.0.0' InGAC='true' />" +
                                  "<Remap>" +
                                  "<From AssemblyName='mscorlib' Version='9.0.0.0' PublicKeyToken='b77a5c561934e089' Culture='neutral' ProcessorArchitecture='MSIL' FileVersion='4.0.0.0' InGAC='true'>" +
                                  "   <To AssemblyName='mscorlib' Version='4.0.0.0' PublicKeyToken='b77a5c561934e089' Culture='neutral' ProcessorArchitecture='MSIL' FileVersion='4.0.0.0' InGAC='true' />" +
                                  " </From>" +
                                  "<From AssemblyName='DependsOnOnlyv4Assemblies'>" +
                                  "   <To AssemblyName='ReferenceVersion9' Version='9.0.0.0' PublicKeyToken='b17a5c561934e089' Culture='neutral' ProcessorArchitecture='MSIL' />" +
                                  " </From>" +
                                  "<From AssemblyName='AnotherOne'>" +
                                  "   <To AssemblyName='ReferenceVersion9' Version='9.0.0.0' PublicKeyToken='b17a5c561934e089' Culture='neutral' ProcessorArchitecture='MSIL' />" +
                                  " </From>" +
                                  "</Remap>" +
                                  "</FileList >";

            ResolveAssemblyReference t = new ResolveAssemblyReference();
            ExecuteRAROnItemsAndRedist(t, e, items, redistString, false);

            Assert.Equal(0, e.Warnings); // "Expected NO warning in this scenario."
            e.AssertLogContainsMessageFromResource(resourceDelegate, "ResolveAssemblyReference.RemappedReference", "DependsOnOnlyv4Assemblies", "ReferenceVersion9, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089");
            e.AssertLogContainsMessageFromResource(resourceDelegate, "ResolveAssemblyReference.RemappedReference", "AnotherOne", "ReferenceVersion9, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089");

            Assert.Equal(1, t.ResolvedFiles.Length);

            Assert.True(t.ResolvedFiles[0].GetMetadata("OriginalItemSpec").Equals("AnotherOne", StringComparison.OrdinalIgnoreCase));

            Assert.True(t.ResolvedFiles[0].ItemSpec.Equals(@"c:\MyComponents\misc\ReferenceVersion9.dll", StringComparison.OrdinalIgnoreCase));
        }
        public void Exists()
        {
            // Create the engine.
            MockEngine engine = new MockEngine();

            ITaskItem[] assemblyNames = new TaskItem[]
            {
                new TaskItem("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
            };
            assemblyNames[0].SetMetadata("SpecificVersion", "false");


            // Construct the app.config.
            string appConfigFile = WriteAppConfig
                (
                    "        <dependentAssembly>\n" +
                    "            <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
                    "            <bindingRedirect oldVersion='1.0.0.0' newVersion='2.0.0.0' />\n" +
                    "        </dependentAssembly>\n"
                );

            // Now, pass feed resolved primary references into ResolveAssemblyReference.
            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.BuildEngine = engine;
            t.Assemblies = assemblyNames;
            t.SearchPaths = DefaultPaths;
            t.AppConfigFile = appConfigFile;

            bool succeeded = Execute(t);

            Assert.True(succeeded);
            Assert.Equal(1, t.ResolvedFiles.Length);
            AssertNoCase("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, ProcessorArchitecture=MSIL", t.ResolvedFiles[0].GetMetadata("FusionName"));

            // Cleanup.
            File.Delete(appConfigFile);
        }
        public void SDkNameNotInResolvedSDKListButOnSearchPath()
        {
            // Create the engine.
            MockEngine engine = new MockEngine();
            TaskItem taskItem = new TaskItem(@"SDKWinMD");
            taskItem.SetMetadata("SDKName", "NotInstalled, Version=1.0");

            TaskItem[] assemblies = new TaskItem[] { taskItem };

            // Now, pass feed resolved primary references into ResolveAssemblyReference.
            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.BuildEngine = engine;
            t.Assemblies = assemblies;
            t.SearchPaths = new String[] { @"C:\FakeSDK\References" };
            bool succeeded = Execute(t);

            Assert.True(succeeded);
            Assert.Equal(0, t.ResolvedFiles.Length);

            Assert.Equal(0, engine.Errors);
            Assert.Equal(1, engine.Warnings);
        }
        public void GarbageAppConfigAssemblyNameMissingPKTAndCulture()
        {
            // Create the engine.
            MockEngine engine = new MockEngine();

            ITaskItem[] assemblyNames = new TaskItem[]
            {
                new TaskItem("DependsOnUnified, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
            };

            // Construct the app.config.
            string appConfigFile = WriteAppConfig
                (
                    "        <dependentAssembly>\n" +
                    "            <assemblyIdentity name='GarbledOldVersion' />\n" +
                    "            <bindingRedirect oldVersion='Garbled' newVersion='2.0.0.0' />\n" +
                    "        </dependentAssembly>\n"
                );

            // Now, pass feed resolved primary references into ResolveAssemblyReference.
            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.BuildEngine = engine;
            t.Assemblies = assemblyNames;
            t.SearchPaths = DefaultPaths;
            t.AppConfigFile = appConfigFile;

            bool succeeded = Execute(t);
            Assert.False(succeeded);
            Assert.Equal(1, engine.Errors);

            // Cleanup.
            File.Delete(appConfigFile);
        }
示例#13
0
        public void ForwardRedistRoot()
        {
            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.BuildEngine = new MockEngine();

            t.Assemblies = new ITaskItem[]
            {
                new TaskItem("MyRedistRootAssembly"),
                new TaskItem("MyOtherAssembly"),
                new TaskItem("MyThirdAssembly")
            };

            t.SearchPaths = new string[]
            {
                @"c:\MyRedist"
            };

            string redistFile = FileUtilities.GetTemporaryFile();

            try
            {
                File.Delete(redistFile);
                File.WriteAllText
                    (
                        redistFile,
                        "<FileList Redist='Microsoft-Windows-CLRCoreComp' >" +
                        "<File IsRedistRoot='true' AssemblyName='MyRedistRootAssembly' Version='0.0.0.0' PublicKeyToken='null' Culture='Neutral' FileVersion='2.0.40824.0' InGAC='true'/>" +
                        "<File IsRedistRoot='false' AssemblyName='MyOtherAssembly' Version='0.0.0.0' PublicKeyToken='null' Culture='Neutral' FileVersion='2.0.40824.0' InGAC='true'/>" +
                        "<File AssemblyName='MyThirdAssembly' Version='0.0.0.0' PublicKeyToken='null' Culture='Neutral' FileVersion='2.0.40824.0' InGAC='true'/>" +
                        "</FileList >"
                    );

                t.InstalledAssemblyTables = new TaskItem[] { new TaskItem(redistFile) };

                Execute(t);
            }
            finally
            {
                File.Delete(redistFile);
            }

            Assert.Equal(3, t.ResolvedFiles.Length); // "Expected three assemblies to be found."
            Assert.Equal("true", t.ResolvedFiles[1].GetMetadata("IsRedistRoot"));
            Assert.Equal("false", t.ResolvedFiles[0].GetMetadata("IsRedistRoot"));
            Assert.Equal("", t.ResolvedFiles[2].GetMetadata("IsRedistRoot"));

            Assert.Equal("Microsoft-Windows-CLRCoreComp", t.ResolvedFiles[0].GetMetadata("Redist"));
            Assert.Equal("Microsoft-Windows-CLRCoreComp", t.ResolvedFiles[1].GetMetadata("Redist"));
            Assert.Equal("Microsoft-Windows-CLRCoreComp", t.ResolvedFiles[2].GetMetadata("Redist"));
        }
        public void HighVersionDoesntExist()
        {
            // Create the engine.
            MockEngine engine = new MockEngine();

            ITaskItem[] assemblyNames = new TaskItem[]
            {
                new TaskItem("DependsOnUnified, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
            };

            // Construct the app.config.
            string appConfigFile = WriteAppConfig
                (
                    "        <dependentAssembly>\n" +
                    "            <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
                    "            <bindingRedirect oldVersion='1.0.0.0' newVersion='4.0.0.0' />\n" +
                    "        </dependentAssembly>\n"
                );

            // Now, pass feed resolved primary references into ResolveAssemblyReference.
            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.BuildEngine = engine;
            t.Assemblies = assemblyNames;
            t.SearchPaths = DefaultPaths;
            t.AppConfigFile = appConfigFile;

            bool succeeded = Execute(t);

            Assert.True(succeeded);
            Assert.Equal(0, t.ResolvedDependencyFiles.Length);
            string shouldContain;

            string code = t.Log.ExtractMessageCode
                (
                    String.Format(AssemblyResources.GetString("ResolveAssemblyReference.FailedToResolveReference"),
                        String.Format(AssemblyResources.GetString("General.CouldNotLocateAssembly"), "UNIFyMe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")),
                    out shouldContain
                );


            engine.AssertLogContains
                (
                    shouldContain
                );

            engine.AssertLogContains
                (
                    String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAppConfig"), "1.0.0.0", appConfigFile, @"C:\MyApp\v1.0\DependsOnUnified.dll")
                );

            engine.AssertLogContains
                (
                    String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnifiedDependency"), "UNIFyMe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
                );



            // Cleanup.
            File.Delete(appConfigFile);
        }
        public void HigherVersionButSpecificVersionDirect()
        {
            MockEngine e = new MockEngine();

            TaskItem item = new TaskItem("DependsOnFoo45Framework, Version=4.5.0.0, PublicKeyToken=null, Culture=Neutral");
            item.SetMetadata("SpecificVersion", "true");

            ITaskItem[] items = new ITaskItem[]
            {
                item
            };

            ResolveAssemblyReference t = new ResolveAssemblyReference();
            t.BuildEngine = e;
            t.Assemblies = items;
            t.TargetFrameworkMoniker = "Foo, Version=4.0";
            t.TargetFrameworkMonikerDisplayName = "Foo";
            t.SearchPaths = new string[] { @"c:\Frameworks\" };
            Execute(t);

            Assert.Equal(0, e.Warnings); // "No warnings expected in this scenario."
            Assert.Equal(0, e.Errors); // "No errors expected in this scenario."
            Assert.Equal(1, t.ResolvedFiles.Length);
            Assert.True(ContainsItem(t.ResolvedFiles, @"c:\Frameworks\DependsOnFoo45Framework.dll")); // "Expected to find assembly, but didn't."
        }
示例#16
0
        public void VerifyClientProfileRedistListAndProfileList2()
        {
            // Create a generic redist list with system.xml and microsoft.build.engine.
            string profileRedistList = String.Empty;
            string fullRedistList = String.Empty;
            string fullFrameworkDirectory = Path.Combine(Path.GetTempPath(), "VerifyClientProfileRedistListAndProfileList2");
            string targetFrameworkDirectory = Path.Combine(fullFrameworkDirectory, "Profiles\\Client");
            try
            {
                GenerateRedistAndProfileXmlLocations(_fullRedistListContents, _engineOnlySubset, out profileRedistList, out fullRedistList, fullFrameworkDirectory, targetFrameworkDirectory);

                ResolveAssemblyReference t = new ResolveAssemblyReference();
                MockEngine e = new MockEngine();
                t.BuildEngine = e;
                t.Assemblies = new ITaskItem[] { new TaskItem("Microsoft.Build.Engine"), new TaskItem("System.Xml") };
                t.SearchPaths = new string[] { @"{TargetFrameworkDirectory}", fullFrameworkDirectory };
                t.TargetFrameworkDirectories = new string[] { targetFrameworkDirectory };
                t.InstalledAssemblyTables = new ITaskItem[] { new TaskItem(profileRedistList) };
                t.IgnoreDefaultInstalledAssemblyTables = true;

                ITaskItem item = new TaskItem(fullRedistList);
                item.SetMetadata("FrameworkDirectory", Path.GetDirectoryName(fullRedistList));
                t.FullFrameworkAssemblyTables = new ITaskItem[] { item };
                t.ProfileName = "Client";

                string microsoftBuildEnginePath = Path.Combine(fullFrameworkDirectory, "Microsoft.Build.Engine.dll");
                string systemXmlPath = Path.Combine(targetFrameworkDirectory, "System.Xml.dll");

                bool success = GenerateHelperDelegatesAndExecuteTask(t, microsoftBuildEnginePath, systemXmlPath);
                Assert.True(success); // "Expected no errors."
                Assert.Equal(1, t.ResolvedFiles.Length); // "Expected one resolved assembly."
                Assert.True(t.ResolvedFiles[0].ItemSpec.Contains("Microsoft.Build.Engine")); // "Expected Engine to resolve."
                e.AssertLogContains("MSB3252");
            }
            finally
            {
                if (Directory.Exists(fullFrameworkDirectory))
                {
                    Directory.Delete(fullFrameworkDirectory, true);
                }
            }
        }
示例#17
0
        /// <summary>
        /// Going through all the binding redirects in the runtime node, if anyone overlaps with a RAR suggested redirect,
        /// we update the existing redirect and output warning.
        /// </summary>
        private void UpdateExistingBindingRedirects(XElement runtimeNode, IDictionary <AssemblyName, string> redirects)
        {
            ErrorUtilities.VerifyThrow(runtimeNode != null, "This should not be called if the \"runtime\" node is missing.");

            var assemblyBindingNodes = runtimeNode.Nodes()
                                       .OfType <XElement>()
                                       .Where(e => e.Name.LocalName == "assemblyBinding");

            foreach (var assemblyBinding in assemblyBindingNodes)
            {
                var dependentAssembly = assemblyBinding.Nodes()
                                        .OfType <XElement>()
                                        .FirstOrDefault();

                if (dependentAssembly == null)
                {
                    Log.LogWarningWithCodeFromResources("GenerateBindingRedirects.MissingNode", "dependentAssembly", "assemblyBinding");
                    continue;
                }

                var assemblyIdentity = dependentAssembly.Nodes()
                                       .OfType <XElement>()
                                       .Where(e => e.Name.LocalName == "assemblyIdentity")
                                       .FirstOrDefault();

                if (assemblyIdentity == null)
                {
                    Log.LogWarningWithCodeFromResources("GenerateBindingRedirects.MissingNode", "assemblyIdentity", "dependentAssembly");
                    continue;
                }

                var bindingRedirect = dependentAssembly.Nodes()
                                      .OfType <XElement>()
                                      .Where(e => e.Name.LocalName == "bindingRedirect")
                                      .FirstOrDefault();

                if (bindingRedirect == null)
                {
                    Log.LogWarningWithCodeFromResources("GenerateBindingRedirects.MissingNode", "bindingRedirect", "dependentAssembly");
                    continue;
                }

                var name                = assemblyIdentity.Attribute("name");
                var nameValue           = name.Value;
                var publicKeyToken      = assemblyIdentity.Attribute("publicKeyToken");
                var publicKeyTokenValue = publicKeyToken.Value;
                var culture             = assemblyIdentity.Attribute("culture");
                var cultureValue        = culture == null ? String.Empty : culture.Value;

                if (name == null || publicKeyToken == null)
                {
                    continue;
                }

                var oldVersionAttribute = bindingRedirect.Attribute("oldVersion");
                var newVersionAttribute = bindingRedirect.Attribute("newVersion");

                if (oldVersionAttribute == null || newVersionAttribute == null)
                {
                    continue;
                }

                var oldVersionRange = oldVersionAttribute.Value.Split('-');
                if (oldVersionRange == null || oldVersionRange.Length == 0 || oldVersionRange.Length > 2)
                {
                    continue;
                }

                var oldVerStrLow  = oldVersionRange[0];
                var oldVerStrHigh = oldVersionRange[oldVersionRange.Length == 1 ? 0 : 1];

                Version oldVersionLow, oldVersionHigh;
                if (!Version.TryParse(oldVerStrLow, out oldVersionLow))
                {
                    Log.LogWarningWithCodeFromResources("GenerateBindingRedirects.MalformedVersionNumber", oldVerStrLow);
                    continue;
                }

                if (!Version.TryParse(oldVerStrHigh, out oldVersionHigh))
                {
                    Log.LogWarningWithCodeFromResources("GenerateBindingRedirects.MalformedVersionNumber", oldVerStrHigh);
                    continue;
                }

                // We cannot do a simply dictionary lookup here because we want to allow relaxed "culture" matching:
                // we consider it a match if the existing binding redirect doesn't specify culture in the assembly identity.
                foreach (var entry in redirects)
                {
                    if (IsMatch(entry.Key, nameValue, cultureValue, publicKeyTokenValue))
                    {
                        string maxVerStr  = entry.Value;
                        var    maxVersion = new Version(maxVerStr);

                        if (maxVersion >= oldVersionLow)
                        {
                            // Update the existing binding redirect to the RAR suggested one.
                            var newName                  = entry.Key.Name;
                            var newCulture               = entry.Key.CultureName;
                            var newPublicKeyToken        = entry.Key.GetPublicKeyToken();
                            var newProcessorArchitecture = entry.Key.ProcessorArchitecture;

                            var attributes = new List <XAttribute>(4);
                            attributes.Add(new XAttribute("name", newName));
                            attributes.Add(new XAttribute("culture", String.IsNullOrEmpty(newCulture) ? "neutral" : newCulture));
                            attributes.Add(new XAttribute("publicKeyToken", ResolveAssemblyReference.ByteArrayToString(newPublicKeyToken)));
                            if (newProcessorArchitecture != 0)
                            {
                                attributes.Add(new XAttribute("processorArchitecture", newProcessorArchitecture.ToString()));
                            }

                            assemblyIdentity.ReplaceAttributes(attributes);

                            oldVersionAttribute.Value = "0.0.0.0-" + (maxVersion >= oldVersionHigh ? maxVerStr : oldVerStrHigh);
                            newVersionAttribute.Value = maxVerStr;
                            redirects.Remove(entry.Key);

                            Log.LogWarningWithCodeFromResources("GenerateBindingRedirects.OverlappingBindingRedirect", entry.Key.ToString(), bindingRedirect.ToString());
                        }

                        break;
                    }
                }
            }
        }
        public void ExistsPromotedDependencyInTheBlackList()
        {
            string engineOnlySubset =
                "<FileList Redist='Microsoft-Windows-CLRCoreComp' >" +
                "<File AssemblyName='Microsoft.Build.Engine' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' />" +
                "</FileList >";

            string implicitRedistListContents =
                "<FileList Redist='Microsoft-Windows-CLRCoreComp' >" +
                "<File AssemblyName='UniFYme' Version='2.0.0.0' Culture='neutral' PublicKeyToken='b77a5c561934e089' InGAC='false' />" +
                "</FileList >";

            string redistListPath = FileUtilities.GetTemporaryFile();
            string subsetListPath = FileUtilities.GetTemporaryFile();
            string appConfigFile = null;
            try
            {
                File.WriteAllText(redistListPath, implicitRedistListContents);
                File.WriteAllText(subsetListPath, engineOnlySubset);


                // Create the engine.
                MockEngine engine = new MockEngine();

                ITaskItem[] assemblyNames = new TaskItem[]
                {
                    new TaskItem("DependsOnUnified, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
                };

                // Construct the app.config.
                appConfigFile = WriteAppConfig
                    (
                        "        <dependentAssembly>\n" +
                        "            <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
                        "            <bindingRedirect oldVersion='1.0.0.0' newVersion='2.0.0.0' />\n" +
                        "        </dependentAssembly>\n"
                    );

                // Now, pass feed resolved primary references into ResolveAssemblyReference.
                ResolveAssemblyReference t = new ResolveAssemblyReference();
                t.InstalledAssemblyTables = new TaskItem[] { new TaskItem(redistListPath) };
                t.InstalledAssemblySubsetTables = new TaskItem[] { new TaskItem(subsetListPath) };

                t.BuildEngine = engine;
                t.Assemblies = assemblyNames;
                t.SearchPaths = DefaultPaths;
                t.AppConfigFile = appConfigFile;

                bool succeeded = Execute(t, false);

                Assert.True(succeeded);
                Assert.Equal(0, t.ResolvedDependencyFiles.Length);
                engine.AssertLogDoesntContain
                    (
                        String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAppConfig"), "1.0.0.0", appConfigFile, @"C:\MyApp\v1.0\DependsOnUnified.dll")
                    );
            }
            finally
            {
                File.Delete(redistListPath);
                File.Delete(subsetListPath);

                // Cleanup.
                File.Delete(appConfigFile);
            }
        }
示例#19
0
        public void InputAllowedRelatedFileExtensionsAreUsed()
        {
            // This WriteLine is a hack.  On a slow machine, the Tasks unittest fails because remoting
            // times out the object used for remoting console writes.  Adding a write in the middle of
            // keeps remoting from timing out the object.
            Console.WriteLine("Performing Miscellaneous.InputRelatedFileExtensionsAreUsed() test");

            // Create the engine.
            MockEngine engine = new MockEngine();

            // Construct a list of assembly files.
            ITaskItem[] assemblies = new TaskItem[]
            {
                new TaskItem(@"c:\AssemblyFolder\SomeAssembly.dll")
            };

            // Now, pass feed resolved primary references into ResolveAssemblyReference.
            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.BuildEngine = engine;
            t.Assemblies = assemblies;
            t.TargetFrameworkDirectories = new string[] { @"c:\WINNT\Microsoft.NET\Framework\v2.0.MyVersion" };
            t.SearchPaths = DefaultPaths;
            t.AllowedRelatedFileExtensions = new string[] { @".licenses", ".xml" }; //no .pdb or .config
            Execute(t);

            Assert.Equal(1, t.ResolvedFiles.Length);
            Assert.True(t.ResolvedFiles[0].ItemSpec.EndsWith(@"AssemblyFolder\SomeAssembly.dll"));

            // Process the related files.
            Assert.Equal(2, t.RelatedFiles.Length);

            bool licensesFound = false;
            bool xmlFound = false;
            foreach (ITaskItem item in t.RelatedFiles)
            {
                if (item.ItemSpec.EndsWith(@"AssemblyFolder\SomeAssembly.licenses"))
                {
                    licensesFound = true;
                }
                if (item.ItemSpec.EndsWith(@"AssemblyFolder\SomeAssembly.xml"))
                {
                    xmlFound = true;
                }
            }

            Assert.True(licensesFound && xmlFound); // "Expected to find .licenses and .xml related files."
        }
        private void UpdateExistingBindingRedirects(XElement runtimeNode, IDictionary <AssemblyName, string> redirects)
        {
            ErrorUtilities.VerifyThrow(runtimeNode != null, "This should not be called if the \"runtime\" node is missing.");

            var assemblyBindingNodes = runtimeNode.Nodes()
                                       .OfType <XElement>()
                                       .Where(e => e.Name.LocalName == "assemblyBinding");

            foreach (var assemblyBinding in assemblyBindingNodes)
            {
                // Each assemblyBinding section could have more than one dependentAssembly elements
                var dependentAssemblies = assemblyBinding.Nodes()
                                          .OfType <XElement>()
                                          .Where(e => e.Name.LocalName == "dependentAssembly");

                foreach (var dependentAssembly in dependentAssemblies)
                {
                    var assemblyIdentity = dependentAssembly
                                           .Nodes()
                                           .OfType <XElement>()
                                           .FirstOrDefault(e => e.Name.LocalName == "assemblyIdentity");

                    if (assemblyIdentity == null)
                    {
                        // Due to MSDN documentation (https://msdn.microsoft.com/en-us/library/0ash1ksb(v=vs.110).aspx)
                        // assemblyIdentity is required subelement. Emitting a warning if it's not there.
                        Log.LogWarningWithCodeFromResources("GenerateBindingRedirects.MissingNode", "dependentAssembly", "assemblyBinding");
                        continue;
                    }

                    var bindingRedirect = dependentAssembly
                                          .Nodes()
                                          .OfType <XElement>()
                                          .FirstOrDefault(e => e.Name.LocalName == "bindingRedirect");

                    if (bindingRedirect == null)
                    {
                        // Due to xsd schema and MSDN documentation bindingRedirect is not required subelement.
                        // Just skipping it without a warning.
                        continue;
                    }

                    var name           = assemblyIdentity.Attribute("name");
                    var publicKeyToken = assemblyIdentity.Attribute("publicKeyToken");

                    if (name == null || publicKeyToken == null)
                    {
                        continue;
                    }

                    var nameValue           = name.Value;
                    var publicKeyTokenValue = publicKeyToken.Value;
                    var culture             = assemblyIdentity.Attribute("culture");
                    var cultureValue        = culture?.Value ?? String.Empty;

                    var oldVersionAttribute = bindingRedirect.Attribute("oldVersion");
                    var newVersionAttribute = bindingRedirect.Attribute("newVersion");

                    if (oldVersionAttribute == null || newVersionAttribute == null)
                    {
                        continue;
                    }

                    var oldVersionRange = oldVersionAttribute.Value.Split(MSBuildConstants.HyphenChar);
                    if (oldVersionRange.Length == 0 || oldVersionRange.Length > 2)
                    {
                        continue;
                    }

                    var oldVerStrLow  = oldVersionRange[0];
                    var oldVerStrHigh = oldVersionRange[oldVersionRange.Length == 1 ? 0 : 1];

                    if (!Version.TryParse(oldVerStrLow, out Version oldVersionLow))
                    {
                        Log.LogWarningWithCodeFromResources("GenerateBindingRedirects.MalformedVersionNumber", oldVerStrLow);
                        continue;
                    }

                    if (!Version.TryParse(oldVerStrHigh, out Version oldVersionHigh))
                    {
                        Log.LogWarningWithCodeFromResources("GenerateBindingRedirects.MalformedVersionNumber", oldVerStrHigh);
                        continue;
                    }

                    // We cannot do a simply dictionary lookup here because we want to allow relaxed "culture" matching:
                    // we consider it a match if the existing binding redirect doesn't specify culture in the assembly identity.
                    foreach (var entry in redirects)
                    {
                        if (IsMatch(entry.Key, nameValue, cultureValue, publicKeyTokenValue))
                        {
                            string maxVerStr  = entry.Value;
                            var    maxVersion = new Version(maxVerStr);

                            if (maxVersion >= oldVersionLow)
                            {
                                // Update the existing binding redirect to the RAR suggested one.
                                var newName                  = entry.Key.Name;
                                var newCulture               = entry.Key.CultureName;
                                var newPublicKeyToken        = entry.Key.GetPublicKeyToken();
                                var newProcessorArchitecture = entry.Key.ProcessorArchitecture;

                                var attributes = new List <XAttribute>(4)
                                {
                                    new XAttribute("name", newName),
                                    new XAttribute(
                                        "culture",
                                        String.IsNullOrEmpty(newCulture) ? "neutral" : newCulture),
                                    new XAttribute(
                                        "publicKeyToken",
                                        ResolveAssemblyReference.ByteArrayToString(newPublicKeyToken))
                                };
                                if (newProcessorArchitecture != 0)
                                {
                                    attributes.Add(new XAttribute("processorArchitecture", newProcessorArchitecture.ToString()));
                                }

                                assemblyIdentity.ReplaceAttributes(attributes);

                                oldVersionAttribute.Value = "0.0.0.0-" + (maxVersion >= oldVersionHigh ? maxVerStr : oldVerStrHigh);
                                newVersionAttribute.Value = maxVerStr;
                                redirects.Remove(entry.Key);

                                Log.LogWarningWithCodeFromResources("GenerateBindingRedirects.OverlappingBindingRedirect", entry.Key.ToString(), bindingRedirect.ToString());
                            }

                            break;
                        }
                    }
                }
            }
        }
示例#21
0
        /// <summary>
        /// Given a strong name, find its path in the GAC.
        /// </summary>
        /// <param name="strongName">The strong name.</param>
        /// <param name="targetProcessorArchitecture">Like x86 or IA64\AMD64.</param>
        /// <param name="getRuntimeVersion">Delegate to get the runtime version from a file path</param>
        /// <param name="targetedRuntimeVersion">What version of the runtime are we targeting</param>
        /// <param name="fullFusionName">Are we guranteed to have a full fusion name. This really can only happen if we have already resolved the assembly</param>
        /// <returns>The path to the assembly. Empty if none exists.</returns>
        internal static string GetLocation
        (
            IBuildEngine4 buildEngine,
            AssemblyNameExtension strongName,
            ProcessorArchitecture targetProcessorArchitecture,
            GetAssemblyRuntimeVersion getRuntimeVersion,
            Version targetedRuntimeVersion,
            bool fullFusionName,
            FileExists fileExists,
            GetPathFromFusionName getPathFromFusionName,
            GetGacEnumerator getGacEnumerator,
            bool specificVersion
        )
        {
            ConcurrentDictionary <AssemblyNameExtension, string> fusionNameToResolvedPath = null;
            bool useGacRarCache = Environment.GetEnvironmentVariable("MSBUILDDISABLEGACRARCACHE") == null;

            if (buildEngine != null && useGacRarCache)
            {
                string key = "44d78b60-3bbe-48fe-9493-04119ebf515f" + "|" + targetProcessorArchitecture.ToString() + "|" + targetedRuntimeVersion.ToString() + "|" + fullFusionName.ToString() + "|" + specificVersion.ToString();
                fusionNameToResolvedPath = buildEngine.GetRegisteredTaskObject(key, RegisteredTaskObjectLifetime.Build) as ConcurrentDictionary <AssemblyNameExtension, string>;
                if (fusionNameToResolvedPath == null)
                {
                    fusionNameToResolvedPath = new ConcurrentDictionary <AssemblyNameExtension, string>(AssemblyNameComparer.GenericComparer);
                    buildEngine.RegisterTaskObject(key, fusionNameToResolvedPath, RegisteredTaskObjectLifetime.Build, true /* dispose early ok*/);
                }
                else
                {
                    if (fusionNameToResolvedPath.ContainsKey(strongName))
                    {
                        string fusionName = null;
                        fusionNameToResolvedPath.TryGetValue(strongName, out fusionName);
                        return(fusionName);
                    }
                }
            }

            // Optimize out the case where the public key token is null, if it is null it is not a strongly named assembly and CANNOT be in the gac.
            // also passing it would cause the gac enumeration method to throw an exception indicating the assembly is not a strongnamed assembly.

            string location = null;

            // If the publickeyToken is null and the publickeytoken is in the fusion name then this means we are passing in a null or empty PublicKeyToken and then this cannot possibly be in the gac.
            if ((strongName.GetPublicKeyToken() == null || strongName.GetPublicKeyToken().Length == 0) && strongName.FullName.IndexOf("PublicKeyToken", StringComparison.OrdinalIgnoreCase) != -1)
            {
                if (fusionNameToResolvedPath != null)
                {
                    fusionNameToResolvedPath.TryAdd(strongName, location);
                }

                return(location);
            }

            // A delegate was not passed in to use the default one
            getPathFromFusionName = getPathFromFusionName ?? pathFromFusionName;

            // A delegate was not passed in to use the default one
            getGacEnumerator = getGacEnumerator ?? gacEnumerator;

            // If we have no processor architecture set then we can tryout a number of processor architectures.
            if (!strongName.HasProcessorArchitectureInFusionName)
            {
                if (targetProcessorArchitecture != ProcessorArchitecture.MSIL && targetProcessorArchitecture != ProcessorArchitecture.None)
                {
                    string processorArchitecture = ResolveAssemblyReference.ProcessorArchitectureToString(targetProcessorArchitecture);
                    // Try processor specific first.
                    if (fullFusionName)
                    {
                        location = CheckForFullFusionNameInGac(strongName, processorArchitecture, getPathFromFusionName);
                    }
                    else
                    {
                        location = GetLocationImpl(strongName, processorArchitecture, getRuntimeVersion, targetedRuntimeVersion, fileExists, getPathFromFusionName, getGacEnumerator, specificVersion);
                    }

                    if (location != null && location.Length > 0)
                    {
                        if (fusionNameToResolvedPath != null)
                        {
                            fusionNameToResolvedPath.TryAdd(strongName, location);
                        }
                        return(location);
                    }
                }

                // Next, try MSIL
                if (fullFusionName)
                {
                    location = CheckForFullFusionNameInGac(strongName, "MSIL", getPathFromFusionName);
                }
                else
                {
                    location = GetLocationImpl(strongName, "MSIL", getRuntimeVersion, targetedRuntimeVersion, fileExists, getPathFromFusionName, getGacEnumerator, specificVersion);
                }
                if (location != null && location.Length > 0)
                {
                    if (fusionNameToResolvedPath != null)
                    {
                        fusionNameToResolvedPath.TryAdd(strongName, location);
                    }
                    return(location);
                }
            }

            // Next, try no processor architecure
            if (fullFusionName)
            {
                location = CheckForFullFusionNameInGac(strongName, null, getPathFromFusionName);
            }
            else
            {
                location = GetLocationImpl(strongName, null, getRuntimeVersion, targetedRuntimeVersion, fileExists, getPathFromFusionName, getGacEnumerator, specificVersion);
            }

            if (location != null && location.Length > 0)
            {
                if (fusionNameToResolvedPath != null)
                {
                    fusionNameToResolvedPath.TryAdd(strongName, location);
                }
                return(location);
            }

            if (fusionNameToResolvedPath != null)
            {
                fusionNameToResolvedPath.TryAdd(strongName, null);
            }

            return(null);
        }
示例#22
0
        /// <summary>
        /// Simulate a CreateProject resolution. This is primarily for IO monitoring.
        /// </summary>
        public void SimulateCreateProjectAgainstWhidbeyInternal(string fxfolder)
        {
            // This WriteLine is a hack.  On a slow machine, the Tasks unittest fails because remoting
            // times out the object used for remoting console writes.  Adding a write in the middle of
            // keeps remoting from timing out the object.
            Console.WriteLine("Performing SimulateCreateProjectAgainstWhidbey() test");

            // Create the engine.
            MockEngine engine = new MockEngine();

            // Now, pass feed resolved primary references into ResolveAssemblyReference.
            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.BuildEngine = engine;
            t.Assemblies = new ITaskItem[] {
                new TaskItem("System"),
                new TaskItem("System.Deployment"),
                new TaskItem("System.Drawing"),
                new TaskItem("System.Windows.Forms"),
            };
            t.TargetFrameworkDirectories = new string[] { fxfolder };

            t.SearchPaths = new string[]
            {
                "{CandidateAssemblyFiles}",
                // Reference path
                "{HintPathFromItem}",
                @"{TargetFrameworkDirectory}",
                @"{Registry:Software\Microsoft\.NetFramework,v2.0,AssemblyFoldersEx}",
                "{AssemblyFolders}",
                "{GAC}",
                "{RawFileName}"
            };

            bool succeeded = Execute(t);

            Assert.True(succeeded); // "Expected success."
        }
示例#23
0
        public void VerifyProfileErrorsAreLogged()
        {
            // Create a generic redist list with system.xml and microsoft.build.engine.
            string profileRedistList = String.Empty;
            string fullRedistList = String.Empty;
            string fullFrameworkDirectory = Path.Combine(Path.GetTempPath(), "VerifyProfileErrorsAreLogged");
            string targetFrameworkDirectory = Path.Combine(fullFrameworkDirectory, "Profiles\\Client");
            try
            {
                string fullRedistListContentsErrors =
                    "<FileList Redist='Microsoft-Windows-CLRCoreComp'>" +
                    "File AssemblyName='System.Xml' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' >" +
                    "File AssemblyName='Microsoft.Build.Engine' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' >" +
                    "";

                GenerateRedistAndProfileXmlLocations(fullRedistListContentsErrors, _engineOnlySubset, out profileRedistList, out fullRedistList, fullFrameworkDirectory, targetFrameworkDirectory);

                ResolveAssemblyReference t = new ResolveAssemblyReference();
                MockEngine e = new MockEngine();
                t.BuildEngine = e;
                t.Assemblies = new ITaskItem[] { new TaskItem("Microsoft.Build.Engine"), new TaskItem("System.Xml") };
                t.SearchPaths = new string[] { @"{TargetFrameworkDirectory}", fullFrameworkDirectory };
                t.TargetFrameworkDirectories = new string[] { targetFrameworkDirectory };
                t.InstalledAssemblyTables = new ITaskItem[] { new TaskItem(profileRedistList) };
                t.IgnoreDefaultInstalledAssemblyTables = true;

                ITaskItem item = new TaskItem(fullRedistList);
                item.SetMetadata("FrameworkDirectory", Path.GetDirectoryName(fullRedistList));
                t.FullFrameworkAssemblyTables = new ITaskItem[] { item };
                t.ProfileName = "Client";

                string microsoftBuildEnginePath = Path.Combine(fullFrameworkDirectory, "Microsoft.Build.Engine.dll");
                string systemXmlPath = Path.Combine(targetFrameworkDirectory, "System.Xml.dll");

                bool success = GenerateHelperDelegatesAndExecuteTask(t, microsoftBuildEnginePath, systemXmlPath);
                Assert.True(success); // "Expected errors."
                Assert.Equal(2, t.ResolvedFiles.Length); // "Expected two resolved assembly."
                e.AssertLogContains("MSB3263");
            }
            finally
            {
                if (Directory.Exists(fullFrameworkDirectory))
                {
                    Directory.Delete(fullFrameworkDirectory, true);
                }
            }
        }
示例#24
0
        public void VerifyAssemblyInGacButNotInProfileIsNotResolved()
        {
            // Create a generic redist list with system.xml and microsoft.build.engine.
            string profileRedistList = String.Empty;
            string fullRedistList = String.Empty;
            string fullFrameworkDirectory = Path.Combine(Path.GetTempPath(), "VerifyAssemblyInGacButNotInProfileIsNotResolved");
            string targetFrameworkDirectory = Path.Combine(fullFrameworkDirectory, "Profiles\\Client");
            useFrameworkFileExists = true;
            string fullRedistListContents =
                "<FileList Redist='Microsoft-Windows-CLRCoreComp' >" +
                "<File AssemblyName='System' Version='9.0.0.0' PublicKeyToken='b77a5c561934e089' Culture='Neutral'/>" +
                "</FileList >";

            try
            {
                GenerateRedistAndProfileXmlLocations(fullRedistListContents, _engineOnlySubset, out profileRedistList, out fullRedistList, fullFrameworkDirectory, targetFrameworkDirectory);

                ResolveAssemblyReference t = new ResolveAssemblyReference();
                MockEngine e = new MockEngine();
                t.BuildEngine = e;
                TaskItem item = new TaskItem(@"DependsOnOnlyv4Assemblies, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089");
                t.Assemblies = new ITaskItem[] { item };
                t.SearchPaths = new string[] { @"c:\MyComponents\4.0Component\", "{GAC}" };
                t.TargetFrameworkDirectories = new string[] { targetFrameworkDirectory };
                t.InstalledAssemblyTables = new ITaskItem[] { new TaskItem(profileRedistList) };
                t.IgnoreDefaultInstalledAssemblyTables = true;
                t.FullFrameworkFolders = new string[] { fullFrameworkDirectory };
                t.LatestTargetFrameworkDirectories = new string[] { fullFrameworkDirectory };
                t.ProfileName = "Client";
                t.TargetFrameworkMoniker = ".NETFramework, Version=4.0";

                bool success = Execute(t, false);
                Console.Out.WriteLine(e.Log);
                Assert.True(success); // "Expected no errors."
                Assert.Equal(0, t.ResolvedFiles.Length); // "Expected no files to resolved."
                string warningMessage = t.Log.FormatResourceString("ResolveAssemblyReference.FailBecauseDependentAssemblyInExclusionList", "DependsOnOnlyv4Assemblies, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089", "SysTem, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", t.TargetFrameworkMoniker);
                e.AssertLogContains(warningMessage);
            }
            finally
            {
                useFrameworkFileExists = false;
                if (Directory.Exists(fullFrameworkDirectory))
                {
                    Directory.Delete(fullFrameworkDirectory, true);
                }
            }
        }
        public void AppConfigSpecifiedWhenAutoUnifyEqualsTrue()
        {
            // Create the engine.
            MockEngine engine = new MockEngine();

            ITaskItem[] assemblyNames = new TaskItem[]
            {
                new TaskItem("DependsOnUnified, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
            };

            // Construct the app.config.
            string appConfigFile = WriteAppConfig
                (
                    "        <dependentAssembly>\n" +
                    "            <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
                    "            <bindingRedirect oldVersion='0.0.0.0-2.0.0.0' newVersion='2.0.0.0' />\n" +
                    "        </dependentAssembly>\n"
                );

            // Now, pass feed resolved primary references into ResolveAssemblyReference.
            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.BuildEngine = engine;
            t.Assemblies = assemblyNames;
            t.SearchPaths = DefaultPaths;
            t.AppConfigFile = appConfigFile;
            t.AutoUnify = true;

            bool succeeded = Execute(t);

            // With the introduction of GenerateBindingRedirects task, RAR now accepts AutoUnify and App.Config at the same time.
            Assert.True(succeeded);
            Assert.Equal(0, engine.Errors);

            // Cleanup.
            File.Delete(appConfigFile);
        }
        public void AppConfigDoesntExist()
        {
            // Create the engine.
            MockEngine engine = new MockEngine();

            ITaskItem[] assemblyNames = new TaskItem[]
            {
                new TaskItem("DependsOnUnified, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
            };

            // Now, pass feed resolved primary references into ResolveAssemblyReference.
            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.BuildEngine = engine;
            t.Assemblies = assemblyNames;
            t.SearchPaths = DefaultPaths;
            t.AppConfigFile = @"C:\MyNonexistentFolder\MyNonExistentApp.config";

            bool succeeded = Execute(t);
            Assert.False(succeeded);
            Assert.Equal(1, engine.Errors);
        }
        public void HigherVersionDirect()
        {
            MockEngine e = new MockEngine();

            TaskItem item = new TaskItem("DependsOnFoo45Framework");

            ITaskItem[] items = new ITaskItem[]
            {
                item
            };

            ResolveAssemblyReference t = new ResolveAssemblyReference();
            t.BuildEngine = e;
            t.Assemblies = items;
            t.TargetFrameworkMoniker = "Foo, Version=4.0";
            t.TargetFrameworkMonikerDisplayName = "Foo";
            t.SearchPaths = new string[] { @"c:\Frameworks\" };
            Execute(t, false);

            Assert.Equal(1, e.Warnings); // "One warning expected in this scenario."
            e.AssertLogContains("MSB3274");
            Assert.Equal(0, e.Errors); // "No errors expected in this scenario."
            Assert.Equal(0, t.ResolvedFiles.Length);
            Assert.Equal(0, t.ResolvedDependencyFiles.Length);
        }
        public void HigherVersionDirectDependenciesFalse()
        {
            MockEngine e = new MockEngine();

            TaskItem item = new TaskItem("DependsOnFoo45Framework");

            ITaskItem[] items = new ITaskItem[]
            {
                item
            };

            ResolveAssemblyReference t = new ResolveAssemblyReference();
            t.BuildEngine = e;
            t.Assemblies = items;
            t.FindDependencies = false;
            t.TargetFrameworkMoniker = "Foo, Version=4.0";
            t.TargetFrameworkMonikerDisplayName = "Foo";
            t.SearchPaths = new string[] { @"c:\Frameworks\" };
            Assert.True(t.Execute(fileExists, directoryExists, getDirectories, getAssemblyName, getAssemblyMetadata, getRegistrySubKeyNames, getRegistrySubKeyDefaultValue, getLastWriteTime, getRuntimeVersion, openBaseKey, checkIfAssemblyIsInGac, isWinMDFile, readMachineTypeFromPEHeader));


            Assert.Equal(0, e.Warnings); // "No warning expected in this scenario."
            Assert.Equal(0, e.Errors); // "No errors expected in this scenario."
            Assert.Equal(1, t.ResolvedFiles.Length);
            Assert.Equal(0, t.ResolvedDependencyFiles.Length);
            Assert.True(ContainsItem(t.ResolvedFiles, @"c:\Frameworks\DependsOnFoo45Framework.dll")); // "Expected to find assembly, but didn't."
        }
示例#29
0
        /// <summary>
        /// helper for  TargetFrameworkFiltering
        /// </summary>
        private int RunTargetFrameworkFilteringTest(string projectTargetFramework)
        {
            ResolveAssemblyReference t = new ResolveAssemblyReference();
            t.BuildEngine = new MockEngine();
            t.Assemblies = new ITaskItem[]
            {
                new TaskItem("A"),
                new TaskItem("B"),
                new TaskItem("C")
            };

            t.SearchPaths = new string[]
            {
                @"c:\MyLibraries"
            };

            t.Assemblies[1].SetMetadata("RequiredTargetFramework", "3.0");
            t.Assemblies[2].SetMetadata("RequiredTargetFramework", "3.5");
            t.TargetFrameworkVersion = projectTargetFramework;

            Execute(t);

            int set = 0;
            foreach (ITaskItem item in t.ResolvedFiles)
            {
                int mask = 0;
                if (item.ItemSpec.EndsWith(@"\A.dll"))
                {
                    mask = 1;
                }
                else if (item.ItemSpec.EndsWith(@"\B.dll"))
                {
                    mask = 2;
                }
                else if (item.ItemSpec.EndsWith(@"\C.dll"))
                {
                    mask = 4;
                }
                Assert.NotEqual(0, mask); // "Unexpected assembly in resolved list."
                Assert.Equal(0, (mask & set)); // "Assembly found twice in resolved list."
                set = set | mask;
            }
            return set;
        }
示例#30
0
        public void Regress286699_InvalidAssemblyFiles()
        {
            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.BuildEngine = new MockEngine();

            t.Assemblies = new ITaskItem[] { new TaskItem("mscorlib") };
            t.AssemblyFiles = new ITaskItem[] { new TaskItem("|") };

            bool retval = Execute(t);

            Assert.False(retval);

            // Should not crash.
        }
示例#31
0
        public void Verifyp2pAndProfile2()
        {
            // Create a generic redist list with system.xml and microsoft.build.engine.
            string profileRedistList = String.Empty;
            string fullRedistList = String.Empty;
            string fullFrameworkDirectory = Path.Combine(Path.GetTempPath(), "Verifyp2pAndProfile");
            string targetFrameworkDirectory = Path.Combine(fullFrameworkDirectory, "Profiles\\Client");

            string fullRedistListContents =
                "<FileList Redist='Microsoft-Windows-CLRCoreComp' >" +
                "<File AssemblyName='System' Version='9.0.0.0' PublicKeyToken='b77a5c561934e089' Culture='Neutral'/>" +
                "</FileList >";

            try
            {
                GenerateRedistAndProfileXmlLocations(fullRedistListContents, _engineOnlySubset, out profileRedistList, out fullRedistList, fullFrameworkDirectory, targetFrameworkDirectory);

                ResolveAssemblyReference t = new ResolveAssemblyReference();
                MockEngine e = new MockEngine();
                t.BuildEngine = e;
                TaskItem item = new TaskItem(@"c:\MyComponents\misc\DependsOn9Also.dll");
                item.SetMetadata("SpecificVersion", "true");
                t.AssemblyFiles = new ITaskItem[] { item };
                t.SearchPaths = new string[] { @"{TargetFrameworkDirectory}", fullFrameworkDirectory };
                t.TargetFrameworkDirectories = new string[] { targetFrameworkDirectory };
                t.InstalledAssemblyTables = new ITaskItem[] { new TaskItem(profileRedistList) };
                t.IgnoreDefaultInstalledAssemblyTables = true;
                t.FullFrameworkFolders = new string[] { fullFrameworkDirectory };
                t.ProfileName = "Client";

                bool success = Execute(t);
                Assert.True(success); // "Expected no errors."
                Assert.Equal(1, t.ResolvedFiles.Length); // "Expected no resolved assemblies."
                string warningMessage = t.Log.FormatResourceString("ResolveAssemblyReference.FailBecauseDependentAssemblyInExclusionList", @"c:\MyComponents\misc\DependsOn9Also.dll", "System, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Client");
                e.AssertLogDoesntContain(warningMessage);
            }
            finally
            {
                if (Directory.Exists(fullFrameworkDirectory))
                {
                    Directory.Delete(fullFrameworkDirectory, true);
                }
            }
        }
 private static bool ByteArrayMatchesString(Byte[] a, string s)
 {
     return(!String.Equals(ResolveAssemblyReference.ByteArrayToString(a), s, StringComparison.OrdinalIgnoreCase));
 }
示例#33
0
        public void Regress286699_InvalidAssembliesParameter()
        {
            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.BuildEngine = new MockEngine();

            t.Assemblies = new ITaskItem[] { new TaskItem("|!@#$%::") };

            bool retval = Execute(t);

            // I think this should return true
            Assert.True(retval);

            // Should not crash.
        }
        public override bool Execute()
        {
            if (SuggestedRedirects == null || SuggestedRedirects.Length == 0)
            {
                Log.LogMessageFromResources("GenerateBindingRedirects.NoSuggestedRedirects");
                OutputAppConfigFile = null;
                return(true);
            }

            var redirects = ParseSuggestedRedirects();

            var doc = LoadAppConfig(AppConfigFile);

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

            XElement runtimeNode = doc.Root
                                   .Nodes()
                                   .OfType <XElement>()
                                   .FirstOrDefault(e => e.Name.LocalName == "runtime");

            if (runtimeNode == null)
            {
                runtimeNode = new XElement("runtime");
                doc.Root.Add(runtimeNode);
            }
            else
            {
                UpdateExistingBindingRedirects(runtimeNode, redirects);
            }

            var ns = XNamespace.Get("urn:schemas-microsoft-com:asm.v1");

            var redirectNodes = from redirect in redirects
                                select new XElement(
                ns + "assemblyBinding",
                new XElement(
                    ns + "dependentAssembly",
                    new XElement(
                        ns + "assemblyIdentity",
                        new XAttribute("name", redirect.Key.Name),
                        new XAttribute("publicKeyToken", ResolveAssemblyReference.ByteArrayToString(redirect.Key.GetPublicKeyToken())),
                        new XAttribute("culture", String.IsNullOrEmpty(redirect.Key.CultureName) ? "neutral" : redirect.Key.CultureName)),
                    new XElement(
                        ns + "bindingRedirect",
                        new XAttribute("oldVersion", "0.0.0.0-" + redirect.Value),
                        new XAttribute("newVersion", redirect.Value))));

            runtimeNode.Add(redirectNodes);

            var writeOutput = true;

            if (FileSystems.Default.FileExists(OutputAppConfigFile.ItemSpec))
            {
                try
                {
                    var outputDoc = LoadAppConfig(OutputAppConfigFile);
                    if (outputDoc.ToString() == doc.ToString())
                    {
                        writeOutput = false;
                    }
                }
                catch (System.Xml.XmlException)
                {
                    writeOutput = true;
                }
            }

            if (AppConfigFile != null)
            {
                AppConfigFile.CopyMetadataTo(OutputAppConfigFile);
            }
            else
            {
                OutputAppConfigFile.SetMetadata(ItemMetadataNames.targetPath, TargetName);
            }

            if (writeOutput)
            {
                using (var stream = FileUtilities.OpenWrite(OutputAppConfigFile.ItemSpec, false))
                {
                    doc.Save(stream);
                }
            }

            return(!Log.HasLoggedErrors);
        }
        /// <summary>
        /// Resolve a single assembly using the provided search paths and setting the targetframework directories.
        /// </summary>
        private static AssemblyResolutionResult ResolveAssembly(string assemblyName, IList<string> searchPaths, IList<string> targetFrameworkDirectories, bool checkDependencies) {
            ResolveAssemblyReference rar = new ResolveAssemblyReference();
            MockEngine engine = new MockEngine();
            rar.BuildEngine = engine;
            if (searchPaths != null) {
                rar.SearchPaths = searchPaths.ToArray();
            }
            if (targetFrameworkDirectories != null) {
                rar.TargetFrameworkDirectories = targetFrameworkDirectories.ToArray();
            }
            rar.Assemblies = new ITaskItem[] {
                new TaskItem(assemblyName),
            };
            rar.Silent = true;
            rar.Execute();

            AssemblyResolutionResult result = new AssemblyResolutionResult();

            List<string> resolvedFiles = new List<string>();
            foreach (ITaskItem item in rar.ResolvedFiles) {
                resolvedFiles.Add(item.ItemSpec);
            }
            if (checkDependencies) {
                CheckOutOfRangeDependencies(assemblyName);
            }
            result.ResolvedFiles = resolvedFiles.ToArray();
            result.Warnings = engine.Warnings;
            result.Errors = engine.Errors;
            return result;
        }