コード例 #1
0
        internal AssemblyFoldersExCache(AssemblyFoldersEx assemblyFoldersEx, FileExists fileExists)
        {
            AssemblyFoldersEx = assemblyFoldersEx;
            _fileExists       = fileExists;

            if (Environment.GetEnvironmentVariable("MSBUILDDISABLEASSEMBLYFOLDERSEXCACHE") != null)
            {
                _useOriginalFileExists = true;
            }
            else
            {
                var lockobject = new Object();

                Parallel.ForEach(assemblyFoldersEx.UniqueDirectoryPaths, assemblyFolder =>
                {
                    if (FileUtilities.DirectoryExistsNoThrow(assemblyFolder))
                    {
                        string[] files = Directory.GetFiles(assemblyFolder, "*.*", SearchOption.TopDirectoryOnly);

                        lock (lockobject)
                        {
                            foreach (string file in files)
                            {
                                _filesInDirectories.Add(file);
                            }
                        }
                    }
                });
            }
        }
コード例 #2
0
        /// <summary>
        /// Determine if an file is a winmd file or not.
        /// </summary>
        internal static bool IsWinMDFile(
            string fullPath,
            GetAssemblyRuntimeVersion getAssemblyRuntimeVersion,
            FileExists fileExists,
            out string imageRuntimeVersion,
            out bool isManagedWinmd)
        {
            imageRuntimeVersion = String.Empty;
            isManagedWinmd      = false;

            if (!NativeMethodsShared.IsWindows)
            {
                return(false);
            }

            // May be null or empty is the file was never resolved to a path on disk.
            if (!String.IsNullOrEmpty(fullPath) && fileExists(fullPath))
            {
                imageRuntimeVersion = getAssemblyRuntimeVersion(fullPath);
                if (!String.IsNullOrEmpty(imageRuntimeVersion))
                {
                    bool containsWindowsRuntime = imageRuntimeVersion.IndexOf(
                        "WindowsRuntime",
                        StringComparison.OrdinalIgnoreCase) >= 0;

                    if (containsWindowsRuntime)
                    {
                        isManagedWinmd = imageRuntimeVersion.IndexOf("CLR", StringComparison.OrdinalIgnoreCase) >= 0;
                        return(true);
                    }
                }
            }

            return(false);
        }
コード例 #3
0
        public void ValidateChecksNameIsSet()
        {
            var condition      = new FileExists();
            var validationMock = new Mock <IValidationLog>(MockBehavior.Strict);

            validationMock.Setup(vl => vl.AddError("FileName has not been set")).Verifiable();
            condition.Validate(validationMock.Object);
            validationMock.Verify();
        }
コード例 #4
0
ファイル: Resolver.cs プロジェクト: cameron314/msbuild
 /// <summary>
 /// Construct.
 /// </summary>
 protected Resolver(string searchPathElement, GetAssemblyName getAssemblyName, FileExists fileExists, GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntimeVesion, ProcessorArchitecture targetedProcessorArchitecture, bool compareProcessorArchitecture)
 {
     this.searchPathElement = searchPathElement;
     this.getAssemblyName = getAssemblyName;
     this.fileExists = fileExists;
     this.getRuntimeVersion = getRuntimeVersion;
     this.targetedRuntimeVersion = targetedRuntimeVesion;
     this.targetProcessorArchitecture = targetedProcessorArchitecture;
     this.compareProcessorArchitecture = compareProcessorArchitecture;
 }
コード例 #5
0
ファイル: Resolver.cs プロジェクト: yxbdali/msbuild
 /// <summary>
 /// Construct.
 /// </summary>
 protected Resolver(string searchPathElement, GetAssemblyName getAssemblyName, FileExists fileExists, GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntimeVesion, ProcessorArchitecture targetedProcessorArchitecture, bool compareProcessorArchitecture)
 {
     this.searchPathElement            = searchPathElement;
     this.getAssemblyName              = getAssemblyName;
     this.fileExists                   = fileExists;
     this.getRuntimeVersion            = getRuntimeVersion;
     this.targetedRuntimeVersion       = targetedRuntimeVesion;
     this.targetProcessorArchitecture  = targetedProcessorArchitecture;
     this.compareProcessorArchitecture = compareProcessorArchitecture;
 }
コード例 #6
0
 /// <summary>
 /// Construct.
 /// </summary>
 public AssemblyFoldersFromConfigResolver(string searchPathElement, GetAssemblyName getAssemblyName,
                                          FileExists fileExists, GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntimeVesion,
                                          ProcessorArchitecture targetProcessorArchitecture, bool compareProcessorArchitecture,
                                          IBuildEngine buildEngine, TaskLoggingHelper log)
     : base(
         searchPathElement, getAssemblyName, fileExists, getRuntimeVersion, targetedRuntimeVesion,
         targetProcessorArchitecture, compareProcessorArchitecture)
 {
     _buildEngine = buildEngine as IBuildEngine4;
     _taskLogger  = log;
 }
コード例 #7
0
 /// <summary>
 /// Construct.
 /// </summary>
 public AssemblyFoldersFromConfigResolver(string searchPathElement, GetAssemblyName getAssemblyName,
     FileExists fileExists, GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntimeVesion,
     ProcessorArchitecture targetProcessorArchitecture, bool compareProcessorArchitecture,
     IBuildEngine buildEngine, TaskLoggingHelper log)
     : base(
         searchPathElement, getAssemblyName, fileExists, getRuntimeVersion, targetedRuntimeVesion,
         targetProcessorArchitecture, compareProcessorArchitecture)
 {
     _buildEngine = buildEngine as IBuildEngine4;
     _taskLogger = log;
 }
コード例 #8
0
        public void negative_test()
        {
            var log = new PackageLog();

            var file        = Guid.NewGuid().ToString() + ".txt";
            var requirement = new FileExists(file);

            requirement.Check(log);

            log.Success.ShouldBeFalse();
            log.FullTraceText().ShouldContain("File '{0}' does not exist!".ToFormat(file));
        }
コード例 #9
0
        public async Task FileNotExistsTest()
        {
            var widget = new FileExists
            {
                Path = "",
            };

            var request = HealthCheckRequest.Create(widget);

            await new FileExistsCheck().Handle(request, CancellationToken.None).ConfigureAwait(false);

            Assert.AreEqual(State.Failed, widget.State);
        }
コード例 #10
0
        public void positive_test()
        {
            new FileSystem().WriteStringToFile("file.txt", "anything");

            var log = new PackageLog();

            var requirement = new FileExists("file.txt");

            requirement.Check(log);

            log.Success.ShouldBeTrue();
            log.FullTraceText().ShouldContain("File 'file.txt' exists");
        }
コード例 #11
0
        public async Task FileExistsTest()
        {
            var widget = new FileExists
            {
                Path = Assembly.GetExecutingAssembly().Location,
            };

            var request = HealthCheckRequest.Create(widget);

            await new FileExistsCheck().Handle(request, CancellationToken.None).ConfigureAwait(false);

            Assert.AreEqual(State.Ok, widget.State);
        }
コード例 #12
0
        public void EvaluateReturnsResultOfFileCheck()
        {
            var fileSystemMock = new Mock <IFileSystem>(MockBehavior.Strict);

            fileSystemMock.Setup(fs => fs.CheckIfFileExists("c:\\test.xml")).Returns(true);
            var condition = new FileExists
            {
                FileName   = "c:\\test.xml",
                FileSystem = fileSystemMock.Object
            };
            var contextMock = new Mock <TaskExecutionContext>(new TaskExecutionParameters());
            var result      = condition.Evaluate(contextMock.Object);

            Assert.IsTrue(result);
        }
コード例 #13
0
 /// <summary>
 /// Given a strong name, find its path in the GAC.
 /// </summary>
 /// <param name="strongName">The strong name.</param>
 /// <param name="targetProcessorArchitecture">Like x86 or IA64\AMD64.</param>
 /// <param name="getRuntimeVersion">Delegate to get the runtime version from a file path</param>
 /// <param name="targetedRuntimeVersion">What version of the runtime are we targeting</param>
 /// <param name="fullFusionName">Are we guranteed to have a full fusion name. This really can only happen if we have already resolved the assembly</param>
 /// <returns>The path to the assembly. Empty if none exists.</returns>
 internal static string GetLocation
 (
     AssemblyNameExtension strongName,
     ProcessorArchitecture targetProcessorArchitecture,
     GetAssemblyRuntimeVersion getRuntimeVersion,
     Version targetedRuntimeVersion,
     bool fullFusionName,
     FileExists fileExists,
     GetPathFromFusionName getPathFromFusionName,
     GetGacEnumerator getGacEnumerator,
     bool specificVersion
 )
 {
     return(GetLocation(null, strongName, targetProcessorArchitecture, getRuntimeVersion, targetedRuntimeVersion, fullFusionName, fileExists, getPathFromFusionName, getGacEnumerator, specificVersion));
 }
コード例 #14
0
        internal ResolveNuGetPackageAssets(FileExists fileExists, TryGetRuntimeVersion tryGetRuntimeVersion)
            : this()
        {
            if (fileExists != null)
            {
                _fileExists = fileExists;
            }

            if (tryGetRuntimeVersion != null)
            {
                _tryGetRuntimeVersion = tryGetRuntimeVersion;
            }

            _reportExceptionsToMSBuildLogger = false;
        }
