/// <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;
        }
Esempio n. 2
0
        /// <summary>
        /// Construct.
        /// </summary>
        /// <param name="findDependencies">If true, then search for dependencies.</param>
        /// <param name="findSatellites">If true, then search for satellite files.</param>
        /// <param name="findSerializatoinAssemblies">If true, then search for serialization assembly files.</param>
        /// <param name="findRelatedFiles">If true, then search for related files.</param>
        /// <param name="searchPaths">Paths to search for dependent assemblies on.</param>
        /// <param name="candidateAssemblyFiles">List of literal assembly file names to be considered when SearchPaths has {CandidateAssemblyFiles}.</param>
        /// <param name="resolvedSDKItems">Resolved sdk items</param>
        /// <param name="frameworkPaths">Path to the FX.</param>
        /// <param name="installedAssemblies">Installed assembly XML tables.</param>
        /// <param name="targetProcessorArchitecture">Like x86 or IA64\AMD64, the processor architecture being targetted.</param>
        /// <param name="fileExists">Delegate used for checking for the existence of a file.</param>
        /// <param name="directoryExists">Delegate used for files.</param>
        /// <param name="getDirectories">Delegate used for getting directories.</param>
        /// <param name="getAssemblyName">Delegate used for getting assembly names.</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>
        internal ReferenceTable
        (
                      IBuildEngine buildEngine,
            bool findDependencies,
            bool findSatellites,
            bool findSerializationAssemblies,
            bool findRelatedFiles,
            string[] searchPaths,
            string[] allowedAssemblyExtensions,
            string[] relatedFileExtensions,
            string[] candidateAssemblyFiles,
            ITaskItem[] resolvedSDKItems,
            string[] frameworkPaths,
            InstalledAssemblies installedAssemblies,
            System.Reflection.ProcessorArchitecture targetProcessorArchitecture,
            FileExists fileExists,
            DirectoryExists directoryExists,
            GetDirectories getDirectories,
            GetAssemblyName getAssemblyName,
            GetAssemblyMetadata getAssemblyMetadata,
            GetRegistrySubKeyNames getRegistrySubKeyNames,
            GetRegistrySubKeyDefaultValue getRegistrySubKeyDefaultValue,
            OpenBaseKey openBaseKey,
            GetAssemblyRuntimeVersion getRuntimeVersion,
            Version targetedRuntimeVersion,
            Version projectTargetFramework,
            FrameworkNameVersioning targetFrameworkMoniker,
            TaskLoggingHelper log,
            string[] latestTargetFrameworkDirectories,
            bool copyLocalDependenciesWhenParentReferenceInGac,
            bool doNotCopyLocalIfInGac,
            GetAssemblyPathInGac getAssemblyPathInGac,
            IsWinMDFile isWinMDFile,
            bool ignoreVersionForFrameworkReferences,
            ReadMachineTypeFromPEHeader readMachineTypeFromPEHeader,
            WarnOrErrorOnTargetArchitectureMismatchBehavior warnOrErrorOnTargetArchitectureMismatch,
            bool ignoreFrameworkAttributeVersionMismatch,
            bool unresolveFrameworkAssembliesFromHigherFrameworks
        )
        {
            _buildEngine = buildEngine;
            _log = log;
            _findDependencies = findDependencies;
            _findSatellites = findSatellites;
            _findSerializationAssemblies = findSerializationAssemblies;
            _findRelatedFiles = findRelatedFiles;
            _frameworkPaths = frameworkPaths;
            _allowedAssemblyExtensions = allowedAssemblyExtensions;
            _relatedFileExtensions = relatedFileExtensions;
            _installedAssemblies = installedAssemblies;
            _targetProcessorArchitecture = targetProcessorArchitecture;
            _fileExists = fileExists;
            _directoryExists = directoryExists;
            _getDirectories = getDirectories;
            _getAssemblyName = getAssemblyName;
            _getAssemblyMetadata = getAssemblyMetadata;
            _getRuntimeVersion = getRuntimeVersion;
            _projectTargetFramework = projectTargetFramework;
            _targetedRuntimeVersion = targetedRuntimeVersion;
            _openBaseKey = openBaseKey;
            _targetFrameworkMoniker = targetFrameworkMoniker;
            _latestTargetFrameworkDirectories = latestTargetFrameworkDirectories;
            _copyLocalDependenciesWhenParentReferenceInGac = copyLocalDependenciesWhenParentReferenceInGac;
            _doNotCopyLocalIfInGac = doNotCopyLocalIfInGac;
            _getAssemblyPathInGac = getAssemblyPathInGac;
            _isWinMDFile = isWinMDFile;
            _readMachineTypeFromPEHeader = readMachineTypeFromPEHeader;
            _warnOrErrorOnTargetArchitectureMismatch = warnOrErrorOnTargetArchitectureMismatch;
            _ignoreFrameworkAttributeVersionMismatch = ignoreFrameworkAttributeVersionMismatch;

            // Set condition for when to check assembly version against the target framework version 
            _checkAssemblyVersionAgainstTargetFrameworkVersion = unresolveFrameworkAssembliesFromHigherFrameworks || ((_projectTargetFramework ?? ReferenceTable.s_targetFrameworkVersion_40) <= ReferenceTable.s_targetFrameworkVersion_40);

            // Convert the list of installed SDK's to a dictionary for faster lookup
            _resolvedSDKReferences = new Dictionary<string, ITaskItem>(StringComparer.OrdinalIgnoreCase);
            _ignoreVersionForFrameworkReferences = ignoreVersionForFrameworkReferences;


            if (resolvedSDKItems != null)
            {
                foreach (ITaskItem resolvedSDK in resolvedSDKItems)
                {
                    string sdkName = resolvedSDK.GetMetadata("SDKName");

                    if (sdkName.Length > 0)
                    {
                        if (!_resolvedSDKReferences.ContainsKey(sdkName))
                        {
                            _resolvedSDKReferences.Add(sdkName, resolvedSDK);
                        }
                        else
                        {
                            _resolvedSDKReferences[sdkName] = resolvedSDK;
                        }
                    }
                }
            }

            // Compile searchpaths into fast resolver array.
            _compiledSearchPaths = AssemblyResolution.CompileSearchPaths
                (
                    buildEngine,
                    searchPaths,
                    candidateAssemblyFiles,
                    targetProcessorArchitecture,
                    frameworkPaths,
                    fileExists,
                    getAssemblyName,
                    getRegistrySubKeyNames,
                    getRegistrySubKeyDefaultValue,
                    openBaseKey,
                    installedAssemblies,
                    getRuntimeVersion,
                    targetedRuntimeVersion,
                    getAssemblyPathInGac
                );
        }
