public void AssemblyFoldersFromConfigPlatformSpecificAssemblyFirstTest()
        {
            var assemblyConfig = Path.GetTempFileName();
            File.WriteAllText(assemblyConfig, TestFile);

            var moniker = "{AssemblyFoldersFromConfig:" + assemblyConfig + ",v4.5}";

            try
            {
                ResolveAssemblyReference t = new ResolveAssemblyReference
                {
                    BuildEngine = new MockEngine(),
                    Assemblies = new ITaskItem[] {new TaskItem("assemblyfromconfig_common.dll")},
                    SearchPaths = new[] {moniker},
                    TargetProcessorArchitecture = "x86"
                };

                Execute(t);

                Assert.Equal(1, t.ResolvedFiles.Length);
                Assert.Equal(@"c:\assemblyfromconfig\folder_x86\assemblyfromconfig_common.dll", t.ResolvedFiles[0].ItemSpec);
                AssertNoCase(moniker, t.ResolvedFiles[0].GetMetadata("ResolvedFrom"));
            }
            finally
            {
                FileUtilities.DeleteNoThrow(assemblyConfig);
            }
        }
Example #2
0
        public void TwoDependenciesSameNameDependOnHigherVersion()
        {
            MockEngine e = new MockEngine();

            ITaskItem[] items = new ITaskItem[]
            {
                new TaskItem("DependsOn9, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089"),
                new TaskItem("DependsOn9, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089")
            };

            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='false' />" +
                                  "</FileList >";

            ResolveAssemblyReference t = new ResolveAssemblyReference();

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

            Assert.Equal(2, e.Warnings); // "Expected two warnings."
            e.AssertLogContains(t.Log.FormatResourceString("ResolveAssemblyReference.DependencyReferenceOutsideOfFramework", "DependsOn9, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089", "System, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "9.0.0.0", "4.0.0.0"));
            e.AssertLogContains(t.Log.FormatResourceString("ResolveAssemblyReference.DependencyReferenceOutsideOfFramework", "DependsOn9, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089", "System, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "9.0.0.0", "4.0.0.0"));
            Assert.Equal(0, e.Errors); // "No errors expected in this scenario."
            Assert.Equal(0, t.ResolvedFiles.Length);
        }
Example #3
0
        public void ExistsOldVersionRange()
        {
            // Create the engine.
            MockEngine engine = new MockEngine();

            ITaskItem[] assemblyFiles = new TaskItem[]
            {
                new TaskItem(@"C:\MyComponents\v1.0\UnifyMe.dll")
            };

            // Construct the app.config.
            string appConfigFile = WriteAppConfig
                                   (
                "        <dependentAssembly>\n" +
                "            <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
                "            <bindingRedirect oldVersion='0.0.0.0-1.5.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.AssemblyFiles = assemblyFiles;
            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);
        }
Example #4
0
        public void HighVersionDoesntExist()
        {
            // Create the engine.
            MockEngine engine = new MockEngine(_output);

            ITaskItem[] assemblyFiles = new TaskItem[]
            {
                new TaskItem(s_unifyMeDll_V10Path)
            };

            // 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.AssemblyFiles = assemblyFiles;
            t.SearchPaths   = DefaultPaths;
            t.AppConfigFile = appConfigFile;

            bool succeeded = Execute(t);

            Assert.True(succeeded);
            Assert.Single(t.ResolvedFiles);
            t.ResolvedFiles[0].GetMetadata("FusionName").ShouldBe("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, ProcessorArchitecture=MSIL", StringCompareShould.IgnoreCase);

            // Cleanup.
            File.Delete(appConfigFile);
        }
Example #5
0
        public void LowVersionDoesntExist()
        {
            // Create the engine.
            MockEngine engine = new MockEngine(_output);

            ITaskItem[] assemblyNames = new TaskItem[]
            {
                new TaskItem("UnifyMe, Version=0.5.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='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;

            bool succeeded = Execute(t);

            Assert.True(succeeded);
            Assert.Empty(t.ResolvedFiles);

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

            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='DontUnifyMe' 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);
            t.ResolvedDependencyFiles[0].GetMetadata("FusionName").ShouldBe("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", StringCompareShould.IgnoreCase);

            // Cleanup.
            File.Delete(appConfigFile);
        }
Example #7
0
        private static Node ReadResolveAssemblyReference(XmlReader reader)
        {
            var task = new ResolveAssemblyReference();

            for (int i = 0; i < reader.AttributeCount; ++i)
            {
                reader.MoveToAttribute(i);
                switch (reader.Name)
                {
                case "Condition":
                    task.Condition = reader.Value;
                    break;

                case "Assemblies":
                    task.Assemblies = reader.Value;
                    break;

                default:
                    throw new ParseException(string.Format("Unknown attribute \"{0}\" on ResolveAssemblyReference element",
                                                           reader.Name));
                }
            }
            return(task);
        }
        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);
        }
Example #9
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)
            {
                // 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;
                        }
                    }
                }
            }
        }