コード例 #15
0
        public ModelGenerator(FileExists p_FileExists, string p_NameSpace,
            bool p_MakePartial, bool p_PropChange, bool p_Validate)
        {
            _FileExists = p_FileExists;
            _NameSpace = p_NameSpace;
            _MakePartial = p_MakePartial;
            _PropChange = p_PropChange;
            _EnableValidationAttributes = p_Validate;
            _fhResult = FileHandlingResult.None;

            // Initialize NVelocity
            engine = new VelocityEngine();
            ExtendedProperties props = new ExtendedProperties();
            props.AddProperty("file.resource.loader.path", new ArrayList(new string[] { ".", @".\Templates" }));
            engine.Init(props);
        }
コード例 #16
0
        /// <summary>
        /// Build a resolver array from a set of directories to resolve directly from.
        /// </summary>
        /// <param name="directories"></param>
        /// <param name="fileExists"></param>
        /// <param name="getAssemblyName"></param>
        /// <returns></returns>
        internal static Resolver[] CompileDirectories
        (
            IEnumerable <string> directories,
            FileExists fileExists,
            GetAssemblyName getAssemblyName,
            GetAssemblyRuntimeVersion getRuntimeVersion,
            Version targetedRuntimeVersion
        )
        {
            List <Resolver> resolvers = new List <Resolver>();

            foreach (string directory in directories)
            {
                resolvers.Add(new DirectoryResolver(directory, getAssemblyName, fileExists, getRuntimeVersion, targetedRuntimeVersion));
            }
            return(resolvers.ToArray());
        }
コード例 #17
0
        public ModelGenerator(FileExists p_FileExists, string p_NameSpace,
                              bool p_MakePartial, bool p_PropChange, bool p_Validate)
        {
            _FileExists  = p_FileExists;
            _NameSpace   = p_NameSpace;
            _MakePartial = p_MakePartial;
            _PropChange  = p_PropChange;
            _EnableValidationAttributes = p_Validate;
            _fhResult = FileHandlingResult.None;

            // Initialize NVelocity
            engine = new VelocityEngine();
            ExtendedProperties props = new ExtendedProperties();

            props.AddProperty("file.resource.loader.path", new ArrayList(new string[] { ".", @".\Templates" }));
            engine.Init(props);
        }
コード例 #18
0
        public void positive_test_with_generic()
        {
            new FileSystem().WriteStringToFile("file.txt", "anything");
            var settings = new FileSettings
            {
                File = "file.txt"
            };

            var log = new PackageLog();

            var requirement = new FileExists <FileSettings>(x => x.File, settings);

            requirement.Check(log);

            log.Success.ShouldBeTrue();
            log.FullTraceText().ShouldContain("File 'file.txt' defined by FileSettings.File exists");
        }
コード例 #19
0
        /// <summary>
        /// Build a resolver array from a set of directories to resolve directly from.
        /// </summary>
        internal static Resolver[] CompileDirectories
        (
            List <string> directories,
            FileExists fileExists,
            GetAssemblyName getAssemblyName,
            GetAssemblyRuntimeVersion getRuntimeVersion,
            Version targetedRuntimeVersion
        )
        {
            var resolvers = new Resolver[directories.Count];

            for (int i = 0; i < directories.Count; i++)
            {
                resolvers[i] = new DirectoryResolver(directories[i], getAssemblyName, fileExists, getRuntimeVersion, targetedRuntimeVersion);
            }

            return(resolvers);
        }
コード例 #20
0
        public void negative_test_with_settings()
        {
            var log = new PackageLog();

            var file     = Guid.NewGuid().ToString() + ".txt";
            var settings = new FileSettings
            {
                File = file
            };

            var requirement = new FileExists <FileSettings>(x => x.File, settings);


            requirement.Check(log);

            log.Success.ShouldBeFalse();
            log.FullTraceText().ShouldContain("File '{0}' defined by FileSettings.File does not exist!".ToFormat(file));
        }
コード例 #21
0
        internal PrereleaseResolveNuGetPackageAssets(DirectoryExists directoryExists, FileExists fileExists, TryGetRuntimeVersion tryGetRuntimeVersion)
            : this()
        {
            if (directoryExists != null)
            {
                _directoryExists = directoryExists;
            }

            if (fileExists != null)
            {
                _fileExists = fileExists;
            }

            if (tryGetRuntimeVersion != null)
            {
                _tryGetRuntimeVersion = tryGetRuntimeVersion;
            }
        }
コード例 #22
0
        internal PrereleaseResolveNuGetPackageAssets(DirectoryExists directoryExists, FileExists fileExists, TryGetRuntimeVersion tryGetRuntimeVersion)
            : this()
        {
            if (directoryExists != null)
            {
                _directoryExists = directoryExists;
            }

            if (fileExists != null)
            {
                _fileExists = fileExists;
            }

            if (tryGetRuntimeVersion != null)
            {
                _tryGetRuntimeVersion = tryGetRuntimeVersion;
            }
        }
コード例 #23
0
ファイル: ModelGenerator.cs プロジェクト: daowzq/ExtFrame
        public ModelGenerator(FileExists p_FileExists, string p_NameSpace, bool p_MakePartial, bool p_PropChange, bool p_Validate)
        {
            this._FileExists  = p_FileExists;
            this._NameSpace   = p_NameSpace;
            this._MakePartial = p_MakePartial;
            this._PropChange  = p_PropChange;
            this._EnableValidationAttributes = p_Validate;
            this._fhResult = FileHandlingResult.None;
            this.engine    = new VelocityEngine();
            ExtendedProperties extendedProperties = new ExtendedProperties();

            extendedProperties.AddProperty("file.resource.loader.path", new ArrayList(new string[]
            {
                ".",
                ".\\Templates"
            }));
            this.engine.Init(extendedProperties);
        }
コード例 #24
0
ファイル: FileUtil.cs プロジェクト: huannguyenfit/MeGUI
        /// <summary>
        /// Generates a unique filename by adding numbers to the filename.
        /// </summary>
        /// <param name="original"></param>
        /// <param name="fileExists"></param>
        /// <returns></returns>
        public static string getUniqueFilename(string original, FileExists fileExists)
        {
            if (!fileExists(original))
            {
                return(original);
            }
            string prefix = Path.Combine(Path.GetDirectoryName(original),
                                         Path.GetFileNameWithoutExtension(original)) + "_";
            string suffix = Path.GetExtension(original);

            for (int i = 0; true; i++)
            {
                string filename = prefix + i + suffix;
                if (!fileExists(filename))
                {
                    return(filename);
                }
            }
        }
コード例 #25
0
        /// <summary>
        /// Constructor
        /// </summary>
        internal AssemblyFoldersFromConfigCache(AssemblyFoldersFromConfig assemblyFoldersFromConfig, FileExists fileExists)
        {
            AssemblyFoldersFromConfig = assemblyFoldersFromConfig;
            _fileExists = fileExists;

            if (Environment.GetEnvironmentVariable("MSBUILDDISABLEASSEMBLYFOLDERSEXCACHE") != null)
            {
                _useOriginalFileExists = true;
            }
            else
            {
                _filesInDirectories = assemblyFoldersFromConfig.AsParallel()
                    .Where(assemblyFolder => FileUtilities.DirectoryExistsNoThrow(assemblyFolder.DirectoryPath))
                    .SelectMany(
                        assemblyFolder =>
                            Directory.GetFiles(assemblyFolder.DirectoryPath, "*.*", SearchOption.TopDirectoryOnly))
                    .ToImmutableHashSet(StringComparer.OrdinalIgnoreCase);
            }
        }
コード例 #26
0
        /// <summary>
        /// Constructor
        /// </summary>
        internal AssemblyFoldersFromConfigCache(AssemblyFoldersFromConfig assemblyFoldersFromConfig, FileExists fileExists)
        {
            AssemblyFoldersFromConfig = assemblyFoldersFromConfig;
            _fileExists = fileExists;

            if (Environment.GetEnvironmentVariable("MSBUILDDISABLEASSEMBLYFOLDERSEXCACHE") != null)
            {
                _useOriginalFileExists = true;
            }
            else
            {
                _filesInDirectories = assemblyFoldersFromConfig.AsParallel()
                                      .Where(assemblyFolder => FileUtilities.DirectoryExistsNoThrow(assemblyFolder.DirectoryPath))
                                      .SelectMany(
                    assemblyFolder =>
                    Directory.GetFiles(assemblyFolder.DirectoryPath, "*.*", SearchOption.TopDirectoryOnly))
                                      .ToImmutableHashSet(StringComparer.OrdinalIgnoreCase);
            }
        }
コード例 #27
0
        internal PrereleaseResolveNuGetPackageAssets(DirectoryExists directoryExists, FileExists fileExists, TryGetRuntimeVersion tryGetRuntimeVersion)
            : this()
        {
            if (directoryExists != null)
            {
                _directoryExists = directoryExists;
            }

            if (fileExists != null)
            {
                _fileExists = fileExists;
            }

            if (tryGetRuntimeVersion != null)
            {
                _tryGetRuntimeVersion = tryGetRuntimeVersion;
            }

            _reportExceptionsToMSBuildLogger = false;
        }
コード例 #28
0
        internal PrereleaseResolveNuGetPackageAssets(DirectoryExists directoryExists, FileExists fileExists, TryGetRuntimeVersion tryGetRuntimeVersion)
            : this()
        {
            if (directoryExists != null)
            {
                _directoryExists = directoryExists;
            }

            if (fileExists != null)
            {
                _fileExists = fileExists;
            }

            if (tryGetRuntimeVersion != null)
            {
                _tryGetRuntimeVersion = tryGetRuntimeVersion;
            }

            _reportExceptionsToMSBuildLogger = false;
        }