Esempio n. 3
0
        /// <summary>
        /// Heuristic that first considers the current runtime path and then searches the base of that path for the given
        /// frameworks version.
        /// </summary>
        /// <owner>JomoF</owner>
        /// <param name="currentRuntimePath">The path to the runtime that is currently executing.</param>
        /// <param name="prefix">Should be something like 'v1.2' that indicates the runtime version we want.</param>
        /// <param name="frameworkVersion">Should be the full version number of the runtime version we want.</param>
        /// <param name="getDirectories">Delegate to method that can return filesystem entries.</param>
        /// <param name="useHeuristic">Whether we should fall back to a search heuristic if other searches fail.</param>
        /// <returns>Will return 'null' if there is no target frameworks on this machine.</returns>
        internal static string FindDotNetFrameworkPath
        (
            string currentRuntimePath,
            string prefix,
            GetDirectories getDirectories
        )
        {
            string leaf = Path.GetFileName(currentRuntimePath);
            if (leaf.StartsWith(prefix, StringComparison.Ordinal))
            {
                // If the current runtime starts with correct prefix, then this is the
                // runtime we want to use.
                return currentRuntimePath;
            }

            // We haven't managed to use exact methods to locate the FX, so
            // search for the correct path with a heuristic.
            string baseLocation = Path.GetDirectoryName(currentRuntimePath);
            string searchPattern = prefix + "*";
            string[] directories = getDirectories(baseLocation, searchPattern);

            if (directories.Length == 0)
            {
                // Couldn't find the path, return a null.
                return null;
            }

            // We don't care which one we choose, but we want to be predictible.
            // The intention here is to choose the alphabetical maximum.
            string max = directories[0];

            // the max.EndsWith condition: pre beta 2 versions of v3.5 have build number like v3.5.20111.  
            // This was removed in beta2
            // We should favor \v3.5 over \v3.5.xxxxx
            // versions previous to 2.0 have .xxxx version numbers.  3.0 and 3.5 do not.
            if (max.EndsWith(prefix, StringComparison.OrdinalIgnoreCase) != true )
            {
                for (int i = 1; i < directories.Length; ++i)
                {
                    if (directories[i].EndsWith(prefix, StringComparison.OrdinalIgnoreCase))
                    {
                        max = directories[i];
                        break;
                    }
                    else if (String.Compare(directories[i], max, StringComparison.OrdinalIgnoreCase) > 0)
                    {
                        max = directories[i];
                    }
                }
            }

            return max;
        }
        /// <summary>
        /// Heuristic that first considers the current runtime path and then searches the base of that path for the given
        /// frameworks version.
        /// </summary>
        /// <param name="currentRuntimePath">The path to the runtime that is currently executing.</param>
        /// <param name="prefix">Should be something like 'v1.2' that indicates the runtime version we want.</param>
        /// <param name="directoryExists">Delegate to method that can check for the existence of a file.</param>
        /// <param name="getDirectories">Delegate to method that can return filesystem entries.</param>
        /// <param name="architecture">.NET framework architecture</param>
        /// <returns>Will return 'null' if there is no target frameworks on this machine.</returns>
        internal static string FindDotNetFrameworkPath
        (
            string currentRuntimePath,
            string prefix,
            DirectoryExists directoryExists,
            GetDirectories getDirectories,
            DotNetFrameworkArchitecture architecture
        )
        {
            // If the COMPLUS variables are set, they override everything -- that's the directory we want.  
            string complusInstallRoot = Environment.GetEnvironmentVariable("COMPLUS_INSTALLROOT");
            string complusVersion = Environment.GetEnvironmentVariable("COMPLUS_VERSION");

            if (!String.IsNullOrEmpty(complusInstallRoot) && !String.IsNullOrEmpty(complusVersion))
            {
                return Path.Combine(complusInstallRoot, complusVersion);
            }

            // If the current runtime starts with correct prefix, then this is the runtime we want to use.
            // However, only if we're requesting current architecture -- otherwise, the base path may be different, so we'll need to look it up. 
            string leaf = Path.GetFileName(currentRuntimePath);
            if (leaf.StartsWith(prefix, StringComparison.Ordinal) && architecture == DotNetFrameworkArchitecture.Current)
            {
                return currentRuntimePath;
            }

            // We haven't managed to use exact methods to locate the FX, so
            // search for the correct path with a heuristic.
            string baseLocation = Path.GetDirectoryName(currentRuntimePath);
            string searchPattern = prefix + "*";

            int indexOfFramework64 = baseLocation.IndexOf("Framework64", StringComparison.OrdinalIgnoreCase);

            if (indexOfFramework64 != -1 && architecture == DotNetFrameworkArchitecture.Bitness32)
            {
                // need to get rid of just the 64, but want to look up 'Framework64' rather than '64' to avoid the case where 
                // the path is something like 'C:\MyPath\64\Framework64'.  9 = length of 'Framework', to make the index match 
                // the location of the '64'. 
                int indexOf64 = indexOfFramework64 + 9;
                string tempLocation = baseLocation;
                baseLocation = tempLocation.Substring(0, indexOf64) + tempLocation.Substring(indexOf64 + 2, tempLocation.Length - indexOf64 - 2);
            }
            else if (indexOfFramework64 == -1 && architecture == DotNetFrameworkArchitecture.Bitness64)
            {
                // need to add 64 -- since this is a heuristic, we assume that we just need to append.  
                baseLocation = baseLocation + "64";
            }
            // we don't need to do anything if it's DotNetFrameworkArchitecture.Current.  

            string[] directories;

            if (directoryExists(baseLocation))
            {
                directories = getDirectories(baseLocation, searchPattern);
            }
            else
            {
                // If we can't even find the base path, might as well give up now. 
                return null;
            }

            if (directories.Length == 0)
            {
                // Couldn't find the path, return a null.
                return null;
            }

            // We don't care which one we choose, but we want to be predictible.
            // The intention here is to choose the alphabetical maximum.
            string max = directories[0];

            // the max.EndsWith condition: pre beta 2 versions of v3.5 have build number like v3.5.20111.  
            // This was removed in beta2
            // We should favor \v3.5 over \v3.5.xxxxx
            // versions previous to 2.0 have .xxxx version numbers.  3.0 and 3.5 do not.
            if (!max.EndsWith(prefix, StringComparison.OrdinalIgnoreCase))
            {
                for (int i = 1; i < directories.Length; ++i)
                {
                    if (directories[i].EndsWith(prefix, StringComparison.OrdinalIgnoreCase))
                    {
                        max = directories[i];
                        break;
                    }
                    else if (String.Compare(directories[i], max, StringComparison.OrdinalIgnoreCase) > 0)
                    {
                        max = directories[i];
                    }
                }
            }

            return max;
        }