Example #10
0
        public void ExistsPromotedDependencyInTheBlackList()
        {
            string implicitRedistListContents =
                "<FileList Redist='Microsoft-Windows-CLRCoreComp' >" +
                "<File AssemblyName='UniFYme' Version='2.0.0.0' Culture='neutral' PublicKeyToken='b77a5c561934e089' InGAC='false' />" +
                "</FileList >";

            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 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);

                Assert.True(succeeded);
                Assert.Equal(0, t.ResolvedDependencyFiles.Length);
                engine.AssertLogDoesntContain
                (
                    String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAppConfig"), "1.0.0.0", appConfigFile, Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll"))
                );
            }
            finally
            {
                File.Delete(redistListPath);
                File.Delete(subsetListPath);

                // Cleanup.
                File.Delete(appConfigFile);
            }
        }
Example #11
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))
                    {
                        fusionNameToResolvedPath.TryGetValue(strongName, out string 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.

            // 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)
            {
                fusionNameToResolvedPath?.TryAdd(strongName, null);
                return(null);
            }

            // 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.
            string location;

            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 (!string.IsNullOrEmpty(location))
                    {
                        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 (!string.IsNullOrEmpty(location))
                {
                    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 (!string.IsNullOrEmpty(location))
            {
                fusionNameToResolvedPath?.TryAdd(strongName, location);
                return(location);
            }

            fusionNameToResolvedPath?.TryAdd(strongName, null);

            return(null);
        }
Example #12
0
        public void SystemRuntimeDepends_No_Build()
        {
            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.BuildEngine = new MockEngine();

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

            t.Assemblies[0].SetMetadata("HintPath", @"C:\SystemRuntime\Regular.dll");

            t.SearchPaths = DefaultPaths;

            // build mode
            t.FindDependencies = true;
            Assert.True(
                t.Execute
                (
                    fileExists,
                    directoryExists,
                    getDirectories,
                    getAssemblyName,
                    getAssemblyMetadata,
#if FEATURE_WIN32_REGISTRY
                    getRegistrySubKeyNames,
                    getRegistrySubKeyDefaultValue,
#endif
                    getLastWriteTime,
                    getRuntimeVersion,
#if FEATURE_WIN32_REGISTRY
                    openBaseKey,
#endif
                    checkIfAssemblyIsInGac,
                    isWinMDFile,
                    readMachineTypeFromPEHeader
                )
                );

            Assert.True(string.Equals(t.DependsOnSystemRuntime, "false", StringComparison.OrdinalIgnoreCase)); //                 "Expected no System.Runtime dependency found during build."
            Assert.True(string.Equals(t.DependsOnNETStandard, "false", StringComparison.OrdinalIgnoreCase));   //                   "Expected no netstandard dependency found during build."

            // intelli build mode
            t.FindDependencies = false;
            Assert.True(
                t.Execute
                (
                    fileExists,
                    directoryExists,
                    getDirectories,
                    getAssemblyName,
                    getAssemblyMetadata,
#if FEATURE_WIN32_REGISTRY
                    getRegistrySubKeyNames,
                    getRegistrySubKeyDefaultValue,
#endif
                    getLastWriteTime,
                    getRuntimeVersion,
#if FEATURE_WIN32_REGISTRY
                    openBaseKey,
#endif
                    checkIfAssemblyIsInGac,
                    isWinMDFile,
                    readMachineTypeFromPEHeader
                )
                );

            Assert.True(string.Equals(t.DependsOnSystemRuntime, "false", StringComparison.OrdinalIgnoreCase)); //                 "Expected no System.Runtime dependency found during intellibuild."
            Assert.True(string.Equals(t.DependsOnNETStandard, "false", StringComparison.OrdinalIgnoreCase));   //                   "Expected no netstandard dependency found during intellibuild."
        }
Example #13
0
        public void NETStandardDepends_Yes_Indirect()
        {
            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.BuildEngine = new MockEngine();

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

            t.Assemblies[0].SetMetadata("HintPath", s_netstandardLibraryDllPath);

            t.SearchPaths = DefaultPaths;

            // build mode
            t.FindDependencies = true;

            Assert.True(t.Execute(
                            fileExists,
                            directoryExists,
                            getDirectories,
                            getAssemblyName,
                            getAssemblyMetadata,
#if FEATURE_WIN32_REGISTRY
                            getRegistrySubKeyNames,
                            getRegistrySubKeyDefaultValue,
#endif
                            getLastWriteTime,
                            getRuntimeVersion,
#if FEATURE_WIN32_REGISTRY
                            openBaseKey,
#endif
                            checkIfAssemblyIsInGac,
                            isWinMDFile,
                            readMachineTypeFromPEHeader));

            Console.WriteLine(((MockEngine)t.BuildEngine).Log);
            Assert.True(string.Equals(t.DependsOnNETStandard, "true", StringComparison.OrdinalIgnoreCase)); //                 "Expected netstandard dependency found during build."

            // intelli build mode
            t.FindDependencies = false;
            Assert.True(t.Execute(
                            fileExists,
                            directoryExists,
                            getDirectories,
                            getAssemblyName,
                            getAssemblyMetadata,
#if FEATURE_WIN32_REGISTRY
                            getRegistrySubKeyNames,
                            getRegistrySubKeyDefaultValue,
#endif
                            getLastWriteTime,
                            getRuntimeVersion,
#if FEATURE_WIN32_REGISTRY
                            openBaseKey,
#endif
                            checkIfAssemblyIsInGac,
                            isWinMDFile,
                            readMachineTypeFromPEHeader));

            Assert.True(string.Equals(t.DependsOnNETStandard, "true", StringComparison.OrdinalIgnoreCase)); //                 "Expected netstandard dependency found during intellibuild."
        }
Example #14
0
        /// <summary>
        /// Execute the task.
        /// </summary>
        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);
        }
        public void AssemblyFoldersFromConfigFileNotFoundTest()
        {
            var assemblyConfig = Path.GetTempFileName();
            File.Delete(assemblyConfig);
            var moniker = "{AssemblyFoldersFromConfig:" + assemblyConfig + ",v4.5}";

            try
            {
                ResolveAssemblyReference t = new ResolveAssemblyReference
                {
                    BuildEngine = new MockEngine(),
                    Assemblies = new ITaskItem[] {new TaskItem("assemblyfromconfig_common.dll")},
                    SearchPaths = new[] {moniker},
                    TargetProcessorArchitecture = "x86"
                };


                Assert.Throws<InternalErrorException>(() => Execute(t));
            }
            finally
            {
                FileUtilities.DeleteNoThrow(assemblyConfig);
            }
        }
        public void AssemblyFoldersFromConfigFileMalformed()
        {
            var assemblyConfig = Path.GetTempFileName();
            File.WriteAllText(assemblyConfig, "<<<>><>!" + TestFile);

            var moniker = "{AssemblyFoldersFromConfig:" + assemblyConfig + ",v4.5}";

            try
            {
                MockEngine engine = new MockEngine();
                ResolveAssemblyReference t = new ResolveAssemblyReference
                {
                    BuildEngine = engine,
                    Assemblies = new ITaskItem[] { new TaskItem("assemblyfromconfig2") },
                    SearchPaths = new[] { moniker }
                };

                var success = Execute(t);

                Assert.False(success);
                Assert.Equal(0, t.ResolvedFiles.Length);
                engine.AssertLogContains(") specified in Microsoft.Common.CurrentVersion.targets was invalid. The error was: ");
            }
            finally
            {
                FileUtilities.DeleteNoThrow(assemblyConfig);
            }
        }
Example #17
0
        public void MultipleUnifiedFromNamesMiddlePrimaryOnBlackList()
        {
            string implicitRedistListContents =
                "<FileList Redist='Microsoft-Windows-CLRCoreComp' >" +
                "<File AssemblyName='DependsOnUnified' Version='3.0.0.0' Culture='neutral' PublicKeyToken='b77a5c561934e089' InGAC='false' />" +
                "</FileList >";

            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 redistListPath = FileUtilities.GetTemporaryFile();
            string subsetListPath = FileUtilities.GetTemporaryFile();

            File.WriteAllText(redistListPath, implicitRedistListContents);
            File.WriteAllText(subsetListPath, engineOnlySubset);

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

            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"),
                new TaskItem("DependsOnUnified, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
            };

            // 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.TargetFrameworkDirectories = new string[] { @"c:\myfx" };
            t.AutoUnify = true;

            bool succeeded = Execute(t);

            Assert.True(succeeded);
            Assert.Equal(2, t.ResolvedFiles.Length);                                                           // "Expected to find two resolved assemblies"
            Assert.True(ContainsItem(t.ResolvedFiles, Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll"))); // "Expected the ItemSpec of the resolved file to be the item spec of the 1.0.0.0 assembly");
            Assert.True(ContainsItem(t.ResolvedFiles, Path.Combine(s_myApp_V20Path, "DependsOnUnified.dll"))); // "Expected the ItemSpec of the resolved file to be the item spec of the 2.0.0.0 assembly");
            t.ResolvedDependencyFiles[0].GetMetadata("FusionName").ShouldBe("UnifyMe, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", StringCompareShould.IgnoreCase);
            t.ResolvedDependencyFiles[0].ItemSpec.ShouldBe(s_unifyMeDll_V20Path, StringCompareShould.IgnoreCase);

            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", Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll"))
            );

            engine.AssertLogDoesntContain
            (
                String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAutoUnify"), "2.0.0.0", Path.Combine(s_myApp_V20Path, "DependsOnUnified.dll"))
            );
        }
        public void AasemblyFoldersFromConfigNormalizeNetFrameworkVersion()
        {
            var assemblyConfig = Path.GetTempFileName();
            File.WriteAllText(assemblyConfig, TestFile);

            var moniker = "{AssemblyFoldersFromConfig:" + assemblyConfig + ",v5.0}";

            try
            {
                ResolveAssemblyReference t = new ResolveAssemblyReference
                {
                    BuildEngine = new MockEngine(),
                    Assemblies = new ITaskItem[] { new TaskItem("v5assembly.dll") },
                    SearchPaths = new[] { moniker },
                    TargetProcessorArchitecture = "x86"
                };

                Execute(t);

                Assert.Equal(1, t.ResolvedFiles.Length);
                Assert.Equal(@"c:\assemblyfromconfig\folder501000x86\v5assembly.dll", t.ResolvedFiles[0].ItemSpec);
                AssertNoCase(moniker, t.ResolvedFiles[0].GetMetadata("ResolvedFrom"));

                // Try again changing only the processor architecture
                t = new ResolveAssemblyReference
                {
                    BuildEngine = new MockEngine(),
                    Assemblies = new ITaskItem[] { new TaskItem("v5assembly.dll") },
                    SearchPaths = new[] { moniker },
                    TargetProcessorArchitecture = "AMD64"
                };

                Execute(t);

                Assert.Equal(1, t.ResolvedFiles.Length);
                Assert.Equal(@"c:\assemblyfromconfig\folder5010x64\v5assembly.dll", t.ResolvedFiles[0].ItemSpec);
                AssertNoCase(moniker, t.ResolvedFiles[0].GetMetadata("ResolvedFrom"));
            }
            finally
            {
                FileUtilities.DeleteNoThrow(assemblyConfig);
            }
        }
        public void HighVersionDoesntExist()
        {
            // Create the engine.
            MockEngine engine = new MockEngine(_output);

            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.Empty(t.ResolvedDependencyFiles);
            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, Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll"))
            );

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



            // Cleanup.
            File.Delete(appConfigFile);
        }