コード例 #29
0
        /// <summary>
        /// Given a strong name, find its path in the GAC.
        /// </summary>
        /// <param name="strongName">The strong name.</param>
        /// <param name="targetProcessorArchitecture">Like x86 or IA64\AMD64.</param>
        /// <returns>The path to the assembly. Empty if none exists.</returns>
        private static string GetLocationImpl(AssemblyNameExtension assemblyName, string targetProcessorArchitecture, GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntime, FileExists fileExists, GetPathFromFusionName getPathFromFusionName, GetGacEnumerator getGacEnumerator, bool specificVersion)
        {
            // Extra checks for PInvoke-destined data.
            ErrorUtilities.VerifyThrowArgumentNull(assemblyName, "assemblyName");
            ErrorUtilities.VerifyThrow(assemblyName.FullName != null, "Got a null assembly name fullname.");

            string strongName = assemblyName.FullName;

            if (targetProcessorArchitecture != null && !assemblyName.HasProcessorArchitectureInFusionName)
            {
                strongName += ", ProcessorArchitecture=" + targetProcessorArchitecture;
            }

            string assemblyPath = String.Empty;

            // Dictionary sorted by Version in reverse order, this will give the values enumeration the highest runtime version first.
            SortedDictionary<Version, SortedDictionary<AssemblyNameExtension, string>> assembliesByRuntime = GenerateListOfAssembliesByRuntime(strongName, getRuntimeVersion, targetedRuntime, fileExists, getPathFromFusionName, getGacEnumerator, specificVersion);
            if (assembliesByRuntime != null)
            {
                foreach (SortedDictionary<AssemblyNameExtension, string> runtimeBucket in assembliesByRuntime.Values)
                {
                    // Grab the first element if there are one or more elements. This will give us the highest version assembly name.
                    if (runtimeBucket.Count > 0)
                    {
                        foreach (KeyValuePair<AssemblyNameExtension, string> kvp in runtimeBucket)
                        {
                            assemblyPath = kvp.Value;
                            break;
                        }

                        if (!String.IsNullOrEmpty(assemblyPath))
                        {
                            break;
                        }
                    }
                }
            }

            return assemblyPath;
        }