Esempio n. 5
0
 /// <summary>
 /// Cache the results of a GetDirectories delegate.
 /// </summary>
 /// <param name="getDirectoriesValue">The delegate.</param>
 /// <returns>Cached version of the delegate.</returns>
 internal GetDirectories CacheDelegate(GetDirectories getDirectoriesValue)
 {
     getDirectories = getDirectoriesValue;
     return(GetDirectories);
 }
Esempio n. 6
0
 /// <summary>
 /// Cache the results of a GetDirectories delegate. 
 /// </summary>
 /// <param name="getDirectories">The delegate.</param>
 /// <returns>Cached version of the delegate.</returns>
 internal GetDirectories CacheDelegate(GetDirectories getDirectoriesValue)
 {
     _getDirectories = getDirectoriesValue;
     return new GetDirectories(this.GetDirectories);
 }
Esempio n. 7
0
 /// <summary>
 /// Cache the results of a GetDirectories delegate.
 /// </summary>
 /// <param name="getDirectories">The delegate.</param>
 /// <returns>Cached version of the delegate.</returns>
 internal GetDirectories CacheDelegate(GetDirectories getDirectoriesValue)
 {
     _getDirectories = getDirectoriesValue;
     return(new GetDirectories(this.GetDirectories));
 }
Esempio n. 8
0
        internal static string FindDotNetFrameworkPath(string currentRuntimePath, string prefix, string frameworkVersion, DirectoryExists directoryExists, GetDirectories getDirectories, DotNetFrameworkArchitecture architecture, bool useHeuristic)
        {
            string[] strArray;
            if (Path.GetFileName(currentRuntimePath).StartsWith(prefix, StringComparison.Ordinal) && (architecture == DotNetFrameworkArchitecture.Current))
            {
                return(currentRuntimePath);
            }
            string str2 = null;

            if (architecture == DotNetFrameworkArchitecture.Current)
            {
                str2 = ConstructDotNetFrameworkPathFromRuntimeInfo(frameworkVersion);
            }
            if ((str2 != null) || !useHeuristic)
            {
                return(str2);
            }
            string directoryName = Path.GetDirectoryName(currentRuntimePath);
            string pattern       = prefix + "*";

            if (directoryName.Contains("64") && (architecture == DotNetFrameworkArchitecture.Bitness32))
            {
                int    index = directoryName.IndexOf("64", StringComparison.OrdinalIgnoreCase);
                string str5  = directoryName;
                directoryName = str5.Substring(0, index) + str5.Substring(index + 2, (str5.Length - index) - 2);
            }
            else if (!directoryName.Contains("64") && (architecture == DotNetFrameworkArchitecture.Bitness64))
            {
                directoryName = directoryName + "64";
            }
            if (directoryExists(directoryName))
            {
                strArray = getDirectories(directoryName, pattern);
            }
            else
            {
                return(null);
            }
            if (strArray.Length == 0)
            {
                return(null);
            }
            string strB = strArray[0];

            if (!strB.EndsWith(prefix, StringComparison.OrdinalIgnoreCase))
            {
                for (int i = 1; i < strArray.Length; i++)
                {
                    if (strArray[i].EndsWith(prefix, StringComparison.OrdinalIgnoreCase))
                    {
                        return(strArray[i]);
                    }
                    if (string.Compare(strArray[i], strB, StringComparison.OrdinalIgnoreCase) > 0)
                    {
                        strB = strArray[i];
                    }
                }
            }
            return(strB);
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            string url         = "ftp://waws-prod-dm1-127.ftp.azurewebsites.windows.net/bdat1001-10824";
            string directories = GetDirectories.GetDirectory(url);

            List <string>  studentDirectories = directories.Split("\r\n", StringSplitOptions.RemoveEmptyEntries).ToList();    //\r stands for carriage return and \n for new line feed, ToList creates a list.
            List <Student> students           = new List <Student>();


            foreach (var studentDirectory in studentDirectories)
            {
                string[] studentsInfo = studentDirectory.Split(" ", StringSplitOptions.None);
                Student  str_student1 = new Student();
                str_student1.StudentId = studentsInfo[0];
                str_student1.FirstName = studentsInfo[1];
                str_student1.LastName  = studentsInfo[2];
                Console.WriteLine($"{studentsInfo[0]}  { studentsInfo[1]}  { studentsInfo[2]}");        //to print the StudentId, FirstName and LastName from String Array named "studentsInfo"
                //students.Add(str_student);


                //Block below creates the JSON file at specified address on line 36
                //JSON Data per Student is Correct. PROBLEM = How to append the data??
                string filepath = $"{studentsInfo[0]}%20{ studentsInfo[1]}%20{ studentsInfo[2]}/info.csv";

                string username = @"bdat100119f\bdat1001";
                string password = "******";

                WebClient request = new WebClient();
                //string url = "ftp://waws-prod-dm1-127.ftp.azurewebsites.windows.net/bdat1001-10824/";
                request.Credentials = new NetworkCredential(username, password);

                try
                {
                    byte[] newFileData = request.DownloadData(url + filepath);
                    string fileString  = System.Text.Encoding.UTF8.GetString(newFileData);


                    Student info_student = new Student();
                    //string[] str_student = new string[];
                    List <string> line_str_student = fileString.Split("\r\n", StringSplitOptions.RemoveEmptyEntries).ToList();
                    string        infoData         = line_str_student[1];
                    List <string> str_student      = fileString.Split(",", StringSplitOptions.RemoveEmptyEntries).ToList();

                    info_student.StudentId       = str_student[0];
                    info_student.FirstName       = str_student[1];
                    info_student.LastName        = str_student[2];
                    info_student.Email           = str_student[3];
                    info_student.DateOfBirth     = str_student[4];
                    info_student.Title           = str_student[5];
                    info_student.PersonalWebsite = str_student[6];
                    info_student.FacebookUrl     = str_student[7];
                    info_student.InstagramUrl    = str_student[8];
                    info_student.TwitterUrl      = str_student[9];
                    info_student.LinkedInUrl     = str_student[10];
                    info_student.Description     = str_student[11];
                    if (info_student.StudentId == "200445936")
                    {
                        info_student.IsME = true;
                    }
                    else
                    {
                        info_student.IsME = false;
                    }
                    //Console.WriteLine($"{info_student.Description}  {info_student.Email}  {info_student.FacebookUrl}  {info_student.DateOfBirth}");
                    students.Add(info_student);
                }
                catch
                {
                    //Console.WriteLine(e.Message);
                    // Do something such as log error, but this is based on OP's original code
                    // so for now we do nothing.
                    throw;
                }

                //Read_File(filepath);
            }
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(students);

            using (StreamWriter sw = new StreamWriter(@"C:\Users\Manan\Desktop\student_info.json"))
            {
                sw.Write(json);
            }
        }