Example #20
0
        public void ExistsWithPrimaryReferenceOnBlackList()
        {
            string implicitRedistListContents =
                "<FileList Redist='Microsoft-Windows-CLRCoreComp' >" +
                "<File AssemblyName='DependsOnUnified' Version='2.0.0.0' Culture='neutral' PublicKeyToken='b77a5c561934e089' InGAC='false' />" +
                "</FileList >";

            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 redistListPath = FileUtilities.GetTemporaryFile();
            string subsetListPath = FileUtilities.GetTemporaryFile();

            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"),
                    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.InstalledAssemblyTables       = new TaskItem[] { new TaskItem(redistListPath) };
                t.InstalledAssemblySubsetTables = new TaskItem[] { new TaskItem(subsetListPath) };
                t.BuildEngine = engine;
                t.Assemblies  = assemblyNames;
                t.SearchPaths = DefaultPaths;
                t.AutoUnify   = true;

                bool succeeded = Execute(t);

                Assert.True(succeeded);
                Assert.Equal(1, t.ResolvedFiles.Length);                                                                  // "Expected there to only be one resolved file"
                Assert.True(t.ResolvedFiles[0].ItemSpec.Contains(Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll"))); // "Expected the ItemSpec of the resolved file to be the item spec of the 1.0.0.0 assembly");
                Assert.Equal(1, t.ResolvedDependencyFiles.Length);                                                        // "Expected there to be two resolved dependencies"
                AssertNoCase("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", t.ResolvedDependencyFiles[0].GetMetadata("FusionName"));
                AssertNoCase(s_unifyMeDll_V10Path, t.ResolvedDependencyFiles[0].ItemSpec);

                engine.AssertLogDoesntContain
                (
                    String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnifiedDependency"), "UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, ProcessorArchitecture=MSIL")
                );

                engine.AssertLogDoesntContain
                (
                    String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAutoUnify"), "1.0.0.0", Path.Combine(s_myApp_V20Path, "DependsOnUnified.dll"))
                );
            }
            finally
            {
                File.Delete(redistListPath);
                File.Delete(subsetListPath);
            }
        }
        public void SystemRuntimeDepends_Yes()
        {
            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.BuildEngine = new MockEngine(_output);

            t.Assemblies = new ITaskItem[]
            {
                new TaskItem("System.Runtime"),
            };

            t.Assemblies[0].SetMetadata("HintPath", @"C:\SystemRuntime\System.Runtime.dll");

            t.SearchPaths = DefaultPaths;

            // build mode
            t.FindDependencies = true;

            Assert.True(
                t.Execute
                (
                    fileExists,
                    directoryExists,
                    getDirectories,
                    getAssemblyName,
                    getAssemblyMetadata,
#if FEATURE_WIN32_REGISTRY
                    getRegistrySubKeyNames,
                    getRegistrySubKeyDefaultValue,
#endif
                    getLastWriteTime,
                    getRuntimeVersion,
#if FEATURE_WIN32_REGISTRY
                    openBaseKey,
#endif
                    checkIfAssemblyIsInGac,
                    isWinMDFile,
                    readMachineTypeFromPEHeader
                )
                );

            Assert.Equal("true", t.DependsOnSystemRuntime, true); // "Expected System.Runtime dependency found during build."

            // intelli build mode
            t.FindDependencies = false;
            Assert.True(
                t.Execute
                (
                    fileExists,
                    directoryExists,
                    getDirectories,
                    getAssemblyName,
                    getAssemblyMetadata,
#if FEATURE_WIN32_REGISTRY
                    getRegistrySubKeyNames,
                    getRegistrySubKeyDefaultValue,
#endif
                    getLastWriteTime,
                    getRuntimeVersion,
#if FEATURE_WIN32_REGISTRY
                    openBaseKey,
#endif
                    checkIfAssemblyIsInGac,
                    isWinMDFile,
                    readMachineTypeFromPEHeader
                )
                );

            Assert.Equal("true", t.DependsOnSystemRuntime, true); // "Expected System.Runtime dependency found during intellibuild."
        }
Example #22
0
        public void VerifyAssemblyPulledOutOfFrameworkDoesntGetFrameworkFileAttribute()
        {
            MockEngine e = new MockEngine(_output);

            string actualFrameworkDirectory      = s_myVersion20Path;
            string alternativeFrameworkDirectory = s_myVersion40Path;

            ITaskItem[] items = new TaskItem[] { new TaskItem(Path.Combine(actualFrameworkDirectory, "System.dll")) };

            // Version and directory match framework - it is a framework assembly
            string redistString1 = "<FileList Redist='Microsoft-Windows-CLRCoreComp-Random' >" +
                                   "<File AssemblyName='System' Version='2.0.0.0' PublicKeyToken='b77a5c561934e089' Culture='neutral' ProcessorArchitecture='MSIL' FileVersion='4.0.0.0' InGAC='true' />" +
                                   "</FileList >";

            ResolveAssemblyReference t1 = new ResolveAssemblyReference();

            t1.TargetFrameworkVersion     = "v4.5";
            t1.TargetFrameworkDirectories = new string[] { actualFrameworkDirectory };
            ExecuteRAROnItemsAndRedist(t1, e, items, redistString1, true, new List <string>()
            {
                "{RawFileName}"
            });

            Assert.False(String.IsNullOrEmpty(t1.ResolvedFiles[0].GetMetadata("FrameworkFile")));

            // Higher version than framework, but directory matches - it is a framework assembly
            string redistString2 = "<FileList Redist='Microsoft-Windows-CLRCoreComp-Random' >" +
                                   "<File AssemblyName='System' Version='1.0.0.0' PublicKeyToken='b77a5c561934e089' Culture='neutral' ProcessorArchitecture='MSIL' FileVersion='4.0.0.0' InGAC='true' />" +
                                   "</FileList >";

            ResolveAssemblyReference t2 = new ResolveAssemblyReference();

            t2.TargetFrameworkVersion     = "v4.5";
            t2.TargetFrameworkDirectories = new string[] { actualFrameworkDirectory };
            ExecuteRAROnItemsAndRedist(t2, e, items, redistString2, true, new List <string>()
            {
                "{RawFileName}"
            });

            Assert.False(String.IsNullOrEmpty(t2.ResolvedFiles[0].GetMetadata("FrameworkFile")));

            // Version is lower but directory does not match - it is a framework assembly
            string redistString3 = "<FileList Redist='Microsoft-Windows-CLRCoreComp-Random' >" +
                                   "<File AssemblyName='System' Version='3.0.0.0' PublicKeyToken='b77a5c561934e089' Culture='neutral' ProcessorArchitecture='MSIL' FileVersion='4.0.0.0' InGAC='true' />" +
                                   "</FileList >";

            ResolveAssemblyReference t3 = new ResolveAssemblyReference();

            t3.TargetFrameworkVersion     = "v4.5";
            t3.TargetFrameworkDirectories = new string[] { alternativeFrameworkDirectory };
            ExecuteRAROnItemsAndRedist(t3, e, items, redistString3, true, new List <string>()
            {
                "{RawFileName}"
            });

            Assert.False(String.IsNullOrEmpty(t3.ResolvedFiles[0].GetMetadata("FrameworkFile")));

            // Version is higher and directory does not match - this assembly has been pulled out of .NET
            string redistString4 = "<FileList Redist='Microsoft-Windows-CLRCoreComp-Random' >" +
                                   "<File AssemblyName='System' Version='1.0.0.0' PublicKeyToken='b77a5c561934e089' Culture='neutral' ProcessorArchitecture='MSIL' FileVersion='4.0.0.0' InGAC='true' />" +
                                   "</FileList >";

            ResolveAssemblyReference t4 = new ResolveAssemblyReference();

            t4.TargetFrameworkVersion     = "v4.5";
            t4.TargetFrameworkDirectories = new string[] { alternativeFrameworkDirectory };
            ExecuteRAROnItemsAndRedist(t4, e, items, redistString4, true, new List <string>()
            {
                "{RawFileName}"
            });

            Assert.True(String.IsNullOrEmpty(t4.ResolvedFiles[0].GetMetadata("FrameworkFile")));
        }
        public void DependsOn_NETStandard_and_SystemRuntime_ExternallyResolved()
        {
            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.BuildEngine = new MockEngine(_output);

            t.Assemblies = new ITaskItem[]
            {
                new TaskItem("netstandardlibrary"),
                new TaskItem("Portable"),
            };

            t.Assemblies[0].SetMetadata("ExternallyResolved", "true");
            t.Assemblies[0].SetMetadata("HintPath", s_netstandardLibraryDllPath);
            t.Assemblies[1].SetMetadata("ExternallyResolved", "true");
            t.Assemblies[1].SetMetadata("HintPath", s_portableDllPath);

            t.SearchPaths = DefaultPaths;

            // build mode
            t.FindDependencies = true;

            Assert.True(t.Execute(
                            fileExists,
                            directoryExists,
                            getDirectories,
                            getAssemblyName,
                            getAssemblyMetadata,
#if FEATURE_WIN32_REGISTRY
                            getRegistrySubKeyNames,
                            getRegistrySubKeyDefaultValue,
#endif
                            getLastWriteTime,
                            getRuntimeVersion,
#if FEATURE_WIN32_REGISTRY
                            openBaseKey,
#endif
                            checkIfAssemblyIsInGac,
                            isWinMDFile,
                            readMachineTypeFromPEHeader));

            Assert.Equal("true", t.DependsOnSystemRuntime, true); // "Expected System.Runtime dependency found during build."
            Assert.Equal("true", t.DependsOnNETStandard, true);   //                   "Expected netstandard dependency found during build."

            // intelli build mode
            t.FindDependencies = false;
            Assert.True(t.Execute(
                            fileExists,
                            directoryExists,
                            getDirectories,
                            getAssemblyName,
                            getAssemblyMetadata,
#if FEATURE_WIN32_REGISTRY
                            getRegistrySubKeyNames,
                            getRegistrySubKeyDefaultValue,
#endif
                            getLastWriteTime,
                            getRuntimeVersion,
#if FEATURE_WIN32_REGISTRY
                            openBaseKey,
#endif
                            checkIfAssemblyIsInGac,
                            isWinMDFile,
                            readMachineTypeFromPEHeader));

            Assert.Equal("true", t.DependsOnSystemRuntime, true); // "Expected System.Runtime dependency found during intellibuild."
            Assert.Equal("true", t.DependsOnNETStandard, true);   //                   "Expected netstandard dependency found during intellibuild."
        }
Example #24
0
        private void VerifyImplementationArchitecture(string winmdName, string targetProcessorArchitecture, string implementationFileArch, string warnOrErrorOnTargetArchitectureMismatch)
        {
            // Create the engine.
            MockEngine engine = new MockEngine(_output);
            TaskItem   item   = new TaskItem(winmdName);

            ITaskItem[] assemblyFiles = new TaskItem[] { item };

            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.BuildEngine = engine;
            t.Assemblies  = assemblyFiles;
            t.SearchPaths = new String[] { @"C:\WinMDArchVerification" };
            t.TargetProcessorArchitecture             = targetProcessorArchitecture;
            t.WarnOrErrorOnTargetArchitectureMismatch = warnOrErrorOnTargetArchitectureMismatch;

            bool succeeded = Execute(t);

            Assert.Single(t.ResolvedFiles);

            Assert.Equal(@"C:\WinMDArchVerification\" + winmdName + ".winmd", t.ResolvedFiles[0].ItemSpec);
            Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime));
            Assert.True(bool.Parse(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile)));

            string fullMessage = null;

            if (implementationFileArch.Equals("Unknown"))
            {
                fullMessage = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ResolveAssemblyReference.UnknownProcessorArchitecture", @"C:\WinMDArchVerification\" + winmdName + ".dll", @"C:\WinMDArchVerification\" + winmdName + ".winmd", NativeMethods.IMAGE_FILE_MACHINE_R4000.ToString("X", CultureInfo.InvariantCulture));
            }
            else
            {
                fullMessage = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ResolveAssemblyReference.MismatchBetweenTargetedAndReferencedArchOfImplementation", targetProcessorArchitecture, implementationFileArch, @"C:\WinMDArchVerification\" + winmdName + ".dll", @"C:\WinMDArchVerification\" + winmdName + ".winmd");
            }

            if (warnOrErrorOnTargetArchitectureMismatch.Equals("None", StringComparison.OrdinalIgnoreCase))
            {
                engine.AssertLogDoesntContain(fullMessage);
            }
            else
            {
                engine.AssertLogContains(fullMessage);
            }

            if (warnOrErrorOnTargetArchitectureMismatch.Equals("Warning", StringComparison.OrdinalIgnoreCase))
            {
                // Should fail since PE Header is not valid and this is always an error.
                Assert.True(succeeded);
                Assert.Equal(winmdName + ".dll", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile));
                Assert.Equal(0, engine.Errors);
                Assert.Equal(1, engine.Warnings);
            }
            else if (warnOrErrorOnTargetArchitectureMismatch.Equals("Error", StringComparison.OrdinalIgnoreCase))
            {
                // Should fail since PE Header is not valid and this is always an error.
                Assert.False(succeeded);
                Assert.Empty(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile));
                Assert.Equal(1, engine.Errors);
                Assert.Equal(0, engine.Warnings);
            }
            else if (warnOrErrorOnTargetArchitectureMismatch.Equals("None", StringComparison.OrdinalIgnoreCase))
            {
                Assert.True(succeeded);
                Assert.Equal(winmdName + ".dll", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile));
                Assert.Equal(0, engine.Errors);
                Assert.Equal(0, engine.Warnings);
            }
        }
Example #25
0
 /// <summary>
 /// Determines whether string "s" is the hexdecimal representation of the byte array "a".
 /// </summary>
 private static bool ByteArrayMatchesString(Byte[] a, string s)
 {
     return(String.Compare(ResolveAssemblyReference.ByteArrayToString(a), s, StringComparison.OrdinalIgnoreCase) != 0);
 }