コード例 #30
0
ファイル: Miscellaneous.cs プロジェクト: nikson/msbuild
        public void VerifyFrameworkFileMetadataFiles()
        {
            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.BuildEngine = new MockEngine();

            t.Assemblies = new ITaskItem[]
            {
                // In framework directory and redist, should have metadata
                new TaskItem("Microsoft.Build.Engine"),
                new TaskItem("System.Xml"),
                // In framework directory, should have metadata
                new TaskItem("B"),
                // Not in framework directory but in redist, should have metadata
                new TaskItem("C"),
                // Not in framework directory and not in redist, should not have metadata
                new TaskItem("D")
            };

            t.SearchPaths = new string[]
            {
                @"{TargetFrameworkDirectory}",
                @"c:\Somewhere\"
            };
            t.TargetFrameworkDirectories = new string[] { @"r:\WINDOWS\Microsoft.NET\Framework\v2.0.myfx" };

            FileExists cachedFileExists = fileExists;
            GetAssemblyName cachedGetAssemblyName = getAssemblyName;

            // Create a redist list which will contains both of the assemblies to search for
            string redistListContents =
                "<FileList Redist='Microsoft-Windows-CLRCoreComp' >" +
                "<File AssemblyName='System.Xml' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' />" +
                "<File AssemblyName='Microsoft.Build.Engine' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' />" +
                "<File AssemblyName='C' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' />" +
                "</FileList >";

            string redistFile = FileUtilities.GetTemporaryFile();
            File.WriteAllText(redistFile, redistListContents);

            bool success = false;
            try
            {
                fileExists = new FileExists(delegate (string path)
                {
                    if (String.Equals(path, @"r:\WINDOWS\Microsoft.NET\Framework\v2.0.myfx\Microsoft.Build.Engine.dll", StringComparison.OrdinalIgnoreCase) ||
                        String.Equals(path, @"r:\WINDOWS\Microsoft.NET\Framework\v2.0.myfx\System.Xml.dll", StringComparison.OrdinalIgnoreCase) ||
                        String.Equals(path, @"r:\WINDOWS\Microsoft.NET\Framework\v2.0.myfx\B.dll", StringComparison.OrdinalIgnoreCase) ||
                        String.Equals(path, @"c:\somewhere\c.dll", StringComparison.OrdinalIgnoreCase) ||
                        String.Equals(path, @"c:\somewhere\d.dll", StringComparison.OrdinalIgnoreCase) ||
                        path.EndsWith("RarCache", StringComparison.OrdinalIgnoreCase))
                    {
                        return true;
                    }
                    return false;
                });

                getAssemblyName = new GetAssemblyName(delegate (string path)
                {
                    if (String.Equals(path, @"r:\WINDOWS\Microsoft.NET\Framework\v2.0.myfx\B.dll", StringComparison.OrdinalIgnoreCase))
                    {
                        return new AssemblyNameExtension("B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                    }

                    if (String.Equals(path, @"c:\somewhere\d.dll", StringComparison.OrdinalIgnoreCase))
                    {
                        return new AssemblyNameExtension("D, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                    }

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

                success = Execute(t);
            }
            finally
            {
                fileExists = cachedFileExists;
                getAssemblyName = cachedGetAssemblyName;
                File.Delete(redistFile);
            }

            Assert.True(success); // "Expected no errors."
            Assert.Equal(5, t.ResolvedFiles.Length); // "Expected two resolved assemblies."
            Assert.True(t.ResolvedFiles.Where(Item => Item.GetMetadata("OriginalItemSpec").Equals("Microsoft.Build.Engine", StringComparison.OrdinalIgnoreCase)).First().GetMetadata("FrameworkFile").Equals("True", StringComparison.OrdinalIgnoreCase));
            Assert.True(t.ResolvedFiles.Where(Item => Item.GetMetadata("OriginalItemSpec").Equals("System.Xml", StringComparison.OrdinalIgnoreCase)).First().GetMetadata("FrameworkFile").Equals("True", StringComparison.OrdinalIgnoreCase));
            Assert.True(t.ResolvedFiles.Where(Item => Item.GetMetadata("OriginalItemSpec").Equals("B", StringComparison.OrdinalIgnoreCase)).First().GetMetadata("FrameworkFile").Equals("True", StringComparison.OrdinalIgnoreCase));
            Assert.True(t.ResolvedFiles.Where(Item => Item.GetMetadata("OriginalItemSpec").Equals("C", StringComparison.OrdinalIgnoreCase)).First().GetMetadata("FrameworkFile").Equals("True", StringComparison.OrdinalIgnoreCase));
            Assert.Equal(0, t.ResolvedFiles.Where(Item => Item.GetMetadata("OriginalItemSpec").Equals("D", StringComparison.OrdinalIgnoreCase)).First().GetMetadata("FrameworkFile").Length);
        }
コード例 #31
0
        /// <summary>
        /// Given a strong name, find its path in the GAC.
        /// </summary>
        /// <param name="strongName">The strong name.</param>
        /// <param name="targetProcessorArchitecture">Like x86 or IA64\AMD64.</param>
        /// <returns>The path to the assembly. Empty if none exists.</returns>
        private static string GetLocationImpl(AssemblyNameExtension assemblyName, string targetProcessorArchitecture, GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntime, FileExists fileExists, GetPathFromFusionName getPathFromFusionName, GetGacEnumerator getGacEnumerator, bool specificVersion)
        {
            // Extra checks for PInvoke-destined data.
            ErrorUtilities.VerifyThrowArgumentNull(assemblyName, "assemblyName");
            ErrorUtilities.VerifyThrow(assemblyName.FullName != null, "Got a null assembly name fullname.");

            string strongName = assemblyName.FullName;

            if (targetProcessorArchitecture != null && !assemblyName.HasProcessorArchitectureInFusionName)
            {
                strongName += ", ProcessorArchitecture=" + targetProcessorArchitecture;
            }

            string assemblyPath = String.Empty;

            // Dictionary sorted by Version in reverse order, this will give the values enumeration the highest runtime version first.
            SortedDictionary <Version, SortedDictionary <AssemblyNameExtension, string> > assembliesByRuntime = GenerateListOfAssembliesByRuntime(strongName, getRuntimeVersion, targetedRuntime, fileExists, getPathFromFusionName, getGacEnumerator, specificVersion);

            if (assembliesByRuntime != null)
            {
                foreach (SortedDictionary <AssemblyNameExtension, string> runtimeBucket in assembliesByRuntime.Values)
                {
                    // Grab the first element if there are one or more elements. This will give us the highest version assembly name.
                    if (runtimeBucket.Count > 0)
                    {
                        foreach (KeyValuePair <AssemblyNameExtension, string> kvp in runtimeBucket)
                        {
                            assemblyPath = kvp.Value;
                            break;
                        }

                        if (!String.IsNullOrEmpty(assemblyPath))
                        {
                            break;
                        }
                    }
                }
            }

            return(assemblyPath);
        }
コード例 #32
0
ファイル: Miscellaneous.cs プロジェクト: nikson/msbuild
        public void IgnoreDefaultInstalledAssemblyTables()
        {
            ResolveAssemblyReference t = new ResolveAssemblyReference();

            t.BuildEngine = new MockEngine();

            t.Assemblies = new ITaskItem[]
            {
                new TaskItem("Microsoft.Build.Engine"),
                new TaskItem("System.Xml")
            };

            t.SearchPaths = new string[]
            {
                @"{TargetFrameworkDirectory}"
            };
            t.TargetFrameworkDirectories = new string[] { Path.Combine(ObjectModelHelpers.TempProjectDir, "v3.5") };

            string implicitRedistListContents =
                "<FileList Redist='Microsoft-Windows-CLRCoreComp' >" +
                "<File AssemblyName='Microsoft.Build.Engine' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' />" +
                "</FileList >";
            string implicitRedistListPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("v3.5\\RedistList\\ImplicitList.xml", implicitRedistListContents);
            string microsoftBuildEnginePath = Path.Combine(ObjectModelHelpers.TempProjectDir, "v3.5\\Microsoft.Build.Engine");

            string explicitRedistListContents =
                "<FileList Redist='Microsoft-Windows-CLRCoreComp' >" +
                "<File AssemblyName='System.Xml' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' />" +
                "</FileList >";
            string explicitRedistListPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("v3.5\\RedistList\\ExplicitList.xml", explicitRedistListContents);
            string systemXmlPath = Path.Combine(ObjectModelHelpers.TempProjectDir, "v3.5\\System.Xml.dll");

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

            // Only the explicitly specified redist list should be used
            t.IgnoreDefaultInstalledAssemblyTables = true;

            FileExists cachedFileExists = fileExists;
            GetAssemblyName cachedGetAssemblyName = getAssemblyName;

            fileExists = new FileExists(delegate (string path)
            {
                if (String.Equals(path, microsoftBuildEnginePath, StringComparison.OrdinalIgnoreCase) ||
                    String.Equals(path, systemXmlPath, StringComparison.OrdinalIgnoreCase) ||
                    path.EndsWith("RarCache", StringComparison.OrdinalIgnoreCase))
                {
                    return true;
                }
                return false;
            });

            getAssemblyName = new GetAssemblyName(delegate (string path)
            {
                if (String.Equals(path, microsoftBuildEnginePath, StringComparison.OrdinalIgnoreCase))
                {
                    return new AssemblyNameExtension("Microsoft.Build.Engine, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                }
                else if (String.Equals(path, systemXmlPath, StringComparison.OrdinalIgnoreCase))
                {
                    return new AssemblyNameExtension("System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                }

                return null;
            });

            bool success;
            try
            {
                success = Execute(t);
            }
            finally
            {
                fileExists = cachedFileExists;
                getAssemblyName = cachedGetAssemblyName;
            }

            Assert.True(success); // "Expected no errors."
            Assert.Equal(1, t.ResolvedFiles.Length); // "Expected one resolved assembly."
            Assert.True(t.ResolvedFiles[0].ItemSpec.Contains("System.Xml")); // "Expected System.Xml to resolve."
        }
コード例 #33
0
ファイル: ReferenceTable.cs プロジェクト: cameron314/msbuild
        /// <summary>
        /// Set metadata on the items which will be output from RAR.
        /// </summary>
        private ITaskItem SetItemMetadata(ArrayList relatedItems, ArrayList satelliteItems, ArrayList serializationAssemblyItems, ArrayList scatterItems, string fusionName, Reference reference, AssemblyNameExtension assemblyName, FileExists fileExists)
        {
            // Set up the main item.
            ITaskItem referenceItem = new TaskItem();
            referenceItem.ItemSpec = reference.FullPath;
            referenceItem.SetMetadata(ItemMetadataNames.resolvedFrom, reference.ResolvedSearchPath);

            // Set the CopyLocal metadata.
            if (reference.IsCopyLocal)
            {
                referenceItem.SetMetadata(ItemMetadataNames.copyLocal, "true");
            }
            else
            {
                referenceItem.SetMetadata(ItemMetadataNames.copyLocal, "false");
            }

            // Set the FusionName metadata.
            referenceItem.SetMetadata(ItemMetadataNames.fusionName, fusionName);

            // Set the Redist name metadata.
            if (!String.IsNullOrEmpty(reference.RedistName))
            {
                referenceItem.SetMetadata(ItemMetadataNames.redist, reference.RedistName);
            }

            if (Reference.IsFrameworkFile(reference.FullPath, _frameworkPaths) || (_installedAssemblies != null && _installedAssemblies.FrameworkAssemblyEntryInRedist(assemblyName)))
            {
                if (!IsAssemblyRemovedFromDotNetFramework(assemblyName, reference.FullPath, _frameworkPaths, _installedAssemblies))
                {
                    referenceItem.SetMetadata(ItemMetadataNames.frameworkFile, "true");
                }
            }

            if (!String.IsNullOrEmpty(reference.ImageRuntime))
            {
                referenceItem.SetMetadata(ItemMetadataNames.imageRuntime, reference.ImageRuntime);
            }

            if (reference.IsWinMDFile)
            {
                referenceItem.SetMetadata(ItemMetadataNames.winMDFile, "true");

                // The ImplementationAssembly is only set if the implementation file exits on disk
                if (reference.ImplementationAssembly != null)
                {
                    if (VerifyArchitectureOfImplementationDll(reference.ImplementationAssembly, reference.FullPath))
                    {
                        referenceItem.SetMetadata(ItemMetadataNames.winmdImplmentationFile, Path.GetFileName(reference.ImplementationAssembly));

                        // Add the implementation item as a related file
                        ITaskItem item = new TaskItem(reference.ImplementationAssembly);
                        // Clone metadata.
                        referenceItem.CopyMetadataTo(item);
                        // Related files don't have a fusion name.
                        item.SetMetadata(ItemMetadataNames.fusionName, "");
                        RemoveNonForwardableMetadata(item);

                        // Add the related item.
                        relatedItems.Add(item);
                    }
                }

                if (reference.IsManagedWinMDFile)
                {
                    referenceItem.SetMetadata(ItemMetadataNames.winMDFileType, "Managed");
                }
                else
                {
                    referenceItem.SetMetadata(ItemMetadataNames.winMDFileType, "Native");
                }
            }

            // Set the IsRedistRoot metadata
            if (reference.IsRedistRoot == true)
            {
                referenceItem.SetMetadata(ItemMetadataNames.isRedistRoot, "true");
            }
            else if (reference.IsRedistRoot == false)
            {
                referenceItem.SetMetadata(ItemMetadataNames.isRedistRoot, "false");
            }
            else
            {
                // This happens when the redist root is "null". This means there
                // was no IsRedistRoot flag in the Redist XML (or there was no 
                // redist XML at all for this item).
            }

            // If there was a primary source item, then forward metadata from it.
            // It's important that the metadata from the primary source item
            // win over the same metadata from other source items, so that's
            // why we put this first.  (CopyMetadataTo will never override an 
            // already existing metadata.)  For example, if this reference actually
            // came directly from an item declared in the project file, we'd
            // want to use the metadata from it, not some other random item in
            // the project file that happened to have this reference as a dependency.
            if (reference.PrimarySourceItem != null)
            {
                reference.PrimarySourceItem.CopyMetadataTo(referenceItem);
            }
            else
            {
                bool hasImplementationFile = referenceItem.GetMetadata(ItemMetadataNames.winmdImplmentationFile).Length > 0;
                bool hasImageRuntime = referenceItem.GetMetadata(ItemMetadataNames.imageRuntime).Length > 0;
                bool hasWinMDFile = referenceItem.GetMetadata(ItemMetadataNames.winMDFile).Length > 0;

                // If there were non-primary source items, then forward metadata from them.
                ICollection sourceItems = reference.GetSourceItems();
                foreach (ITaskItem sourceItem in sourceItems)
                {
                    sourceItem.CopyMetadataTo(referenceItem);
                }

                // If the item originally did not have the implementation file metadata then we do not want to get it from the set of primary source items
                // since the implementation file is something specific to the source item and not supposed to be propigated.
                if (!hasImplementationFile)
                {
                    referenceItem.RemoveMetadata(ItemMetadataNames.winmdImplmentationFile);
                }

                // If the item originally did not have the ImageRuntime metadata then we do not want to get it from the set of primary source items
                // since the ImageRuntime is something specific to the source item and not supposed to be propigated.
                if (!hasImageRuntime)
                {
                    referenceItem.RemoveMetadata(ItemMetadataNames.imageRuntime);
                }

                // If the item originally did not have the WinMDFile metadata then we do not want to get it from the set of primary source items
                // since the WinMDFile is something specific to the source item and not supposed to be propigated
                if (!hasWinMDFile)
                {
                    referenceItem.RemoveMetadata(ItemMetadataNames.winMDFile);
                }
            }

            if (reference.ReferenceVersion != null)
            {
                referenceItem.SetMetadata(ItemMetadataNames.version, reference.ReferenceVersion.ToString());
            }
            else
            {
                referenceItem.SetMetadata(ItemMetadataNames.version, String.Empty);
            }

            // Now clone all properties onto the related files.
            foreach (string relatedFileExtension in reference.GetRelatedFileExtensions())
            {
                ITaskItem item = new TaskItem(reference.FullPathWithoutExtension + relatedFileExtension);
                // Clone metadata.
                referenceItem.CopyMetadataTo(item);
                // Related files don't have a fusion name.
                item.SetMetadata(ItemMetadataNames.fusionName, "");
                RemoveNonForwardableMetadata(item);

                // Add the related item.
                relatedItems.Add(item);
            }

            // Set up the satellites.
            foreach (string satelliteFile in reference.GetSatelliteFiles())
            {
                ITaskItem item = new TaskItem(Path.Combine(reference.DirectoryName, satelliteFile));
                // Clone metadata.
                referenceItem.CopyMetadataTo(item);
                // Set the destination directory.
                item.SetMetadata(ItemMetadataNames.destinationSubDirectory, FileUtilities.EnsureTrailingSlash(Path.GetDirectoryName(satelliteFile)));
                // Satellite files don't have a fusion name.
                item.SetMetadata(ItemMetadataNames.fusionName, "");
                RemoveNonForwardableMetadata(item);

                // Add the satellite item.
                satelliteItems.Add(item);
            }

            // Set up the serialization assemblies
            foreach (string serializationAssemblyFile in reference.GetSerializationAssemblyFiles())
            {
                ITaskItem item = new TaskItem(Path.Combine(reference.DirectoryName, serializationAssemblyFile));
                // Clone metadata.
                referenceItem.CopyMetadataTo(item);
                // serialization assemblies files don't have a fusion name.
                item.SetMetadata(ItemMetadataNames.fusionName, "");
                RemoveNonForwardableMetadata(item);

                // Add the serialization assembly item.
                serializationAssemblyItems.Add(item);
            }

            // Set up the scatter files.
            foreach (string scatterFile in reference.GetScatterFiles())
            {
                ITaskItem item = new TaskItem(Path.Combine(reference.DirectoryName, scatterFile));
                // Clone metadata.
                referenceItem.CopyMetadataTo(item);
                // We don't have a fusion name for scatter files.
                item.SetMetadata(ItemMetadataNames.fusionName, "");
                RemoveNonForwardableMetadata(item);

                // Add the satellite item.
                scatterItems.Add(item);
            }

            // As long as the item has not come from somewhere else say it came from rar (p2p's can come from somewhere else).
            if (referenceItem.GetMetadata(ItemMetadataNames.msbuildReferenceSourceTarget).Length == 0)
            {
                referenceItem.SetMetadata(ItemMetadataNames.msbuildReferenceSourceTarget, "ResolveAssemblyReference");
            }

            if (referenceItem.GetMetadata(ItemMetadataNames.msbuildReferenceSourceTarget).Equals("ProjectReference"))
            {
                if (reference.PrimarySourceItem != null)
                {
                    referenceItem.SetMetadata(ItemMetadataNames.projectReferenceOriginalItemSpec, reference.PrimarySourceItem.GetMetadata("OriginalItemSpec"));
                }
            }

            return referenceItem;
        }
コード例 #34
0
ファイル: Miscellaneous.cs プロジェクト: nikson/msbuild
        /// <summary>
        /// Generate helper delegates for returning the file existence and the assembly name.
        /// Also run the rest and return the result.
        /// </summary>
        private bool GenerateHelperDelegatesAndExecuteTask(ResolveAssemblyReference t)
        {
            FileExists cachedFileExists = fileExists;
            GetAssemblyName cachedGetAssemblyName = getAssemblyName;
            string microsoftBuildEnginePath = Path.Combine(ObjectModelHelpers.TempProjectDir, "v3.5\\Microsoft.Build.Engine.dll");
            string systemXmlPath = Path.Combine(ObjectModelHelpers.TempProjectDir, "v3.5\\System.Xml.dll");
            fileExists = new FileExists(delegate (string path)
            {
                if (String.Equals(path, microsoftBuildEnginePath, StringComparison.OrdinalIgnoreCase) ||
                    String.Equals(path, systemXmlPath, StringComparison.OrdinalIgnoreCase) ||
                    path.EndsWith("RarCache", StringComparison.OrdinalIgnoreCase))
                {
                    return true;
                }
                return false;
            });

            getAssemblyName = new GetAssemblyName(delegate (string path)
            {
                if (String.Equals(path, microsoftBuildEnginePath, StringComparison.OrdinalIgnoreCase))
                {
                    return new AssemblyNameExtension("Microsoft.Build.Engine, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                }
                else if (String.Equals(path, systemXmlPath, StringComparison.OrdinalIgnoreCase))
                {
                    return new AssemblyNameExtension("System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                }

                return null;
            });

            bool success;
            try
            {
                success = Execute(t);
            }
            finally
            {
                fileExists = cachedFileExists;
                getAssemblyName = cachedGetAssemblyName;
            }
            return success;
        }
コード例 #35
0
 /// <summary>
 /// Construct.
 /// </summary>
 /// <param name="frameworkPaths">Paths to framework directories.</param>
 /// <param name="installedAssemblies"></param>
 /// <param name="searchPathElement"></param>
 /// <param name="getAssemblyName"></param>
 /// <param name="fileExists"></param>
 public FrameworkPathResolver(string[] frameworkPaths, InstalledAssemblies installedAssemblies, string searchPathElement, GetAssemblyName getAssemblyName, FileExists fileExists, GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntimeVesion)
     : base(searchPathElement, getAssemblyName, fileExists, getRuntimeVersion, targetedRuntimeVesion, System.Reflection.ProcessorArchitecture.None, false)
 {
     _frameworkPaths = frameworkPaths;
     _installedAssemblies = installedAssemblies;
 }
コード例 #36
0
ファイル: Touch.cs プロジェクト: cameron314/msbuild
        /// <summary>
        /// Implementation of the execute method.
        /// </summary>
        /// <returns></returns>
        internal bool ExecuteImpl
        (
            FileExists fileExists,
            FileCreate fileCreate,
            GetAttributes fileGetAttributes,
            SetAttributes fileSetAttributes,
            SetLastAccessTime fileSetLastAccessTime,
            SetLastWriteTime fileSetLastWriteTime

        )
        {
            // See what time we are touching all files to
            DateTime touchDateTime;
            try
            {
                touchDateTime = GetTouchDateTime();
            }
            catch (FormatException e)
            {
                Log.LogErrorWithCodeFromResources("Touch.TimeSyntaxIncorrect", e.Message);
                return false;
            }

            // Go through all files and touch 'em
            bool retVal = true;
            ArrayList touchedItems = new ArrayList();
            HashSet<string> touchedFilesSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            foreach (ITaskItem file in Files)
            {
                // For speed, eliminate duplicates caused by poor targets authoring
                if (touchedFilesSet.Contains(file.ItemSpec))
                {
                    continue;
                }

                // Touch the file.  If the file was touched successfully then add it to our array of 
                // touched items. 
                if
                (
                    TouchFile
                    (
                        file.ItemSpec,
                        touchDateTime,
                        fileExists,
                        fileCreate,
                        fileGetAttributes,
                        fileSetAttributes,
                        fileSetLastAccessTime,
                        fileSetLastWriteTime

                    )
                )
                {
                    touchedItems.Add(file);
                }
                else
                {
                    retVal = false;
                }

                // Add even on failure to avoid reattempting
                touchedFilesSet.Add(file.ItemSpec);
            }

            // Now, set the property that indicates which items we touched.  Note that we
            // touch all the items 
            TouchedFiles = (ITaskItem[])touchedItems.ToArray(typeof(ITaskItem));
            return retVal;
        }
コード例 #37
0
 /// <summary>
 /// Construct.
 /// </summary>
 public AssemblyFoldersExResolver(string searchPathElement, GetAssemblyName getAssemblyName, FileExists fileExists, GetRegistrySubKeyNames getRegistrySubKeyNames, GetRegistrySubKeyDefaultValue getRegistrySubKeyDefaultValue, GetAssemblyRuntimeVersion getRuntimeVersion, OpenBaseKey openBaseKey, Version targetedRuntimeVesion, ProcessorArchitecture targetProcessorArchitecture, bool compareProcessorArchitecture, IBuildEngine buildEngine)
     : base(searchPathElement, getAssemblyName, fileExists, getRuntimeVersion, targetedRuntimeVesion, targetProcessorArchitecture, compareProcessorArchitecture)
 {
     _buildEngine = buildEngine as IBuildEngine4;
     _getRegistrySubKeyNames = getRegistrySubKeyNames;
     _getRegistrySubKeyDefaultValue = getRegistrySubKeyDefaultValue;
     _openBaseKey = openBaseKey;
 }
コード例 #38
0
 /// <summary>
 /// Construct.
 /// </summary>
 /// <param name="searchPathElement"></param>
 /// <param name="getAssemblyName"></param>
 /// <param name="fileExists"></param>
 public AssemblyFoldersResolver(string searchPathElement, GetAssemblyName getAssemblyName, FileExists fileExists, GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntimeVesion)
     : base(searchPathElement, getAssemblyName, fileExists, getRuntimeVersion, targetedRuntimeVesion, System.Reflection.ProcessorArchitecture.None, false)
 {
 }
コード例 #39
0
        /// <summary>
        /// Given a strong name, find its path in the GAC.
        /// </summary>
        /// <param name="strongName">The strong name.</param>
        /// <param name="targetProcessorArchitecture">Like x86 or IA64\AMD64.</param>
        /// <param name="getRuntimeVersion">Delegate to get the runtime version from a file path</param>
        /// <param name="targetedRuntimeVersion">What version of the runtime are we targeting</param>
        /// <param name="fullFusionName">Are we guranteed to have a full fusion name. This really can only happen if we have already resolved the assembly</param>
        /// <returns>The path to the assembly. Empty if none exists.</returns>
        internal static string GetLocation
        (
            IBuildEngine4 buildEngine,
            AssemblyNameExtension strongName,
            ProcessorArchitecture targetProcessorArchitecture,
            GetAssemblyRuntimeVersion getRuntimeVersion,
            Version targetedRuntimeVersion,
            bool fullFusionName,
            FileExists fileExists,
            GetPathFromFusionName getPathFromFusionName,
            GetGacEnumerator getGacEnumerator,
            bool specificVersion
        )
        {
            ConcurrentDictionary<AssemblyNameExtension, string> fusionNameToResolvedPath = null;
            bool useGacRarCache = Environment.GetEnvironmentVariable("MSBUILDDISABLEGACRARCACHE") == null;
            if (buildEngine != null && useGacRarCache)
            {
                string key = "44d78b60-3bbe-48fe-9493-04119ebf515f" + "|" + targetProcessorArchitecture.ToString() + "|" + targetedRuntimeVersion.ToString() + "|" + fullFusionName.ToString() + "|" + specificVersion.ToString();
                fusionNameToResolvedPath = buildEngine.GetRegisteredTaskObject(key, RegisteredTaskObjectLifetime.Build) as ConcurrentDictionary<AssemblyNameExtension, string>;
                if (fusionNameToResolvedPath == null)
                {
                    fusionNameToResolvedPath = new ConcurrentDictionary<AssemblyNameExtension, string>(AssemblyNameComparer.GenericComparer);
                    buildEngine.RegisterTaskObject(key, fusionNameToResolvedPath, RegisteredTaskObjectLifetime.Build, true /* dispose early ok*/);
                }
                else
                {
                    if (fusionNameToResolvedPath.ContainsKey(strongName))
                    {
                        string fusionName = null;
                        fusionNameToResolvedPath.TryGetValue(strongName, out fusionName);
                        return fusionName;
                    }
                }
            }

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

            string location = null;

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

                return location;
            }

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

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

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

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

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

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

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

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

            return null;
        }
コード例 #40
0
        /// <summary>
        /// Constructor
        /// </summary>
        internal AssemblyFoldersExCache(AssemblyFoldersEx assemblyFoldersEx, FileExists fileExists)
        {
            _assemblyFoldersEx = assemblyFoldersEx;
            _fileExists = fileExists;

            if (Environment.GetEnvironmentVariable("MSBUILDDISABLEASSEMBLYFOLDERSEXCACHE") != null)
            {
                _useOriginalFileExists = true;
            }
            else
            {
                Object lockobject = new Object();

                Parallel.ForEach<AssemblyFoldersExInfo>(assemblyFoldersEx, assemblyFolder =>
                {
                    if (FileUtilities.DirectoryExistsNoThrow(assemblyFolder.DirectoryPath))
                    {
                        string[] files = Directory.GetFiles(assemblyFolder.DirectoryPath, "*.*", SearchOption.TopDirectoryOnly);

                        lock (lockobject)
                        {
                            foreach (string file in files)
                            {
                                _filesInDirectories.Add(file);
                            }
                        }
                    }
                });
            }
        }
コード例 #41
0
        /// <summary>
        /// Enumerate the gac and generate a list of assemblies which match the strongname by runtime.
        /// </summary>
        private static SortedDictionary<Version, SortedDictionary<AssemblyNameExtension, string>> GenerateListOfAssembliesByRuntime(string strongName, GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntime, FileExists fileExists, GetPathFromFusionName getPathFromFusionName, GetGacEnumerator getGacEnumerator, bool specificVersion)
        {
            ErrorUtilities.VerifyThrowArgumentNull(targetedRuntime, "targetedRuntime");

            IEnumerable<AssemblyNameExtension> gacEnum = getGacEnumerator(strongName);

            // Dictionary of Runtime version (sorted in reverse order) to a list of assemblies which are part of that runtime. This will allow us to pick the highest runtime and version first.
            SortedDictionary<Version, SortedDictionary<AssemblyNameExtension, string>> assembliesWithValidRuntimes = new SortedDictionary<Version, SortedDictionary<AssemblyNameExtension, string>>(ReverseVersionGenericComparer.Comparer);

            // Enumerate the gac values returned based on the partial or full fusion name.
            if (gacEnum != null)
            {
                foreach (AssemblyNameExtension gacAssembly in gacEnum)
                {
                    // We only have a fusion name from the IAssemblyName interface we need to get the path to the assembly to resolve it and to check its runtime.
                    string assemblyPath = getPathFromFusionName(gacAssembly.FullName);

                    // Make sure we could get the path from the Fusion name and make sure the file actually exists.
                    if (!String.IsNullOrEmpty(assemblyPath) && fileExists(assemblyPath))
                    {
                        // Get the runtime version from the found assembly.
                        string runtimeVersionRaw = getRuntimeVersion(assemblyPath);

                        // Convert the runtime string to a version so we can properly compare them as per version object comparison rules. 
                        // We will accept version which are less than or equal to the targeted runtime.
                        Version runtimeVersion = VersionUtilities.ConvertToVersion(runtimeVersionRaw);

                        // Make sure the targeted runtime is greater than or equal to the runtime version of the assembly we got from the gac.
                        if (runtimeVersion != null)
                        {
                            if (targetedRuntime.CompareTo(runtimeVersion) >= 0 || specificVersion)
                            {
                                SortedDictionary<AssemblyNameExtension, string> assembliesWithRuntime = null;
                                assembliesWithValidRuntimes.TryGetValue(runtimeVersion, out assembliesWithRuntime);

                                // Create a new list if one does not exist.
                                if (assembliesWithRuntime == null)
                                {
                                    assembliesWithRuntime = new SortedDictionary<AssemblyNameExtension, string>(AssemblyNameReverseVersionComparer.GenericComparer);
                                    assembliesWithValidRuntimes.Add(runtimeVersion, assembliesWithRuntime);
                                }

                                if (!assembliesWithRuntime.ContainsKey(gacAssembly))
                                {
                                    // Add the assembly to the list
                                    assembliesWithRuntime.Add(gacAssembly, assemblyPath);
                                }
                            }
                        }
                    }
                }
            }

            return assembliesWithValidRuntimes;
        }
コード例 #42
0
ファイル: SystemState.cs プロジェクト: hongli051/IronyTest
 /// <summary>
 /// Cache the results of a FileExists delegate.
 /// </summary>
 /// <param name="fileExists">The delegate.</param>
 /// <returns>Cached version of the delegate.</returns>
 internal FileExists CacheDelegate(FileExists fileExistsValue)
 {
     fileExists = fileExistsValue;
     return(new FileExists(this.FileExists));
 }
コード例 #43
0
ファイル: CommandLine.cs プロジェクト: nulltoken/xunit
        protected XunitProject Parse(FileExists fileExists)
        {
            Dictionary<string, string> transforms = new Dictionary<string, string>();
            bool passedProjectFile = false;
            XunitProject project = null;

            string filename = arguments.Pop();
            if (!fileExists(filename))
                throw new ArgumentException(String.Format("file not found: {0}", filename));

            if (IsProjectFilename(filename))
            {
                project = GetMultiAssemblyProject(filename);
                passedProjectFile = true;
            }
            else
            {
                string configFile = null;

                if (arguments.Count > 0 && !arguments.Peek().StartsWith("/"))
                {
                    configFile = arguments.Pop();

                    if (!fileExists(configFile))
                        throw new ArgumentException(String.Format("config file not found: {0}", configFile));
                }

                project = GetSingleAssemblyProject(filename, configFile);
            }

            while (arguments.Count > 0)
            {
                KeyValuePair<string, string> option = PopOption(arguments);
                string optionName = option.Key.ToLowerInvariant();

                if (!optionName.StartsWith("/"))
                    throw new ArgumentException(String.Format("unknown command line option: {0}", option.Key));

                if (optionName == "/wait")
                {
                    GuardNoOptionValue(option);
                    Wait = true;
                }
                else if (optionName == "/silent")
                {
                    GuardNoOptionValue(option);
                    Silent = true;
                }
                else if (optionName == "/teamcity")
                {
                    GuardNoOptionValue(option);
                    TeamCity = true;
                }
                else if (optionName == "/noshadow")
                {
                    GuardNoProjectFile(passedProjectFile, option);
                    GuardNoOptionValue(option);
                    foreach (var assembly in project.Assemblies)
                        assembly.ShadowCopy = false;
                }
                else if (optionName == "/trait")
                {
                    if (option.Value == null)
                        throw new ArgumentException("missing argument for /trait");

                    string[] pieces = option.Value.Split('=');
                    if (pieces.Length != 2 || String.IsNullOrEmpty(pieces[0]) || String.IsNullOrEmpty(pieces[1]))
                        throw new ArgumentException("incorrect argument format for /trait (should be \"name=value\")");

                    string name = pieces[0];
                    string value = pieces[1];
                    project.Filters.IncludedTraits.AddValue(name, value);
                }
                else if (optionName == "/-trait")
                {
                    if (option.Value == null)
                        throw new ArgumentException("missing argument for /-trait");

                    string[] pieces = option.Value.Split('=');
                    if (pieces.Length != 2 || String.IsNullOrEmpty(pieces[0]) || String.IsNullOrEmpty(pieces[1]))
                        throw new ArgumentException("incorrect argument format for /-trait (should be \"name=value\")");

                    string name = pieces[0];
                    string value = pieces[1];
                    project.Filters.ExcludedTraits.AddValue(name, value);
                }
                else
                {
                    GuardNoProjectFile(passedProjectFile, option);

                    if (option.Value == null)
                        throw new ArgumentException(String.Format("missing filename for {0}", option.Key));

                    foreach (var assembly in project.Assemblies)
                        assembly.Output.Add(optionName.Substring(1), option.Value);
                }
            }

            return project;
        }
コード例 #44
0
ファイル: GacResolver.cs プロジェクト: ChronosWS/msbuild
 /// <summary>
 /// Construct.
 /// </summary>
 /// <param name="targetProcessorArchitecture">Like x86 or IA64\AMD64, the processor architecture being targetted.</param>
 public GacResolver(System.Reflection.ProcessorArchitecture targetProcessorArchitecture, string searchPathElement, GetAssemblyName getAssemblyName, FileExists fileExists, GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntimeVesion, IBuildEngine buildEngine)
     : base(searchPathElement, getAssemblyName, fileExists, getRuntimeVersion, targetedRuntimeVesion, targetProcessorArchitecture, true)
 {
     _buildEngine = buildEngine as IBuildEngine4;
 }
コード例 #45
0
ファイル: Touch.cs プロジェクト: cameron314/msbuild
        /// <summary>
        /// Helper method touches a file.
        /// </summary>
        /// <param name="file"></param>
        /// <param name="dt"></param>
        /// <param name="fileExists"></param>
        /// <param name="fileCreate"></param>
        /// <param name="fileGetAttributes"></param>
        /// <param name="fileSetAttributes"></param>
        /// <param name="fileSetLastAccessTime"></param>
        /// <param name="fileSetLastWriteTime"></param>
        /// <returns>"True" if the file was touched.</returns>
        private bool TouchFile
        (
            string file,
            DateTime dt,
            FileExists fileExists,
            FileCreate fileCreate,
            GetAttributes fileGetAttributes,
            SetAttributes fileSetAttributes,
            SetLastAccessTime fileSetLastAccessTime,
            SetLastWriteTime fileSetLastWriteTime
        )
        {
            if (!fileExists(file))
            {
                // If the file does not exist then we check if we need to create it.
                if (AlwaysCreate)
                {
                    Log.LogMessageFromResources(MessageImportance.Normal, "Touch.CreatingFile", file, "AlwaysCreate");
                    if (!CreateFile(file, fileCreate))
                    {
                        return false;
                    }
                }
                else
                {
                    Log.LogErrorWithCodeFromResources("Touch.FileDoesNotExist", file);
                    return false;
                }
            }
            else
            {
                Log.LogMessageFromResources(MessageImportance.Normal, "Touch.Touching", file);
            }

            // If the file is read only then we must either issue an error, or, if the user so 
            // specified, make the file temporarily not read only.
            bool needToRestoreAttributes = false;
            System.IO.FileAttributes faOriginal = fileGetAttributes(file);
            if ((faOriginal & System.IO.FileAttributes.ReadOnly) == System.IO.FileAttributes.ReadOnly)
            {
                if (ForceTouch)
                {
                    try
                    {
                        System.IO.FileAttributes faNew = (faOriginal & ~System.IO.FileAttributes.ReadOnly);
                        fileSetAttributes(file, faNew);
                        needToRestoreAttributes = true;
                    }
                    catch (Exception e) // Catching Exception, but rethrowing unless it's a well-known exception.
                    {
                        if (ExceptionHandling.NotExpectedException(e))
                            throw;
                        Log.LogErrorWithCodeFromResources("Touch.CannotMakeFileWritable", file, e.Message);
                        return false;
                    }
                }
            }

            // Do the actual touch operation
            bool retVal = true;
            try
            {
                fileSetLastAccessTime(file, dt);
                fileSetLastWriteTime(file, dt);
            }
            catch (Exception e) // Catching Exception, but rethrowing unless it's a well-known exception.
            {
                if (ExceptionHandling.NotExpectedException(e))
                    throw;
                Log.LogErrorWithCodeFromResources("Touch.CannotTouch", file, e.Message);
                return false;
            }
            finally
            {
                if (needToRestoreAttributes)
                {
                    // Attempt to restore the attributes.  If we fail here, then there is 
                    // not much we can do.
                    try
                    {
                        fileSetAttributes(file, faOriginal);
                    }
                    catch (Exception e) // Catching Exception, but rethrowing unless it's a well-known exception.
                    {
                        if (ExceptionHandling.NotExpectedException(e))
                            throw;
                        Log.LogErrorWithCodeFromResources("Touch.CannotRestoreAttributes", file, e.Message);
                        retVal = false;
                    }
                }
            }

            return retVal;
        }
コード例 #46
0
        /// <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;
        }
コード例 #47
0
ファイル: Miscellaneous.cs プロジェクト: nikson/msbuild
        public void DoNotAssumeFilesDescribedByRedistListExistOnDisk()
        {
            string redistListPath = CreateGenericRedistList();
            try
            {
                ResolveAssemblyReference t = new ResolveAssemblyReference();

                t.BuildEngine = new MockEngine();

                t.Assemblies = new ITaskItem[]
                {
                    new TaskItem("Microsoft.Build.Engine"),
                    new TaskItem("System.Xml")
                };

                t.SearchPaths = new string[]
                {
                    @"{TargetFrameworkDirectory}"
                };
                t.TargetFrameworkDirectories = new string[] { Path.Combine(ObjectModelHelpers.TempProjectDir, "v3.5") };
                string microsoftBuildEnginePath = Path.Combine(ObjectModelHelpers.TempProjectDir, "v3.5\\Microsoft.Build.Engine");
                string systemXmlPath = Path.Combine(ObjectModelHelpers.TempProjectDir, "v3.5\\System.Xml.dll");

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

                FileExists cachedFileExists = fileExists;
                GetAssemblyName cachedGetAssemblyName = getAssemblyName;

                // Note that Microsoft.Build.Engine.dll does not exist
                fileExists = new FileExists(delegate (string path)
                {
                    if (String.Equals(path, systemXmlPath, StringComparison.OrdinalIgnoreCase) || path.EndsWith("RarCache", StringComparison.OrdinalIgnoreCase))
                    {
                        return true;
                    }
                    return false;
                });

                getAssemblyName = new GetAssemblyName(delegate (string path)
                {
                    if (String.Equals(path, microsoftBuildEnginePath, StringComparison.OrdinalIgnoreCase))
                    {
                        return new AssemblyNameExtension("Microsoft.Build.Engine, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                    }
                    else if (String.Equals(path, systemXmlPath, StringComparison.OrdinalIgnoreCase))
                    {
                        return new AssemblyNameExtension("System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                    }

                    return null;
                });

                bool success;
                try
                {
                    success = Execute(t);
                }
                finally
                {
                    fileExists = cachedFileExists;
                    getAssemblyName = cachedGetAssemblyName;
                }

                Assert.True(success); // "Expected no errors."
                Assert.Equal(1, t.ResolvedFiles.Length); // "Expected one resolved assembly."
                Assert.True(t.ResolvedFiles[0].ItemSpec.Contains("System.Xml")); // "Expected System.Xml to resolve."
            }
            finally
            {
                File.Delete(redistListPath);
            }
        }
コード例 #48
0
        /// <summary>
        /// Returns the raw list of direct dependent assemblies from assembly's metadata.
        /// </summary>
        /// <param name="fileExists">the delegate to check for the existence of a file.</param>
        /// <param name="resolvedReference">reference we are interested</param>
        /// <param name="getAssemblyMetadata">the delegate to access assembly metadata</param>
        /// <returns>list of dependencies</returns>
        private AssemblyNameExtension[] GetDependencies(Reference resolvedReference, FileExists fileExists, GetAssemblyMetadata getAssemblyMetadata)
        {
            AssemblyNameExtension[] result = null;
            if (resolvedReference != null && resolvedReference.IsPrimary && !resolvedReference.IsBadImage)
            {
                System.Runtime.Versioning.FrameworkName frameworkName = null;
                string[] scatterFiles = null;
                try
                {
                    // in case of P2P that have not build the reference can be resolved but file does not exist on disk. 
                    if (fileExists(resolvedReference.FullPath))
                    {
                        getAssemblyMetadata(resolvedReference.FullPath, out result, out scatterFiles, out frameworkName);
                    }
                }
                catch (Exception e)
                {
                    if (ExceptionHandling.IsCriticalException(e))
                    {
                        throw;
                    }
                }
            }

            return result;
        }
コード例 #49
0
ファイル: ReferenceTable.cs プロジェクト: cameron314/msbuild
        /// <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
                );
        }
コード例 #50
0
 /// <summary>
 ///  Checks to see if the assemblyName passed in is in the GAC.
 /// </summary>
 private string GetAssemblyPathInGac(AssemblyNameExtension assemblyName, SystemProcessorArchitecture targetProcessorArchitecture, GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntimeVersion, FileExists fileExists, bool fullFusionName, bool specificVersion)
 {
     return GlobalAssemblyCache.GetLocation(BuildEngine as IBuildEngine4, assemblyName, targetProcessorArchitecture, getRuntimeVersion, targetedRuntimeVersion, fullFusionName, fileExists, null, null, specificVersion /* this value does not matter if we are passing a full fusion name*/);
 }
コード例 #51
0
        /// <summary>
        /// Enumerate the gac and generate a list of assemblies which match the strongname by runtime.
        /// </summary>
        private static SortedDictionary <Version, SortedDictionary <AssemblyNameExtension, string> > GenerateListOfAssembliesByRuntime(string strongName, GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntime, FileExists fileExists, GetPathFromFusionName getPathFromFusionName, GetGacEnumerator getGacEnumerator, bool specificVersion)
        {
            ErrorUtilities.VerifyThrowArgumentNull(targetedRuntime, "targetedRuntime");

            IEnumerable <AssemblyNameExtension> gacEnum = getGacEnumerator(strongName);

            // Dictionary of Runtime version (sorted in reverse order) to a list of assemblies which are part of that runtime. This will allow us to pick the highest runtime and version first.
            SortedDictionary <Version, SortedDictionary <AssemblyNameExtension, string> > assembliesWithValidRuntimes = new SortedDictionary <Version, SortedDictionary <AssemblyNameExtension, string> >(ReverseVersionGenericComparer.Comparer);

            // Enumerate the gac values returned based on the partial or full fusion name.
            if (gacEnum != null)
            {
                foreach (AssemblyNameExtension gacAssembly in gacEnum)
                {
                    // We only have a fusion name from the IAssemblyName interface we need to get the path to the assembly to resolve it and to check its runtime.
                    string assemblyPath = getPathFromFusionName(gacAssembly.FullName);

                    // Make sure we could get the path from the Fusion name and make sure the file actually exists.
                    if (!String.IsNullOrEmpty(assemblyPath) && fileExists(assemblyPath))
                    {
                        // Get the runtime version from the found assembly.
                        string runtimeVersionRaw = getRuntimeVersion(assemblyPath);

                        // Convert the runtime string to a version so we can properly compare them as per version object comparison rules.
                        // We will accept version which are less than or equal to the targeted runtime.
                        Version runtimeVersion = VersionUtilities.ConvertToVersion(runtimeVersionRaw);

                        // Make sure the targeted runtime is greater than or equal to the runtime version of the assembly we got from the gac.
                        if (runtimeVersion != null)
                        {
                            if (targetedRuntime.CompareTo(runtimeVersion) >= 0 || specificVersion)
                            {
                                SortedDictionary <AssemblyNameExtension, string> assembliesWithRuntime = null;
                                assembliesWithValidRuntimes.TryGetValue(runtimeVersion, out assembliesWithRuntime);

                                // Create a new list if one does not exist.
                                if (assembliesWithRuntime == null)
                                {
                                    assembliesWithRuntime = new SortedDictionary <AssemblyNameExtension, string>(AssemblyNameReverseVersionComparer.GenericComparer);
                                    assembliesWithValidRuntimes.Add(runtimeVersion, assembliesWithRuntime);
                                }

                                if (!assembliesWithRuntime.ContainsKey(gacAssembly))
                                {
                                    // Add the assembly to the list
                                    assembliesWithRuntime.Add(gacAssembly, assemblyPath);
                                }
                            }
                        }
                    }
                }
            }

            return(assembliesWithValidRuntimes);
        }
コード例 #52
0
ファイル: Reference.cs プロジェクト: ravpacheco/msbuild
 internal Reference(IsWinMDFile isWinMDFile, FileExists fileExists, GetAssemblyRuntimeVersion getRuntimeVersion)
 {
     _isWinMDFile = isWinMDFile;
     _fileExists = fileExists;
     _getRuntimeVersion = getRuntimeVersion;
 }
コード例 #53
0
        /// <summary>
        /// Given a strong name, find its path in the GAC.
        /// </summary>
        /// <param name="strongName">The strong name.</param>
        /// <param name="targetProcessorArchitecture">Like x86 or IA64\AMD64.</param>
        /// <param name="getRuntimeVersion">Delegate to get the runtime version from a file path</param>
        /// <param name="targetedRuntimeVersion">What version of the runtime are we targeting</param>
        /// <param name="fullFusionName">Are we guranteed to have a full fusion name. This really can only happen if we have already resolved the assembly</param>
        /// <returns>The path to the assembly. Empty if none exists.</returns>
        internal static string GetLocation
        (
            IBuildEngine4 buildEngine,
            AssemblyNameExtension strongName,
            ProcessorArchitecture targetProcessorArchitecture,
            GetAssemblyRuntimeVersion getRuntimeVersion,
            Version targetedRuntimeVersion,
            bool fullFusionName,
            FileExists fileExists,
            GetPathFromFusionName getPathFromFusionName,
            GetGacEnumerator getGacEnumerator,
            bool specificVersion
        )
        {
            ConcurrentDictionary <AssemblyNameExtension, string> fusionNameToResolvedPath = null;
            bool useGacRarCache = Environment.GetEnvironmentVariable("MSBUILDDISABLEGACRARCACHE") == null;

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

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

            string location = null;

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

                return(location);
            }

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

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

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

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

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

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

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

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

            return(null);
        }
コード例 #54
0
ファイル: HintPathResolver.cs プロジェクト: baronfel/msbuild
 /// <summary>
 /// Construct.
 /// </summary>
 public HintPathResolver(string searchPathElement, GetAssemblyName getAssemblyName, FileExists fileExists, GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntimeVesion)
     : base(searchPathElement, getAssemblyName, fileExists, getRuntimeVersion, targetedRuntimeVesion, ProcessorArchitecture.None, false)
 {
 }
コード例 #55
0
 public AssemblyFoldersExResolver(string searchPathElement, GetAssemblyName getAssemblyName, FileExists fileExists, GetRegistrySubKeyNames getRegistrySubKeyNames, GetRegistrySubKeyDefaultValue getRegistrySubKeyDefaultValue, GetAssemblyRuntimeVersion getRuntimeVersion, OpenBaseKey openBaseKey, Version targetedRuntimeVesion, ProcessorArchitecture targetProcessorArchitecture, bool compareProcessorArchitecture, IBuildEngine buildEngine)
     : base(searchPathElement, getAssemblyName, fileExists, getRuntimeVersion, targetedRuntimeVesion, targetProcessorArchitecture, compareProcessorArchitecture)
 {
     _buildEngine                   = buildEngine as IBuildEngine4;
     _getRegistrySubKeyNames        = getRegistrySubKeyNames;
     _getRegistrySubKeyDefaultValue = getRegistrySubKeyDefaultValue;
     _openBaseKey                   = openBaseKey;
 }
コード例 #56
0
 /// <summary>
 /// Construct.
 /// </summary>
 public FrameworkPathResolver(string[] frameworkPaths, InstalledAssemblies installedAssemblies, string searchPathElement, GetAssemblyName getAssemblyName, FileExists fileExists, GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntimeVesion)
     : base(searchPathElement, getAssemblyName, fileExists, getRuntimeVersion, targetedRuntimeVesion, System.Reflection.ProcessorArchitecture.None, false)
 {
     _frameworkPaths      = frameworkPaths;
     _installedAssemblies = installedAssemblies;
 }
コード例 #57
0
 /// <summary>
 /// Construct.
 /// </summary>
 /// <param name="searchPathElement"></param>
 /// <param name="getAssemblyName"></param>
 /// <param name="fileExists"></param>
 public AssemblyFoldersResolver(string searchPathElement, GetAssemblyName getAssemblyName, FileExists fileExists, GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntimeVesion)
     : base(searchPathElement, getAssemblyName, fileExists, getRuntimeVersion, targetedRuntimeVesion, System.Reflection.ProcessorArchitecture.None, false)
 {
 }
コード例 #58
0
ファイル: Reference.cs プロジェクト: ravpacheco/msbuild
        /// <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;
        }
コード例 #59
0
 /// <summary>
 /// Given a strong name, find its path in the GAC.
 /// </summary>
 /// <param name="strongName">The strong name.</param>
 /// <param name="targetProcessorArchitecture">Like x86 or IA64\AMD64.</param>
 /// <param name="getRuntimeVersion">Delegate to get the runtime version from a file path</param>
 /// <param name="targetedRuntimeVersion">What version of the runtime are we targeting</param>
 /// <param name="fullFusionName">Are we guranteed to have a full fusion name. This really can only happen if we have already resolved the assembly</param>
 /// <returns>The path to the assembly. Empty if none exists.</returns>
 internal static string GetLocation
 (
     AssemblyNameExtension strongName,
     ProcessorArchitecture targetProcessorArchitecture,
     GetAssemblyRuntimeVersion getRuntimeVersion,
     Version targetedRuntimeVersion,
     bool fullFusionName,
     FileExists fileExists,
     GetPathFromFusionName getPathFromFusionName,
     GetGacEnumerator getGacEnumerator,
     bool specificVersion
 )
 {
     return GetLocation(null, strongName, targetProcessorArchitecture, getRuntimeVersion, targetedRuntimeVersion, fullFusionName, fileExists, getPathFromFusionName, getGacEnumerator, specificVersion);
 }
コード例 #60
0
 /// <summary>
 /// Construct.
 /// </summary>
 /// <param name="searchPathElement"></param>
 /// <param name="getAssemblyName"></param>
 /// <param name="fileExists"></param>
 public RawFilenameResolver(string searchPathElement, GetAssemblyName getAssemblyName, FileExists fileExists, GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntimeVesion)
     : base(searchPathElement, getAssemblyName, fileExists, getRuntimeVersion, targetedRuntimeVesion, ProcessorArchitecture.None, false)
 {
 }