private void DumpTargetProfileLists(AssemblyTableInfo[] installedAssemblyTableInfo, AssemblyTableInfo[] whiteListSubsetTableInfo, ReferenceTable referenceTable)
 {
     if ((installedAssemblyTableInfo != null) && (Environment.GetEnvironmentVariable("MSBUILDDUMPFRAMEWORKSUBSETLIST") != null))
     {
         base.Log.LogMessageFromResources(MessageImportance.Low, "ResolveAssemblyReference.TargetFrameworkSubsetLogHeader", new object[0]);
         base.Log.LogMessageFromResources(MessageImportance.Low, "ResolveAssemblyReference.TargetFrameworkRedistLogHeader", new object[0]);
         if (installedAssemblyTableInfo != null)
         {
             foreach (AssemblyTableInfo info in installedAssemblyTableInfo)
             {
                 if (info != null)
                 {
                     base.Log.LogMessageFromResources(MessageImportance.Low, "ResolveAssemblyReference.FourSpaceIndent", new object[] { base.Log.FormatResourceString("ResolveAssemblyReference.FormattedAssemblyInfo", new object[] { info.Path }) });
                 }
             }
         }
         base.Log.LogMessageFromResources(MessageImportance.Low, "ResolveAssemblyReference.TargetFrameworkWhiteListLogHeader", new object[0]);
         if (whiteListSubsetTableInfo != null)
         {
             foreach (AssemblyTableInfo info2 in whiteListSubsetTableInfo)
             {
                 if (info2 != null)
                 {
                     base.Log.LogMessageFromResources(MessageImportance.Low, "ResolveAssemblyReference.FourSpaceIndent", new object[] { base.Log.FormatResourceString("ResolveAssemblyReference.FormattedAssemblyInfo", new object[] { info2.Path }) });
                 }
             }
         }
         if (referenceTable.ListOfExcludedAssemblies != null)
         {
             base.Log.LogMessageFromResources(MessageImportance.Low, "ResolveAssemblyReference.TargetFrameworkExclusionListLogHeader", new object[0]);
             foreach (string str2 in referenceTable.ListOfExcludedAssemblies)
             {
                 base.Log.LogMessageFromResources(MessageImportance.Low, "ResolveAssemblyReference.FourSpaceIndent", new object[] { str2 });
             }
         }
     }
 }
        /// <summary>
        /// Log the results.
        /// </summary>
        /// <param name="dependencyTable">Reference table.</param>
        /// <param name="idealAssemblyRemappings">Array of ideal assembly remappings.</param>
        /// <param name="idealAssemblyRemappingsIdentities">Array of identities of ideal assembly remappings.</param>
        /// <param name="generalResolutionExceptions">List of exceptions that were not attributable to a particular fusion name.</param>
        /// <returns></returns>
        private bool LogResults
        (
            ReferenceTable dependencyTable,
            DependentAssembly[] idealAssemblyRemappings,
            AssemblyNameReference[] idealAssemblyRemappingsIdentities,
            ArrayList generalResolutionExceptions
        )
        {
            bool success = true;
#if (!STANDALONEBUILD)
            using (new CodeMarkerStartEnd(CodeMarkerEvent.perfMSBuildRARLogResultsBegin, CodeMarkerEvent.perfMSBuildRARLogResultsEnd))
#endif
            {
                /*
                PERF NOTE: The Silent flag turns off logging completely from the task side. This means
                we avoid the String.Formats that would normally occur even if the verbosity was set to 
                quiet at the engine level.
                */
                if (!Silent)
                {
                    // First, loop over primaries and display information.
                    foreach (AssemblyNameExtension assemblyName in dependencyTable.References.Keys)
                    {
                        string fusionName = assemblyName.FullName;
                        Reference primaryCandidate = dependencyTable.GetReference(assemblyName);

                        if (primaryCandidate.IsPrimary && !(primaryCandidate.IsConflictVictim && primaryCandidate.IsCopyLocal))
                        {
                            LogReference(primaryCandidate, fusionName);
                        }
                    }

                    // Second, loop over dependencies and display information.
                    foreach (AssemblyNameExtension assemblyName in dependencyTable.References.Keys)
                    {
                        string fusionName = assemblyName.FullName;
                        Reference dependencyCandidate = dependencyTable.GetReference(assemblyName);

                        if (!dependencyCandidate.IsPrimary && !(dependencyCandidate.IsConflictVictim && dependencyCandidate.IsCopyLocal))
                        {
                            LogReference(dependencyCandidate, fusionName);
                        }
                    }

                    // Third, show conflicts and their resolution.
                    foreach (AssemblyNameExtension assemblyName in dependencyTable.References.Keys)
                    {
                        string fusionName = assemblyName.FullName;
                        Reference conflictCandidate = dependencyTable.GetReference(assemblyName);

                        if (conflictCandidate.IsConflictVictim)
                        {
                            LogConflict(conflictCandidate, fusionName);

                            // Log the assemblies and primary source items which are related to the conflict which was just logged.
                            Reference victor = dependencyTable.GetReference(conflictCandidate.ConflictVictorName);

                            // Log the winner of the conflict resolution, the source items and dependencies which caused it
                            LogReferenceDependenciesAndSourceItems(conflictCandidate.ConflictVictorName.FullName, victor);

                            // Log the reference which lost the conflict and the dependencies and source items which caused it.
                            LogReferenceDependenciesAndSourceItems(fusionName, conflictCandidate);
                        }
                    }

                    // Fourth, if there were any suggested redirects. Show one message per redirect and a single warning.
                    if (idealAssemblyRemappings != null)
                    {
                        bool foundAtLeastOneValidBindingRedirect = false;
                        bool foundAtLeastOneUnresolvableConflict = false;

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

                        // A high-priority message for each individual redirect.
                        for (int i = 0; i < idealAssemblyRemappings.Length; i++)
                        {
                            DependentAssembly idealRemapping = idealAssemblyRemappings[i];
                            AssemblyName idealRemappingPartialAssemblyName = idealRemapping.PartialAssemblyName;
                            Reference reference = idealAssemblyRemappingsIdentities[i].reference;

                            for (int j = 0; j < idealRemapping.BindingRedirects.Length; j++)
                            {
                                AssemblyNameExtension[] conflictVictims = reference.GetConflictVictims();
                                foreach (AssemblyNameExtension conflictVictim in conflictVictims)
                                {
                                    // Make note we only output a conflict suggestion if the reference has at 
                                    // least one conflict victim - that way we don't suggest redirects to 
                                    // assemblies that don't exist at runtime. For example, this avoids us suggesting
                                    // a redirect from Foo 1.0.0.0 -> 2.0.0.0 in the following:
                                    //
                                    //      Project -> Foo, 1.0.0.0
                                    //      Project -> Bar -> Foo, 2.0.0.0
                                    //
                                    // Above, Foo, 1.0.0.0 wins out and is copied to the output directory because 
                                    // it is a primary reference.
                                    foundAtLeastOneValidBindingRedirect = true;

                                    Reference victimReference = dependencyTable.GetReference(conflictVictim);
                                    var newVerStr = idealRemapping.BindingRedirects[j].NewVersion.ToString();
                                    Log.LogMessageFromResources
                                    (
                                        MessageImportance.High,
                                        "ResolveAssemblyReference.ConflictRedirectSuggestion",
                                        idealRemappingPartialAssemblyName,
                                        conflictVictim.Version,
                                        victimReference.FullPath,
                                        newVerStr,
                                        reference.FullPath
                                    );

                                    if (!SupportsBindingRedirectGeneration && !AutoUnify)
                                    {
                                        // When running against projects types (such as Web Projects) where we can't auto-generate
                                        // binding redirects during the build, populate a buffer (to be output below) with the
                                        // binding redirect syntax that users need to add manually to the App.Config.

                                        var assemblyIdentityAttributes = new List<XAttribute>(4);

                                        assemblyIdentityAttributes.Add(new XAttribute("name", idealRemappingPartialAssemblyName.Name));

                                        // We use "neutral" for "Invariant Language (Invariant Country)" in assembly names.
                                        var cultureString = idealRemappingPartialAssemblyName.CultureName;
                                        assemblyIdentityAttributes.Add(new XAttribute("culture", String.IsNullOrEmpty(idealRemappingPartialAssemblyName.CultureName) ? "neutral" : idealRemappingPartialAssemblyName.CultureName));

                                        var publicKeyToken = idealRemappingPartialAssemblyName.GetPublicKeyToken();
                                        assemblyIdentityAttributes.Add(new XAttribute("publicKeyToken", ResolveAssemblyReference.ByteArrayToString(publicKeyToken)));

                                        var node = new XElement(
                                            ns + "assemblyBinding",
                                            new XElement(
                                                ns + "dependentAssembly",
                                                new XElement(
                                                    ns + "assemblyIdentity",
                                                    assemblyIdentityAttributes),
                                                new XElement(
                                                    ns + "bindingRedirect",
                                                    new XAttribute("oldVersion", "0.0.0.0-" + newVerStr),
                                                    new XAttribute("newVersion", newVerStr))));

                                        buffer.Append(node.ToString(SaveOptions.DisableFormatting));
                                    }
                                }

                                if (conflictVictims.Length == 0)
                                {
                                    foundAtLeastOneUnresolvableConflict = true;
                                }
                            }
                        }

                        // Log the warning
                        if (idealAssemblyRemappings.Length > 0 && foundAtLeastOneValidBindingRedirect)
                        {
                            if (SupportsBindingRedirectGeneration)
                            {
                                if (!AutoUnify)
                                {
                                    Log.LogWarningWithCodeFromResources("ResolveAssemblyReference.TurnOnAutoGenerateBindingRedirects");
                                }
                                // else we'll generate bindingRedirects to address the remappings
                            }
                            else if (!AutoUnify)
                            {
                                Log.LogWarningWithCodeFromResources("ResolveAssemblyReference.SuggestedRedirects", buffer.ToString());
                            }
                            // else AutoUnify is on and bindingRedirect generation is not supported
                            // we don't warn in this case since the binder will automatically unify these remappings
                        }

                        if (foundAtLeastOneUnresolvableConflict)
                        {
                            // This warning is logged regardless of AutoUnify since it means a conflict existed where the reference
                            // chosen was not the conflict victor in a version comparison, in other words it was older.
                            Log.LogWarningWithCodeFromResources("ResolveAssemblyReference.FoundConflicts");
                        }
                    }

                    // Fifth, log general resolution problems.

                    // Log general resolution exceptions.
                    foreach (Exception error in generalResolutionExceptions)
                    {
                        if (error is InvalidReferenceAssemblyNameException)
                        {
                            InvalidReferenceAssemblyNameException e = (InvalidReferenceAssemblyNameException)error;
                            Log.LogWarningWithCodeFromResources("General.MalformedAssemblyName", e.SourceItemSpec);
                        }
                        else
                        {
                            // An unknown Exception type was returned. Just throw.
                            throw error;
                        }
                    }
                }
            }

            if (dependencyTable.Resolvers != null)
            {
                foreach (Resolver r in dependencyTable.Resolvers)
                {
                    if (r is AssemblyFoldersExResolver)
                    {
                        AssemblyFoldersEx assemblyFoldersEx = ((AssemblyFoldersExResolver)r).AssemblyFoldersExLocations;

                        MessageImportance messageImportance = MessageImportance.Low;
                        if (assemblyFoldersEx != null && _showAssemblyFoldersExLocations.TryGetValue(r.SearchPath, out messageImportance))
                        {
                            Log.LogMessageFromResources(messageImportance, "ResolveAssemblyReference.AssemblyFoldersExSearchLocations", r.SearchPath);
                            foreach (AssemblyFoldersExInfo info in assemblyFoldersEx)
                            {
                                Log.LogMessageFromResources(messageImportance, "ResolveAssemblyReference.EightSpaceIndent", info.DirectoryPath);
                            }
                        }
                    }
                }
            }

            return success;
        }
        /// <summary>
        /// Log the target framework subset information.
        /// </summary>
        private void DumpTargetProfileLists(AssemblyTableInfo[] installedAssemblyTableInfo, AssemblyTableInfo[] whiteListSubsetTableInfo, ReferenceTable referenceTable)
        {
            if (installedAssemblyTableInfo != null)
            {
                string dumpFrameworkSubsetList = Environment.GetEnvironmentVariable("MSBUILDDUMPFRAMEWORKSUBSETLIST");

                if (dumpFrameworkSubsetList != null)
                {
                    Log.LogMessageFromResources(MessageImportance.Low, "ResolveAssemblyReference.TargetFrameworkSubsetLogHeader");

                    Log.LogMessageFromResources(MessageImportance.Low, "ResolveAssemblyReference.TargetFrameworkRedistLogHeader");
                    foreach (AssemblyTableInfo redistInfo in installedAssemblyTableInfo)
                    {
                        if (redistInfo != null)
                        {
                            Log.LogMessageFromResources(MessageImportance.Low, "ResolveAssemblyReference.FourSpaceIndent", Log.FormatResourceString("ResolveAssemblyReference.FormattedAssemblyInfo", redistInfo.Path));
                        }
                    }

                    Log.LogMessageFromResources(MessageImportance.Low, "ResolveAssemblyReference.TargetFrameworkWhiteListLogHeader");
                    if (whiteListSubsetTableInfo != null)
                    {
                        foreach (AssemblyTableInfo whiteListInfo in whiteListSubsetTableInfo)
                        {
                            if (whiteListInfo != null)
                            {
                                Log.LogMessageFromResources(MessageImportance.Low, "ResolveAssemblyReference.FourSpaceIndent", Log.FormatResourceString("ResolveAssemblyReference.FormattedAssemblyInfo", whiteListInfo.Path));
                            }
                        }
                    }

                    if (referenceTable.ListOfExcludedAssemblies != null)
                    {
                        Log.LogMessageFromResources(MessageImportance.Low, "ResolveAssemblyReference.TargetFrameworkExclusionListLogHeader");
                        foreach (string assemblyFullName in referenceTable.ListOfExcludedAssemblies)
                        {
                            Log.LogMessageFromResources(MessageImportance.Low, "ResolveAssemblyReference.FourSpaceIndent", assemblyFullName);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Execute the task.
        /// </summary>
        /// <param name="fileExists">Delegate used for checking for the existence of a file.</param>
        /// <param name="directoryExists">Delegate used for checking for the existence of a directory.</param>
        /// <param name="getDirectories">Delegate used for finding directories.</param>
        /// <param name="getAssemblyName">Delegate used for finding fusion names of assemblyFiles.</param>
        /// <param name="getAssemblyMetadata">Delegate used for finding dependencies of a file.</param>
        /// <param name="getRegistrySubKeyNames">Used to get registry subkey names.</param>
        /// <param name="getRegistrySubKeyDefaultValue">Used to get registry default values.</param>
        /// <param name="getLastWriteTime">Delegate used to get the last write time.</param>
        /// <returns>True if there was success.</returns>
        internal bool Execute
        (
            FileExists fileExists,
            DirectoryExists directoryExists,
            GetDirectories getDirectories,
            GetAssemblyName getAssemblyName,
            GetAssemblyMetadata getAssemblyMetadata,
            GetRegistrySubKeyNames getRegistrySubKeyNames,
            GetRegistrySubKeyDefaultValue getRegistrySubKeyDefaultValue,
            GetLastWriteTime getLastWriteTime,
            GetAssemblyRuntimeVersion getRuntimeVersion,
            OpenBaseKey openBaseKey,
            GetAssemblyPathInGac getAssemblyPathInGac,
            IsWinMDFile isWinMDFile,
            ReadMachineTypeFromPEHeader readMachineTypeFromPEHeader
        )
        {
            bool success = true;
#if (!STANDALONEBUILD)
            using (new CodeMarkerStartEnd(CodeMarkerEvent.perfMSBuildResolveAssemblyReferenceBegin, CodeMarkerEvent.perfMSBuildResolveAssemblyReferenceEnd))
#endif
            {
                try
                {
                    FrameworkNameVersioning frameworkMoniker = null;
                    if (!String.IsNullOrEmpty(_targetedFrameworkMoniker))
                    {
                        try
                        {
                            frameworkMoniker = new FrameworkNameVersioning(_targetedFrameworkMoniker);
                        }
                        catch (ArgumentException)
                        {
                            // The exception doesn't contain the bad value, so log it ourselves
                            Log.LogErrorWithCodeFromResources("ResolveAssemblyReference.InvalidParameter", "TargetFrameworkMoniker", _targetedFrameworkMoniker, String.Empty);
                            return false;
                        }
                    }

                    Version targetedRuntimeVersion = SetTargetedRuntimeVersion(_targetedRuntimeVersionRawValue);

                    // Log task inputs.
                    LogInputs();

                    if (!VerifyInputConditions())
                    {
                        return false;
                    }

                    _logVerboseSearchResults = Environment.GetEnvironmentVariable("MSBUILDLOGVERBOSERARSEARCHRESULTS") != null;

                    // Loop through all the target framework directories that were passed in,
                    // and ensure that they all have a trailing slash.  This is necessary
                    // for the string comparisons we will do later on.
                    if (_targetFrameworkDirectories != null)
                    {
                        for (int i = 0; i < _targetFrameworkDirectories.Length; i++)
                        {
                            _targetFrameworkDirectories[i] = FileUtilities.EnsureTrailingSlash(_targetFrameworkDirectories[i]);
                        }
                    }


                    // Validate the contents of the InstalledAssemblyTables parameter.
                    AssemblyTableInfo[] installedAssemblyTableInfo = GetInstalledAssemblyTableInfo(_ignoreDefaultInstalledAssemblyTables, _installedAssemblyTables, new GetListPath(RedistList.GetRedistListPathsFromDisk), TargetFrameworkDirectories);
                    AssemblyTableInfo[] whiteListSubsetTableInfo = null;

                    InstalledAssemblies installedAssemblies = null;
                    RedistList redistList = null;

                    if (installedAssemblyTableInfo != null && installedAssemblyTableInfo.Length > 0)
                    {
                        redistList = RedistList.GetRedistList(installedAssemblyTableInfo);
                    }

                    Hashtable blackList = null;

                    // The name of the subset if it is generated or the name of the profile. This will be used for error messages and logging.
                    string subsetOrProfileName = null;

                    // Are we targeting a profile
                    bool targetingProfile = !String.IsNullOrEmpty(ProfileName) && ((FullFrameworkFolders.Length > 0) || (FullFrameworkAssemblyTables.Length > 0));
                    bool targetingSubset = false;
                    List<Exception> whiteListErrors = new List<Exception>();
                    List<string> whiteListErrorFilesNames = new List<string>();

                    // Check for partial success in GetRedistList and log any tolerated exceptions.
                    if (redistList != null && redistList.Count > 0 || targetingProfile || ShouldUseSubsetBlackList())
                    {
                        // If we are not targeting a dev 10 profile and we have the required components to generate a orcas style subset, do so
                        if (!targetingProfile && ShouldUseSubsetBlackList())
                        {
                            // Based in the target framework subset names find the paths to the files
                            SubsetListFinder whiteList = new SubsetListFinder(_targetFrameworkSubsets);
                            whiteListSubsetTableInfo = GetInstalledAssemblyTableInfo(IgnoreDefaultInstalledAssemblySubsetTables, InstalledAssemblySubsetTables, new GetListPath(whiteList.GetSubsetListPathsFromDisk), TargetFrameworkDirectories);
                            if (whiteListSubsetTableInfo.Length > 0 && (redistList != null && redistList.Count > 0))
                            {
                                blackList = redistList.GenerateBlackList(whiteListSubsetTableInfo, whiteListErrors, whiteListErrorFilesNames);
                            }
                            else
                            {
                                Log.LogWarningWithCodeFromResources("ResolveAssemblyReference.NoSubsetsFound");
                            }

                            // Could get into this situation if the redist list files were full of junk and no assemblies were read in.
                            if (blackList == null)
                            {
                                Log.LogWarningWithCodeFromResources("ResolveAssemblyReference.NoRedistAssembliesToGenerateExclusionList");
                            }

                            subsetOrProfileName = GenerateSubSetName(_targetFrameworkSubsets, _installedAssemblySubsetTables);
                            targetingSubset = true;
                        }
                        else
                        {
                            // We are targeting a profile
                            if (targetingProfile)
                            {
                                // When targeting a profile we want the redist list to be the full framework redist list, since this is what should be used
                                // when unifying assemblies ect. 
                                AssemblyTableInfo[] fullRedistAssemblyTableInfo = null;
                                RedistList fullFrameworkRedistList = null;

                                HandleProfile(installedAssemblyTableInfo /*This is the table info related to the profile*/, out fullRedistAssemblyTableInfo, out blackList, out fullFrameworkRedistList);

                                // Make sure the redist list and the installedAsemblyTableInfo structures point to the full framework, we replace the installedAssemblyTableInfo
                                // which contained the information about the profile redist files with the one from the full framework because when doing anything with the RAR cache
                                // we want to use the full frameworks redist list. Essentailly after generating the exclusion list the job of the profile redist list is done.
                                redistList = fullFrameworkRedistList;

                                // Save the profile redist list file locations as the whiteList
                                whiteListSubsetTableInfo = installedAssemblyTableInfo;

                                // Set the installed assembly table to the full redist list values
                                installedAssemblyTableInfo = fullRedistAssemblyTableInfo;
                                subsetOrProfileName = _profileName;
                            }
                        }

                        if (redistList != null && redistList.Count > 0)
                        {
                            installedAssemblies = new InstalledAssemblies(redistList);
                        }
                    }

                    // Print out any errors reading the redist list.
                    if (redistList != null)
                    {
                        // Some files may have been skipped. Log warnings for these.
                        for (int i = 0; i < redistList.Errors.Length; ++i)
                        {
                            Exception e = redistList.Errors[i];
                            string filename = redistList.ErrorFileNames[i];

                            // Give the user a warning about the bad file (or files).
                            Log.LogWarningWithCodeFromResources("ResolveAssemblyReference.InvalidInstalledAssemblyTablesFile", filename, RedistList.RedistListFolder, e.Message);
                        }

                        // Some files may have been skipped. Log warnings for these.
                        for (int i = 0; i < whiteListErrors.Count; ++i)
                        {
                            Exception e = whiteListErrors[i];
                            string filename = whiteListErrorFilesNames[i];

                            // Give the user a warning about the bad file (or files).
                            Log.LogWarningWithCodeFromResources("ResolveAssemblyReference.InvalidInstalledAssemblySubsetTablesFile", filename, SubsetListFinder.SubsetListFolder, e.Message);
                        }
                    }

                    // Load any prior saved state.
                    ReadStateFile();
                    _cache.SetGetLastWriteTime(getLastWriteTime);
                    _cache.SetInstalledAssemblyInformation(installedAssemblyTableInfo);

                    // Cache delegates.
                    getAssemblyName = _cache.CacheDelegate(getAssemblyName);
                    getAssemblyMetadata = _cache.CacheDelegate(getAssemblyMetadata);
                    fileExists = _cache.CacheDelegate(fileExists);
                    getDirectories = _cache.CacheDelegate(getDirectories);
                    getRuntimeVersion = _cache.CacheDelegate(getRuntimeVersion);

                    _projectTargetFramework = FrameworkVersionFromString(_projectTargetFrameworkAsString);

                    // Filter out all Assemblies that have SubType!='', or higher framework
                    FilterBySubtypeAndTargetFramework();

                    // Compute the set of bindingRedirect remappings.
                    DependentAssembly[] appConfigRemappedAssemblies = null;
                    if (FindDependencies)
                    {
                        try
                        {
                            appConfigRemappedAssemblies = GetAssemblyRemappingsFromAppConfig();
                        }
                        catch (AppConfigException e)
                        {
                            Log.LogErrorWithCodeFromResources(null, e.FileName, e.Line, e.Column, 0, 0, "ResolveAssemblyReference.InvalidAppConfig", AppConfigFile, e.Message);
                            return false;
                        }
                    }

                    SystemProcessorArchitecture processorArchitecture = TargetProcessorArchitectureToEnumeration(_targetProcessorArchitecture);

                    // Start the table of dependencies with all of the primary references.
                    ReferenceTable dependencyTable = new ReferenceTable
                    (
                        BuildEngine,
                        _findDependencies,
                        _findSatellites,
                        _findSerializationAssemblies,
                        _findRelatedFiles,
                        _searchPaths,
                        _allowedAssemblyExtensions,
                        _relatedFileExtensions,
                        _candidateAssemblyFiles,
                        _resolvedSDKReferences,
                        _targetFrameworkDirectories,
                        installedAssemblies,
                        processorArchitecture,
                        fileExists,
                        directoryExists,
                        getDirectories,
                        getAssemblyName,
                        getAssemblyMetadata,
                        getRegistrySubKeyNames,
                        getRegistrySubKeyDefaultValue,
                        openBaseKey,
                        getRuntimeVersion,
                        targetedRuntimeVersion,
                        _projectTargetFramework,
                        frameworkMoniker,
                        Log,
                        _latestTargetFrameworkDirectories,
                        _copyLocalDependenciesWhenParentReferenceInGac,
                        DoNotCopyLocalIfInGac,
                        getAssemblyPathInGac,
                        isWinMDFile,
                        _ignoreVersionForFrameworkReferences,
                        readMachineTypeFromPEHeader,
                        _warnOrErrorOnTargetArchitectureMismatch,
                        _ignoreTargetFrameworkAttributeVersionMismatch,
                        _unresolveFrameworkAssembliesFromHigherFrameworks
                        );

                    // If AutoUnify, then compute the set of assembly remappings.
                    ArrayList generalResolutionExceptions = new ArrayList();

                    subsetOrProfileName = targetingSubset && String.IsNullOrEmpty(_targetedFrameworkMoniker) ? subsetOrProfileName : _targetedFrameworkMoniker;
                    bool excludedReferencesExist = false;

                    DependentAssembly[] autoUnifiedRemappedAssemblies = null;
                    AssemblyNameReference[] autoUnifiedRemappedAssemblyReferences = null;
                    if (AutoUnify && FindDependencies)
                    {
                        // Compute all dependencies.
                        dependencyTable.ComputeClosure
                        (
                            // Use any app.config specified binding redirects so that later when we output suggested redirects
                            // for the GenerateBindingRedirects target, we don't suggest ones that the user already wrote
                            appConfigRemappedAssemblies,
                            _assemblyFiles,
                            _assemblyNames,
                            generalResolutionExceptions
                        );

                        try
                        {
                            excludedReferencesExist = false;
                            if (redistList != null && redistList.Count > 0)
                            {
                                excludedReferencesExist = dependencyTable.MarkReferencesForExclusion(blackList);
                            }
                        }
                        catch (InvalidOperationException e)
                        {
                            Log.LogErrorWithCodeFromResources("ResolveAssemblyReference.ProblemDeterminingFrameworkMembership", e.Message);
                            return false;
                        }

                        if (excludedReferencesExist)
                        {
                            dependencyTable.RemoveReferencesMarkedForExclusion(true /* Remove the reference and do not warn*/, subsetOrProfileName);
                        }


                        // Based on the closure, get a table of ideal remappings needed to 
                        // produce zero conflicts.
                        dependencyTable.ResolveConflicts
                        (
                            out autoUnifiedRemappedAssemblies,
                            out autoUnifiedRemappedAssemblyReferences
                        );
                    }

                    DependentAssembly[] allRemappedAssemblies = CombineRemappedAssemblies(appConfigRemappedAssemblies, autoUnifiedRemappedAssemblies);

                    // Compute all dependencies.
                    dependencyTable.ComputeClosure(allRemappedAssemblies, _assemblyFiles, _assemblyNames, generalResolutionExceptions);

                    try
                    {
                        excludedReferencesExist = false;
                        if (redistList != null && redistList.Count > 0)
                        {
                            excludedReferencesExist = dependencyTable.MarkReferencesForExclusion(blackList);
                        }
                    }
                    catch (InvalidOperationException e)
                    {
                        Log.LogErrorWithCodeFromResources("ResolveAssemblyReference.ProblemDeterminingFrameworkMembership", e.Message);
                        return false;
                    }

                    if (excludedReferencesExist)
                    {
                        dependencyTable.RemoveReferencesMarkedForExclusion(false /* Remove the reference and warn*/, subsetOrProfileName);
                    }

                    // Resolve any conflicts.
                    DependentAssembly[] idealAssemblyRemappings = null;
                    AssemblyNameReference[] idealAssemblyRemappingsIdentities = null;

                    dependencyTable.ResolveConflicts
                    (
                        out idealAssemblyRemappings,
                        out idealAssemblyRemappingsIdentities
                    );

                    // Build the output tables.
                    dependencyTable.GetReferenceItems
                    (
                        out _resolvedFiles,
                        out _resolvedDependencyFiles,
                        out _relatedFiles,
                        out _satelliteFiles,
                        out _serializationAssemblyFiles,
                        out _scatterFiles,
                        out _copyLocalFiles
                    );

                    // If we're not finding dependencies, then don't suggest redirects (they're only about dependencies).
                    if (FindDependencies)
                    {
                        // Build the table of suggested redirects. If we're auto-unifying, we want to output all the 
                        // assemblies that we auto-unified so that GenerateBindingRedirects can consume them, 
                        // not just the required ones for build to succeed
                        DependentAssembly[] remappings = AutoUnify ? autoUnifiedRemappedAssemblies : idealAssemblyRemappings;
                        AssemblyNameReference[] remappedReferences = AutoUnify ? autoUnifiedRemappedAssemblyReferences : idealAssemblyRemappingsIdentities;
                        PopulateSuggestedRedirects(remappings, remappedReferences);
                    }

                    bool useSystemRuntime = false;
                    foreach (var reference in dependencyTable.References.Keys)
                    {
                        if (string.Equals(SystemRuntimeAssemblyName, reference.Name, StringComparison.OrdinalIgnoreCase))
                        {
                            useSystemRuntime = true;
                            break;
                        }
                    }

                    if (!useSystemRuntime && !FindDependencies)
                    {
                        // when we are not producing the dependency graph look for direct dependencies of primary references.
                        foreach (var resolvedReference in dependencyTable.References.Values)
                        {
                            var rawDependencies = GetDependencies(resolvedReference, fileExists, getAssemblyMetadata);
                            if (rawDependencies != null)
                            {
                                foreach (var dependentReference in rawDependencies)
                                {
                                    if (string.Equals(SystemRuntimeAssemblyName, dependentReference.Name, StringComparison.OrdinalIgnoreCase))
                                    {
                                        useSystemRuntime = true;
                                        break;
                                    }
                                }
                            }

                            if (useSystemRuntime)
                            {
                                break;
                            }
                        }
                    }

                    this.DependsOnSystemRuntime = useSystemRuntime.ToString();

                    WriteStateFile();

                    // Save the new state out and put into the file exists if it is actually on disk.
                    if (_stateFile != null && fileExists(_stateFile))
                    {
                        _filesWritten.Add(new TaskItem(_stateFile));
                    }

                    // Log the results.
                    success = LogResults(dependencyTable, idealAssemblyRemappings, idealAssemblyRemappingsIdentities, generalResolutionExceptions);

                    DumpTargetProfileLists(installedAssemblyTableInfo, whiteListSubsetTableInfo, dependencyTable);

                    if (processorArchitecture != SystemProcessorArchitecture.None && _warnOrErrorOnTargetArchitectureMismatch != WarnOrErrorOnTargetArchitectureMismatchBehavior.None)
                    {
                        foreach (ITaskItem item in _resolvedFiles)
                        {
                            AssemblyNameExtension assemblyName = null;

                            if (fileExists(item.ItemSpec) && !Reference.IsFrameworkFile(item.ItemSpec, _targetFrameworkDirectories))
                            {
                                try
                                {
                                    assemblyName = getAssemblyName(item.ItemSpec);
                                }
                                catch (System.IO.FileLoadException)
                                {
                                    // Its pretty hard to get here, you need an assembly that contains a valid reference
                                    // to a dependent assembly that, in turn, throws a FileLoadException during GetAssemblyName.
                                    // Still it happened once, with an older version of the CLR. 

                                    // ...falling through and relying on the targetAssemblyName==null behavior below...
                                }
                                catch (System.IO.FileNotFoundException)
                                {
                                    // Its pretty hard to get here, also since we do a file existence check right before calling this method so it can only happen if the file got deleted between that check and this call.
                                }
                                catch (UnauthorizedAccessException)
                                {
                                }
                                catch (BadImageFormatException)
                                {
                                }
                            }

                            if (assemblyName != null)
                            {
                                SystemProcessorArchitecture assemblyArch = assemblyName.ProcessorArchitecture;

                                // If the assembly is MSIL or none it can work anywhere so there does not need to be any warning ect.
                                if (assemblyArch == SystemProcessorArchitecture.MSIL || assemblyArch == SystemProcessorArchitecture.None)
                                {
                                    continue;
                                }

                                if (processorArchitecture != assemblyArch)
                                {
                                    if (_warnOrErrorOnTargetArchitectureMismatch == WarnOrErrorOnTargetArchitectureMismatchBehavior.Error)
                                    {
                                        Log.LogErrorWithCodeFromResources("ResolveAssemblyReference.MismatchBetweenTargetedAndReferencedArch", ProcessorArchitectureToString(processorArchitecture), item.GetMetadata("OriginalItemSpec"), ProcessorArchitectureToString(assemblyArch));
                                    }
                                    else
                                    {
                                        Log.LogWarningWithCodeFromResources("ResolveAssemblyReference.MismatchBetweenTargetedAndReferencedArch", ProcessorArchitectureToString(processorArchitecture), item.GetMetadata("OriginalItemSpec"), ProcessorArchitectureToString(assemblyArch));
                                    }
                                }
                            }
                        }
                    }
                    return success && !Log.HasLoggedErrors;
                }
                catch (ArgumentException e)
                {
                    Log.LogErrorWithCodeFromResources("General.InvalidArgument", e.Message);
                }

                // InvalidParameterValueException is thrown inside RAR when we find a specific parameter
                // has an invalid value. It's then caught up here so that we can abort the task.
                catch (InvalidParameterValueException e)
                {
                    Log.LogErrorWithCodeFromResources(null, "", 0, 0, 0, 0,
                        "ResolveAssemblyReference.InvalidParameter", e.ParamName, e.ActualValue, e.Message);
                }
            }

            return success && !Log.HasLoggedErrors;
        }
 private bool LogResults(ReferenceTable dependencyTable, DependentAssembly[] idealAssemblyRemappings, AssemblyNameReference[] idealAssemblyRemappingsIdentities, ArrayList generalResolutionExceptions)
 {
     bool flag = true;
     using (new CodeMarkerStartEnd(CodeMarkerEvent.perfMSBuildRARLogResultsBegin, CodeMarkerEvent.perfMSBuildRARLogResultsEnd))
     {
         if (this.Silent)
         {
             return flag;
         }
         foreach (AssemblyNameExtension extension in dependencyTable.References.Keys)
         {
             string fullName = extension.FullName;
             Reference reference = dependencyTable.GetReference(extension);
             if (reference.IsPrimary && (!reference.IsConflictVictim || !reference.IsCopyLocal))
             {
                 this.LogReference(reference, fullName);
             }
         }
         foreach (AssemblyNameExtension extension2 in dependencyTable.References.Keys)
         {
             string fusionName = extension2.FullName;
             Reference reference2 = dependencyTable.GetReference(extension2);
             if (!reference2.IsPrimary && (!reference2.IsConflictVictim || !reference2.IsCopyLocal))
             {
                 this.LogReference(reference2, fusionName);
             }
         }
         foreach (AssemblyNameExtension extension3 in dependencyTable.References.Keys)
         {
             string str3 = extension3.FullName;
             Reference reference3 = dependencyTable.GetReference(extension3);
             if (reference3.IsConflictVictim)
             {
                 this.LogConflict(reference3, str3);
                 Reference conflictCandidate = dependencyTable.GetReference(reference3.ConflictVictorName);
                 this.LogReferenceDependenciesAndSourceItems(reference3.ConflictVictorName.FullName, conflictCandidate);
                 this.LogReferenceDependenciesAndSourceItems(str3, reference3);
             }
         }
         if (this.suggestedRedirects.Length > 0)
         {
             for (int i = 0; i < idealAssemblyRemappings.Length; i++)
             {
                 DependentAssembly assembly = idealAssemblyRemappings[i];
                 AssemblyName partialAssemblyName = assembly.PartialAssemblyName;
                 Reference reference5 = idealAssemblyRemappingsIdentities[i].reference;
                 for (int j = 0; j < assembly.BindingRedirects.Length; j++)
                 {
                     foreach (AssemblyNameExtension extension4 in reference5.GetConflictVictims())
                     {
                         Reference reference6 = dependencyTable.GetReference(extension4);
                         base.Log.LogMessageFromResources(MessageImportance.High, "ResolveAssemblyReference.ConflictRedirectSuggestion", new object[] { partialAssemblyName, extension4.Version, reference6.FullPath, assembly.BindingRedirects[j].NewVersion, reference5.FullPath });
                     }
                 }
             }
             base.Log.LogWarningWithCodeFromResources("ResolveAssemblyReference.SuggestedRedirects", new object[0]);
         }
         foreach (Exception exception in generalResolutionExceptions)
         {
             if (!(exception is InvalidReferenceAssemblyNameException))
             {
                 throw exception;
             }
             InvalidReferenceAssemblyNameException exception2 = (InvalidReferenceAssemblyNameException) exception;
             base.Log.LogWarningWithCodeFromResources("General.MalformedAssemblyName", new object[] { exception2.SourceItemSpec });
         }
     }
     return flag;
 }
Esempio n. 6
0
        /// <summary>
        /// Figure out the what the CopyLocal state of given assembly should be.
        /// </summary>
        /// <param name="assemblyName">The name of the assembly.</param>
        /// <param name="frameworkPaths">The framework paths.</param>
        /// <param name="targetProcessorArchitecture">Like x86 or IA64\AMD64.</param>
        /// <param name="getRuntimeVersion">Delegate to get runtime version.</param>
        /// <param name="targetedRuntimeVersion">The targeted runtime version.</param>
        /// <param name="fileExists">Delegate to check if a file exists.</param>
        /// <param name="getAssemblyPathInGac">Delegate to get the path to an assembly in the system GAC.</param>
        /// <param name="copyLocalDependenciesWhenParentReferenceInGac">if set to true, copy local dependencies when only parent reference in gac.</param>
        /// <param name="doNotCopyLocalIfInGac">If set to true, do not copy local a reference that exists in the GAC (legacy behavior).</param>
        /// <param name="referenceTable">The reference table.</param>
        internal void SetFinalCopyLocalState
        (
            AssemblyNameExtension assemblyName,
            string[] frameworkPaths,
            ProcessorArchitecture targetProcessorArchitecture,
            GetAssemblyRuntimeVersion getRuntimeVersion,
            Version targetedRuntimeVersion,
            FileExists fileExists,
            GetAssemblyPathInGac getAssemblyPathInGac,
            bool copyLocalDependenciesWhenParentReferenceInGac,
            bool doNotCopyLocalIfInGac,
            ReferenceTable referenceTable
        )
        {
            // If this item was unresolvable, then copy-local is false.
            if (IsUnresolvable)
            {
                _copyLocalState = CopyLocalState.NoBecauseUnresolved;
                return;
            }

            if (EmbedInteropTypes)
            {
                _copyLocalState = CopyLocalState.NoBecauseEmbedded;
                return;
            }

            // If this item was a conflict victim, then it should not be copy-local.
            if (IsConflictVictim)
            {
                _copyLocalState = CopyLocalState.NoBecauseConflictVictim;
                return;
            }

            // If this is a primary reference then see if there's a Private metadata on the source item
            if (IsPrimary)
            {
                bool found;
                bool result = MetadataConversionUtilities.TryConvertItemMetadataToBool
                    (
                        PrimarySourceItem,
                        ItemMetadataNames.privateMetadata,
                        out found
                    );

                if (found)
                {
                    _copyLocalState = result
                        ? CopyLocalState.YesBecauseReferenceItemHadMetadata
                        : CopyLocalState.NoBecauseReferenceItemHadMetadata;
                    return;
                }
            }
            else
            {
                // This is a dependency. If any primary reference that lead to this dependency
                // has Private=false, then this dependency should false too.
                bool privateTrueFound = false;
                bool privateFalseFound = false;
                foreach (DictionaryEntry entry in _sourceItems)
                {
                    bool found;
                    bool result = MetadataConversionUtilities.TryConvertItemMetadataToBool
                        (
                            (ITaskItem)entry.Value,
                            ItemMetadataNames.privateMetadata,
                            out found
                        );

                    if (found)
                    {
                        if (result)
                        {
                            privateTrueFound = true;

                            // Once we hit this once we know there will be no modification to CopyLocal state.
                            // so we can immediately...
                            break;
                        }
                        else
                        {
                            privateFalseFound = true;
                        }
                    }
                }

                if (privateFalseFound && !privateTrueFound)
                {
                    _copyLocalState = CopyLocalState.NoBecauseReferenceItemHadMetadata;
                    return;
                }
            }

            // If the item was determined to be an prereq assembly.
            if (IsPrerequisite && !UserRequestedSpecificFile)
            {
                _copyLocalState = CopyLocalState.NoBecausePrerequisite;
                return;
            }

            // Items in the frameworks directory shouldn't be copy-local
            if (IsFrameworkFile(_fullPath, frameworkPaths))
            {
                _copyLocalState = CopyLocalState.NoBecauseFrameworkFile;
                return;
            }

            // We are a dependency, check to see if all of our parent references have come from the GAC
            if (!IsPrimary && !copyLocalDependenciesWhenParentReferenceInGac)
            {
                // Did we discover a parent reference which was not found in the GAC
                bool foundSourceItemNotInGac = false;

                // Go through all of the parent source items and check to see if they were found in the GAC
                foreach (DictionaryEntry entry in _sourceItems)
                {
                    AssemblyNameExtension primaryAssemblyName = referenceTable.GetReferenceFromItemSpec((string)entry.Key);
                    Reference primaryReference = referenceTable.GetReference(primaryAssemblyName);

                    if (doNotCopyLocalIfInGac)
                    {
                        // Legacy behavior, don't copy local if the assembly is in the GAC at all
                        if (!primaryReference.FoundInGac.HasValue)
                        {
                            primaryReference.FoundInGac = !string.IsNullOrEmpty(getAssemblyPathInGac(primaryAssemblyName, targetProcessorArchitecture, getRuntimeVersion, targetedRuntimeVersion, fileExists, true, false));
                        }

                        if (!primaryReference.FoundInGac.Value)
                        {
                            foundSourceItemNotInGac = true;
                            break;
                        }
                    }
                    else
                    {
                    if (!primaryReference.ResolvedFromGac)
                    {
                        foundSourceItemNotInGac = true;
                        break;
                    }
                }
                }

                // All parent source items were found in the GAC.
                if (!foundSourceItemNotInGac)
                {
                    _copyLocalState = CopyLocalState.NoBecauseParentReferencesFoundInGAC;
                    return;
                }
            }

            if (doNotCopyLocalIfInGac)
            {
                // Legacy behavior, don't copy local if the assembly is in the GAC at all
                if (!FoundInGac.HasValue)
                {
                    FoundInGac = !string.IsNullOrEmpty(getAssemblyPathInGac(assemblyName, targetProcessorArchitecture, getRuntimeVersion, targetedRuntimeVersion, fileExists, true, false));
                }

                if (FoundInGac.Value)
                {
                    _copyLocalState = CopyLocalState.NoBecauseReferenceFoundInGAC;
                    return;
                }
            }

            if (ResolvedFromGac)
            {
                _copyLocalState = CopyLocalState.NoBecauseReferenceResolvedFromGAC;
                return;
            }

            //  It was resolved locally, so copy it.
            _copyLocalState = CopyLocalState.YesBecauseOfHeuristic;
        }
 internal bool Execute(Microsoft.Build.Shared.FileExists fileExists, Microsoft.Build.Shared.DirectoryExists directoryExists, Microsoft.Build.Tasks.GetDirectories getDirectories, GetAssemblyName getAssemblyName, GetAssemblyMetadata getAssemblyMetadata, GetRegistrySubKeyNames getRegistrySubKeyNames, GetRegistrySubKeyDefaultValue getRegistrySubKeyDefaultValue, GetLastWriteTime getLastWriteTime, GetAssemblyRuntimeVersion getRuntimeVersion, OpenBaseKey openBaseKey, CheckIfAssemblyInGac checkIfAssemblyIsInGac)
 {
     bool flag = true;
     CodeMarkerStartEnd end = new CodeMarkerStartEnd(CodeMarkerEvent.perfMSBuildResolveAssemblyReferenceBegin, CodeMarkerEvent.perfMSBuildResolveAssemblyReferenceEnd);
     try
     {
         FrameworkName targetFrameworkMoniker = null;
         if (!string.IsNullOrEmpty(this.targetedFrameworkMoniker))
         {
             targetFrameworkMoniker = new FrameworkName(this.targetedFrameworkMoniker);
         }
         Version targetedRuntimeVersion = this.SetTargetedRuntimeVersion(getRuntimeVersion);
         this.LogInputs();
         if (!this.VerifyInputConditions())
         {
             return false;
         }
         if (this.targetFrameworkDirectories != null)
         {
             for (int i = 0; i < this.targetFrameworkDirectories.Length; i++)
             {
                 this.targetFrameworkDirectories[i] = Microsoft.Build.Shared.FileUtilities.EnsureTrailingSlash(this.targetFrameworkDirectories[i]);
             }
         }
         AssemblyTableInfo[] assemblyTables = this.GetInstalledAssemblyTableInfo(this.ignoreDefaultInstalledAssemblyTables, this.installedAssemblyTables, new GetListPath(RedistList.GetRedistListPathsFromDisk), this.TargetFrameworkDirectories);
         AssemblyTableInfo[] whiteListAssemblyTableInfo = null;
         InstalledAssemblies installedAssemblies = null;
         RedistList redistList = null;
         if ((assemblyTables != null) && (assemblyTables.Length > 0))
         {
             redistList = RedistList.GetRedistList(assemblyTables);
         }
         Hashtable blackList = null;
         string subsetName = null;
         bool flag2 = !string.IsNullOrEmpty(this.ProfileName) && ((this.FullFrameworkFolders.Length > 0) || (this.FullFrameworkAssemblyTables.Length > 0));
         bool flag3 = false;
         if (((redistList != null) && (redistList.Count > 0)) || (flag2 || this.ShouldUseSubsetBlackList()))
         {
             if (!flag2 && this.ShouldUseSubsetBlackList())
             {
                 SubsetListFinder finder = new SubsetListFinder(this.targetFrameworkSubsets);
                 whiteListAssemblyTableInfo = this.GetInstalledAssemblyTableInfo(this.IgnoreDefaultInstalledAssemblySubsetTables, this.InstalledAssemblySubsetTables, new GetListPath(finder.GetSubsetListPathsFromDisk), this.TargetFrameworkDirectories);
                 if (((whiteListAssemblyTableInfo.Length > 0) && (redistList != null)) && (redistList.Count > 0))
                 {
                     blackList = redistList.GenerateBlackList(whiteListAssemblyTableInfo);
                 }
                 else
                 {
                     base.Log.LogWarningWithCodeFromResources("ResolveAssemblyReference.NoSubsetsFound", new object[0]);
                 }
                 if (blackList == null)
                 {
                     base.Log.LogWarningWithCodeFromResources("ResolveAssemblyReference.NoRedistAssembliesToGenerateExclusionList", new object[0]);
                 }
                 subsetName = GenerateSubSetName(this.targetFrameworkSubsets, this.installedAssemblySubsetTables);
                 flag3 = true;
             }
             else if (flag2)
             {
                 AssemblyTableInfo[] fullRedistAssemblyTableInfo = null;
                 RedistList fullFrameworkRedistList = null;
                 this.HandleProfile(assemblyTables, out fullRedistAssemblyTableInfo, out blackList, out fullFrameworkRedistList);
                 redistList = fullFrameworkRedistList;
                 whiteListAssemblyTableInfo = assemblyTables;
                 assemblyTables = fullRedistAssemblyTableInfo;
                 subsetName = this.profileName;
             }
             if ((redistList != null) && (redistList.Count > 0))
             {
                 installedAssemblies = new InstalledAssemblies(redistList);
             }
         }
         if (redistList != null)
         {
             for (int j = 0; j < redistList.Errors.Length; j++)
             {
                 Exception exception = redistList.Errors[j];
                 string str2 = redistList.ErrorFileNames[j];
                 base.Log.LogWarningWithCodeFromResources("ResolveAssemblyReference.InvalidInstalledAssemblyTablesFile", new object[] { str2, RedistList.RedistListFolder, exception.Message });
             }
             for (int k = 0; k < redistList.WhiteListErrors.Length; k++)
             {
                 Exception exception2 = redistList.WhiteListErrors[k];
                 string str3 = redistList.WhiteListErrorFileNames[k];
                 base.Log.LogWarningWithCodeFromResources("ResolveAssemblyReference.InvalidInstalledAssemblySubsetTablesFile", new object[] { str3, SubsetListFinder.SubsetListFolder, exception2.Message });
             }
         }
         this.ReadStateFile();
         this.cache.SetGetLastWriteTime(getLastWriteTime);
         this.cache.SetInstalledAssemblyInformation(assemblyTables);
         getAssemblyName = this.cache.CacheDelegate(getAssemblyName);
         getAssemblyMetadata = this.cache.CacheDelegate(getAssemblyMetadata);
         fileExists = this.cache.CacheDelegate(fileExists);
         getDirectories = this.cache.CacheDelegate(getDirectories);
         getRuntimeVersion = this.cache.CacheDelegate(getRuntimeVersion);
         this.projectTargetFramework = this.FrameworkVersionFromString(this.projectTargetFrameworkAsString);
         this.FilterBySubtypeAndTargetFramework();
         DependentAssembly[] idealRemappings = null;
         if (this.FindDependencies)
         {
             try
             {
                 idealRemappings = this.GetAssemblyRemappingsFromAppConfig();
             }
             catch (AppConfigException exception3)
             {
                 base.Log.LogErrorWithCodeFromResources(null, exception3.FileName, exception3.Line, exception3.Column, 0, 0, "ResolveAssemblyReference.InvalidAppConfig", new object[] { this.AppConfigFile, exception3.Message });
                 return false;
             }
         }
         System.Reflection.ProcessorArchitecture targetProcessorArchitecture = TargetProcessorArchitectureToEnumeration(this.targetProcessorArchitecture);
         if (checkIfAssemblyIsInGac == null)
         {
             checkIfAssemblyIsInGac = new CheckIfAssemblyInGac(this.CheckForAssemblyInGac);
         }
         ReferenceTable dependencyTable = new ReferenceTable(this.findDependencies, this.findSatellites, this.findSerializationAssemblies, this.findRelatedFiles, this.searchPaths, this.allowedAssemblyExtensions, this.relatedFileExtensions, this.candidateAssemblyFiles, this.targetFrameworkDirectories, installedAssemblies, targetProcessorArchitecture, fileExists, directoryExists, getDirectories, getAssemblyName, getAssemblyMetadata, getRegistrySubKeyNames, getRegistrySubKeyDefaultValue, openBaseKey, getRuntimeVersion, targetedRuntimeVersion, this.projectTargetFramework, targetFrameworkMoniker, base.Log, this.latestTargetFrameworkDirectories, this.copyLocalDependenciesWhenParentReferenceInGac, checkIfAssemblyIsInGac);
         ArrayList exceptions = new ArrayList();
         subsetName = flag3 ? subsetName : this.targetedFrameworkMoniker;
         bool flag4 = false;
         if (this.AutoUnify && this.FindDependencies)
         {
             dependencyTable.ComputeClosure(null, this.assemblyFiles, this.assemblyNames, exceptions);
             try
             {
                 flag4 = false;
                 if ((redistList != null) && (redistList.Count > 0))
                 {
                     flag4 = dependencyTable.MarkReferencesForExclusion(blackList);
                 }
             }
             catch (InvalidOperationException exception4)
             {
                 base.Log.LogErrorWithCodeFromResources("ResolveAssemblyReference.ProblemDeterminingFrameworkMembership", new object[] { exception4.Message });
                 return false;
             }
             if (flag4)
             {
                 dependencyTable.RemoveReferencesMarkedForExclusion(true, subsetName);
             }
             AssemblyNameReference[] referenceArray = null;
             dependencyTable.ResolveConflicts(out idealRemappings, out referenceArray);
         }
         dependencyTable.ComputeClosure(idealRemappings, this.assemblyFiles, this.assemblyNames, exceptions);
         try
         {
             flag4 = false;
             if ((redistList != null) && (redistList.Count > 0))
             {
                 flag4 = dependencyTable.MarkReferencesForExclusion(blackList);
             }
         }
         catch (InvalidOperationException exception5)
         {
             base.Log.LogErrorWithCodeFromResources("ResolveAssemblyReference.ProblemDeterminingFrameworkMembership", new object[] { exception5.Message });
             return false;
         }
         if (flag4)
         {
             dependencyTable.RemoveReferencesMarkedForExclusion(false, subsetName);
         }
         DependentAssembly[] assemblyArray2 = null;
         AssemblyNameReference[] conflictingReferences = null;
         dependencyTable.ResolveConflicts(out assemblyArray2, out conflictingReferences);
         dependencyTable.GetReferenceItems(out this.resolvedFiles, out this.resolvedDependencyFiles, out this.relatedFiles, out this.satelliteFiles, out this.serializationAssemblyFiles, out this.scatterFiles, out this.copyLocalFiles);
         if (this.FindDependencies)
         {
             this.PopulateSuggestedRedirects(assemblyArray2);
         }
         if (this.stateFile != null)
         {
             this.filesWritten.Add(new TaskItem(this.stateFile));
         }
         this.WriteStateFile();
         flag = this.LogResults(dependencyTable, assemblyArray2, conflictingReferences, exceptions);
         this.DumpTargetProfileLists(assemblyTables, whiteListAssemblyTableInfo, dependencyTable);
         return (flag && !base.Log.HasLoggedErrors);
     }
     catch (ArgumentException exception6)
     {
         base.Log.LogErrorWithCodeFromResources("General.InvalidArgument", new object[] { exception6.Message });
     }
     catch (InvalidParameterValueException exception7)
     {
         base.Log.LogErrorWithCodeFromResources(null, "", 0, 0, 0, 0, "ResolveAssemblyReference.InvalidParameter", new object[] { exception7.ParamName, exception7.ActualValue, exception7.Message });
     }
     finally
     {
         if (end != null)
         {
             end.Dispose();
         }
     }
     return (flag && !base.Log.HasLoggedErrors);
 }
Esempio n. 8
0
        /// <summary>
        ///Initialize the black list and use it to remove references from the reference table
        /// </summary>
        private void InitializeExclusionList(ReferenceTable referenceTable, AssemblyNameExtension[] assembliesForBlackList, out Hashtable blackList)
        {
            blackList = new Hashtable(StringComparer.OrdinalIgnoreCase);
            foreach (AssemblyNameExtension assemblyName in assembliesForBlackList)
            {
                blackList[assemblyName.FullName] = null;
            }

            referenceTable.MarkReferencesForExclusion(blackList);
            referenceTable.RemoveReferencesMarkedForExclusion(false, "Client");
        }
Esempio n. 9
0
 /// <summary>
 /// Verify the correct references are still in the references table and that references which are in the black list are not in the references table
 /// Also verify any expected warning messages are seen in the log.
 /// </summary>
 private static void VerifyReferenceTable(ReferenceTable referenceTable, MockEngine mockEngine, AssemblyNameExtension engineAssemblyName, AssemblyNameExtension dataAssemblyName, AssemblyNameExtension sqlclientAssemblyName, AssemblyNameExtension xmlAssemblyName, string warningMessage, string warningMessage2)
 {
     IDictionary<AssemblyNameExtension, Reference> table = referenceTable.References;
     Assert.Equal(3, table.Count); // "Expected there to be three elements in the hashtable"
     Assert.False(table.ContainsKey(sqlclientAssemblyName)); // "Expected to not find the sqlclientAssemblyName in the referenceList"
     Assert.True(table.ContainsKey(xmlAssemblyName)); // "Expected to find the xmlssemblyName in the referenceList"
     Assert.True(table.ContainsKey(dataAssemblyName)); // "Expected to find the dataAssemblyName in the referenceList"
     Assert.True(table.ContainsKey(engineAssemblyName)); // "Expected to find the engineAssemblyName in the referenceList"
     if (warningMessage != null)
     {
         mockEngine.AssertLogContains(warningMessage);
     }
     if (warningMessage2 != null)
     {
         mockEngine.AssertLogContains(warningMessage2);
     }
     table.Clear();
 }
Esempio n. 10
0
        /// <summary>
        /// Add a set of references and their names to the reference table.
        /// </summary>
        private static void AddReferencesToReferenceTable(ReferenceTable referenceTable, AssemblyNameExtension engineAssemblyName, AssemblyNameExtension dataAssemblyName, AssemblyNameExtension sqlclientAssemblyName, AssemblyNameExtension xmlAssemblyName, Reference enginePrimaryReference, Reference dataDependencyReference, Reference sqlDependencyReference, Reference xmlPrimaryReference)
        {
            Dictionary<AssemblyNameExtension, Reference> table = referenceTable.References;
            if (enginePrimaryReference != null)
            {
                table.Add(engineAssemblyName, enginePrimaryReference);
            }

            if (dataDependencyReference != null)
            {
                table.Add(dataAssemblyName, dataDependencyReference);
            }
            if (sqlDependencyReference != null)
            {
                table.Add(sqlclientAssemblyName, sqlDependencyReference);
            }

            if (xmlPrimaryReference != null)
            {
                table.Add(xmlAssemblyName, xmlPrimaryReference);
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Initialize the mock engine so we can look at the warning messages, also put the assembly name which is to be in the black list into the black list.
        /// Call remove references so that we can then validate the results.
        /// </summary>
        private void InitializeMockEngine(out ReferenceTable referenceTable, out MockEngine mockEngine, out ResolveAssemblyReference rar)
        {
            mockEngine = new MockEngine();
            rar = new ResolveAssemblyReference();
            rar.BuildEngine = mockEngine;

            referenceTable = MakeEmptyReferenceTable(rar.Log);
        }
Esempio n. 12
0
        /// <summary>
        /// Verify the correct references are still in the references table and that references which are in the black list are not in the references table
        /// Also verify any expected warning messages are seen in the log.
        /// </summary>
        private static void VerifyReferenceTable(ReferenceTable referenceTable, MockEngine mockEngine, AssemblyNameExtension engineAssemblyName, AssemblyNameExtension dataAssemblyName, AssemblyNameExtension sqlclientAssemblyName, AssemblyNameExtension xmlAssemblyName, string[] warningMessages)
        {
            Dictionary<AssemblyNameExtension, Reference> table = referenceTable.References;
            Assert.Equal(0, table.Count); // "Expected there to be zero elements in the hashtable"

            if (warningMessages != null)
            {
                foreach (string warningMessage in warningMessages)
                {
                    Console.Out.WriteLine("WarningMessageToAssert:" + warningMessages);
                    mockEngine.AssertLogContains(warningMessage);
                }
            }

            table.Clear();
        }
Esempio n. 13
0
 private static ReferenceTable MakeEmptyReferenceTable(TaskLoggingHelper log)
 {
     ReferenceTable referenceTable = new ReferenceTable(null, false, false, false, false, new string[0], null, null, null, null, null, null, ProcessorArchitecture.None, fileExists, null, null, null, null, null, null, null, null, null, new Version("4.0"), null, log, null, true, false, null, null, false, null, WarnOrErrorOnTargetArchitectureMismatchBehavior.None, false, false);
     return referenceTable;
 }
Esempio n. 14
0
        public void ReferenceTableDependentItemsInBlackList4()
        {
            ReferenceTable referenceTable = new ReferenceTable(null, false, false, false, false, new string[0], null, null, null, null, null, null, ProcessorArchitecture.None, fileExists, null, null, null, null, null, null, null, null, null, new Version("4.0"), null, null, null, true, false, null, null, false, null, WarnOrErrorOnTargetArchitectureMismatchBehavior.None, false, false);
            MockEngine mockEngine;
            ResolveAssemblyReference rar;
            Hashtable blackList;
            AssemblyNameExtension engineAssemblyName = new AssemblyNameExtension("Microsoft.Build.Engine, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
            AssemblyNameExtension dataAssemblyName = new AssemblyNameExtension("System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
            AssemblyNameExtension sqlclientAssemblyName = new AssemblyNameExtension("System.SqlClient, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
            AssemblyNameExtension xmlAssemblyName = new AssemblyNameExtension("System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
            Reference enginePrimaryReference;
            Reference dataDependencyReference;
            Reference sqlDependencyReference;
            Reference xmlPrimaryReference;

            GenerateNewReferences(out enginePrimaryReference, out dataDependencyReference, out sqlDependencyReference, out xmlPrimaryReference);

            ITaskItem taskItem = new TaskItem("Microsoft.Build.Engine");
            ITaskItem taskItem2 = new TaskItem("System.Xml");
            xmlPrimaryReference.MakePrimaryAssemblyReference(taskItem2, false, ".dll");
            enginePrimaryReference.MakePrimaryAssemblyReference(taskItem, false, ".dll");
            enginePrimaryReference.FullPath = "FullPath";
            xmlPrimaryReference.FullPath = "FullPath";
            dataDependencyReference.FullPath = "FullPath";
            sqlDependencyReference.FullPath = "FullPath";
            dataDependencyReference.MakeDependentAssemblyReference(enginePrimaryReference);
            dataDependencyReference.MakeDependentAssemblyReference(xmlPrimaryReference);
            sqlDependencyReference.MakeDependentAssemblyReference(dataDependencyReference);

            InitializeMockEngine(out referenceTable, out mockEngine, out rar);
            AddReferencesToReferenceTable(referenceTable, engineAssemblyName, dataAssemblyName, sqlclientAssemblyName, xmlAssemblyName, enginePrimaryReference, dataDependencyReference, sqlDependencyReference, xmlPrimaryReference);

            InitializeExclusionList(referenceTable, new AssemblyNameExtension[] { sqlclientAssemblyName }, out blackList);

            string subsetName = ResolveAssemblyReference.GenerateSubSetName(new string[] { "Client" }, null);
            string warningMessage = rar.Log.FormatResourceString("ResolveAssemblyReference.FailBecauseDependentAssemblyInExclusionList", taskItem.ItemSpec, sqlclientAssemblyName.FullName, subsetName);
            string warningMessage2 = rar.Log.FormatResourceString("ResolveAssemblyReference.FailBecauseDependentAssemblyInExclusionList", taskItem2.ItemSpec, sqlclientAssemblyName.FullName, subsetName);
            VerifyReferenceTable(referenceTable, mockEngine, engineAssemblyName, dataAssemblyName, sqlclientAssemblyName, xmlAssemblyName, new string[] { warningMessage, warningMessage2 });
        }
Esempio n. 15
0
        /// <summary>
        /// Generate a fake reference which has been resolved from the gac. We will use it to verify the creation of the exclusion list.
        /// </summary>
        /// <returns></returns>
        private ReferenceTable GenerateTableWithAssemblyFromTheGlobalLocation(string location)
        {
            ReferenceTable referenceTable = new ReferenceTable(null, false, false, false, false, new string[0], null, null, null, null, null, null, ProcessorArchitecture.None, fileExists, null, null, null, null, null, null, null, null, null, new Version("4.0"), null, null, null, true, false, null, null, false, null, WarnOrErrorOnTargetArchitectureMismatchBehavior.None, false, false);

            AssemblyNameExtension assemblyNameExtension = new AssemblyNameExtension(new AssemblyName("Microsoft.VisualStudio.Interopt, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"));
            TaskItem taskItem = new TaskItem("Microsoft.VisualStudio.Interopt, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

            Reference reference = new Reference(isWinMDFile, fileExists, getRuntimeVersion);
            reference.MakePrimaryAssemblyReference(taskItem, false, ".dll");
            // "Resolve the assembly from the gac"
            reference.FullPath = "c:\\Microsoft.VisualStudio.Interopt.dll";
            reference.ResolvedSearchPath = location;
            referenceTable.AddReference(assemblyNameExtension, reference);

            assemblyNameExtension = new AssemblyNameExtension(new AssemblyName("Team.System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"));
            taskItem = new TaskItem("Team, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

            reference = new Reference(isWinMDFile, fileExists, getRuntimeVersion);
            reference.MakePrimaryAssemblyReference(taskItem, false, ".dll");

            // "Resolve the assembly from the gac"
            reference.FullPath = "c:\\Team.System.dll";
            reference.ResolvedSearchPath = location;
            referenceTable.AddReference(assemblyNameExtension, reference);
            return referenceTable;
        }
 internal void SetFinalCopyLocalState(AssemblyNameExtension assemblyName, string[] frameworkPaths, ProcessorArchitecture targetProcessorArchitecture, GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntimeVersion, Microsoft.Build.Shared.FileExists fileExists, bool copyLocalDependenciesWhenParentReferenceInGac, ReferenceTable referenceTable, CheckIfAssemblyInGac checkIfAssemblyInGac)
 {
     if (this.IsUnresolvable)
     {
         this.copyLocalState = CopyLocalState.NoBecauseUnresolved;
     }
     else if (this.EmbedInteropTypes)
     {
         this.copyLocalState = CopyLocalState.NoBecauseEmbedded;
     }
     else if (this.IsConflictVictim)
     {
         this.copyLocalState = CopyLocalState.NoBecauseConflictVictim;
     }
     else
     {
         if (this.IsPrimary)
         {
             bool flag;
             bool flag2 = MetadataConversionUtilities.TryConvertItemMetadataToBool(this.PrimarySourceItem, "Private", out flag);
             if (flag)
             {
                 if (flag2)
                 {
                     this.copyLocalState = CopyLocalState.YesBecauseReferenceItemHadMetadata;
                     return;
                 }
                 this.copyLocalState = CopyLocalState.NoBecauseReferenceItemHadMetadata;
                 return;
             }
         }
         else
         {
             bool flag3 = false;
             bool flag4 = false;
             foreach (DictionaryEntry entry in this.sourceItems)
             {
                 bool flag5;
                 bool flag6 = MetadataConversionUtilities.TryConvertItemMetadataToBool((ITaskItem) entry.Value, "Private", out flag5);
                 if (flag5)
                 {
                     if (flag6)
                     {
                         flag3 = true;
                         break;
                     }
                     flag4 = true;
                 }
             }
             if (flag4 && !flag3)
             {
                 this.copyLocalState = CopyLocalState.NoBecauseReferenceItemHadMetadata;
                 return;
             }
         }
         if (this.IsPrerequisite && !this.UserRequestedSpecificFile)
         {
             this.copyLocalState = CopyLocalState.NoBecausePrerequisite;
         }
         else if (IsFrameworkFile(this.fullPath, frameworkPaths))
         {
             this.copyLocalState = CopyLocalState.NoBecauseFrameworkFile;
         }
         else
         {
             if (!this.FoundInGac.HasValue)
             {
                 bool flag7 = checkIfAssemblyInGac(assemblyName, targetProcessorArchitecture, getRuntimeVersion, targetedRuntimeVersion, fileExists);
                 this.FoundInGac = new bool?(flag7);
             }
             if (this.FoundInGac.Value)
             {
                 this.copyLocalState = CopyLocalState.NoBecauseReferenceFoundInGAC;
             }
             else
             {
                 if (!this.IsPrimary && !copyLocalDependenciesWhenParentReferenceInGac)
                 {
                     bool flag8 = false;
                     foreach (DictionaryEntry entry2 in this.sourceItems)
                     {
                         AssemblyNameExtension referenceFromItemSpec = referenceTable.GetReferenceFromItemSpec((string) entry2.Key);
                         Reference reference = referenceTable.GetReference(referenceFromItemSpec);
                         bool flag9 = false;
                         if (!reference.FoundInGac.HasValue)
                         {
                             flag9 = checkIfAssemblyInGac(referenceFromItemSpec, targetProcessorArchitecture, getRuntimeVersion, targetedRuntimeVersion, fileExists);
                             reference.FoundInGac = new bool?(flag9);
                         }
                         else
                         {
                             flag9 = reference.FoundInGac.Value;
                         }
                         if (!flag9)
                         {
                             flag8 = true;
                             break;
                         }
                     }
                     if (!flag8)
                     {
                         this.copyLocalState = CopyLocalState.NoBecauseParentReferencesFoundInGAC;
                         return;
                     }
                 }
                 this.copyLocalState = CopyLocalState.YesBecauseOfHeuristic;
             }
         }
     }
 }