Ejemplo n.º 1
1
        public bool Execute(string installPath, string scriptFileName, IPackage package, Project project, FrameworkName targetFramework, ILogger logger)
        {
            string scriptPath, fullPath;
            if (package.FindCompatibleToolFiles(scriptFileName, targetFramework, out scriptPath))
            {
                fullPath = Path.Combine(installPath, scriptPath);
            }
            else
            {
                return false;
            }

            if (File.Exists(fullPath))
            {
                string toolsPath = Path.GetDirectoryName(fullPath);
                string logMessage = String.Format(CultureInfo.CurrentCulture, VsResources.ExecutingScript, fullPath);

                // logging to both the Output window and progress window.
                logger.Log(MessageLevel.Info, logMessage);

                IConsole console = OutputConsoleProvider.CreateOutputConsole(requirePowerShellHost: true);
                Host.Execute(console,
                    "$__pc_args=@(); $input|%{$__pc_args+=$_}; & " + PathHelper.EscapePSPath(fullPath) + " $__pc_args[0] $__pc_args[1] $__pc_args[2] $__pc_args[3]; Remove-Variable __pc_args -Scope 0",
                    new object[] { installPath, toolsPath, package, project });

                return true;
            }
            return false;
        }
Ejemplo n.º 2
0
        public LibraryDescription GetDescription(LibraryRange libraryRange, FrameworkName targetFramework)
        {
            if (!DependencyTargets.SupportsPackage(libraryRange.Target))
            {
                return null;
            }

            var versionRange = libraryRange.VersionRange;

            var package = FindCandidate(libraryRange.Name, versionRange);

            if (package != null)
            {
                var dependencies = GetDependencies(package, targetFramework);

                return new LibraryDescription(
                    libraryRange,
                    new LibraryIdentity(package.Id, package.Version, isGacOrFrameworkReference: false),
                    path: null,
                    type: LibraryTypes.Package,
                    dependencies: dependencies,
                    assemblies: null,
                    framework: null);
            }

            return null;
        }
Ejemplo n.º 3
0
 public IEnumerable<string> GetAttemptedPaths(FrameworkName targetFramework)
 {
     return new[]
     {
         Path.Combine(_repository.RepositoryRoot.Root, "{name}", "{version}", "{name}.nuspec")
     };
 }
Ejemplo n.º 4
0
        private bool TryResolvePartialName(string name, SemanticVersion version, FrameworkName targetFramework, out string assemblyLocation)
        {
            foreach (var gacPath in GetGacSearchPaths(targetFramework))
            {
                var di = new DirectoryInfo(Path.Combine(gacPath, name));

                if (!di.Exists)
                {
                    continue;
                }

                foreach (var assemblyFile in di.EnumerateFiles("*.dll", SearchOption.AllDirectories))
                {
                    if (!Path.GetFileNameWithoutExtension(assemblyFile.Name).Equals(name, StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    SemanticVersion assemblyVersion = VersionUtility.GetAssemblyVersion(assemblyFile.FullName);
                    if (version == null || assemblyVersion == version)
                    {
                        assemblyLocation = assemblyFile.FullName;
                        return true;
                    }
                }
            }

            assemblyLocation = null;
            return false;
        }
Ejemplo n.º 5
0
        public LibraryDescription GetDescription(LibraryRange libraryRange, FrameworkName targetFramework)
        {
            if (!libraryRange.IsGacOrFrameworkReference)
            {
                return null;
            }

            if (!RuntimeEnvironmentHelper.IsWindows)
            {
                return null;
            }

            if (!VersionUtility.IsDesktop(targetFramework))
            {
                return null;
            }

            var name = libraryRange.Name;
            var version = libraryRange.VersionRange?.MinVersion;

            string path;
            if (!TryResolvePartialName(libraryRange.GetReferenceAssemblyName(), version, targetFramework, out path))
            {
                return null;
            }

            return new LibraryDescription(
                libraryRange,
                new LibraryIdentity(name, version, isGacOrFrameworkReference: true),
                path,
                LibraryTypes.GlobalAssemblyCache,
                Enumerable.Empty<LibraryDependency>(),
                new[] { libraryRange.GetReferenceAssemblyName() },
                framework: targetFramework);
        }
Ejemplo n.º 6
0
 public PublishRuntime(PublishRoot root, FrameworkName frameworkName, string runtimePath)
 {
     _frameworkName = frameworkName;
     _runtimePath = runtimePath;
     Name = new DirectoryInfo(_runtimePath).Name;
     TargetPath = Path.Combine(root.TargetRuntimesPath, Name);
 }
Ejemplo n.º 7
0
 public static FrameworkName SelectFrameworkNameForRuntime(IEnumerable<FrameworkName> availableFrameworks, FrameworkName currentFramework, string runtime)
 {
     // Filter out frameworks incompatible with the current framework before selecting
     return SelectFrameworkNameForRuntime(
         availableFrameworks.Where(f => VersionUtility.IsCompatible(currentFramework, f)),
         runtime);
 }
        internal static string GetRootEditorSetting(ModelTreeManager modelTreeManager, FrameworkName targetFramework)
        {
            Debug.Assert(modelTreeManager != null, "modelTreeManager is null.");
            Debug.Assert(targetFramework != null, "targetFramework is null.");

            string globalEditorSetting = null;
            if (Is45OrHigher(targetFramework))
            {
                if (modelTreeManager != null)
                {
                    ModelItem rootItem = modelTreeManager.Root;
                    if (rootItem != null)
                    {
                        object root = rootItem.GetCurrentValue();
                        globalEditorSetting = ExpressionActivityEditor.GetExpressionActivityEditor(root);
                        if (string.IsNullOrEmpty(globalEditorSetting))
                        {
                            globalEditorSetting = VBExpressionLanguageName;
                        }
                    }
                }
            }
            else
            {
                // When the target framework is less than 4.5, the root setting is ignored and always return VB
                globalEditorSetting = VBExpressionLanguageName;
            }

            return globalEditorSetting;
        }
        public static string GetDisplayName(FrameworkName version)
        {
            var normalized = VersionUtility.GetShortFrameworkName(version);

            // HACKS :)
            if (version.Profile.Equals("WindowsPhone", StringComparison.InvariantCultureIgnoreCase)
             && version.Identifier.Equals("Silverlight", StringComparison.InvariantCultureIgnoreCase)
             && version.Version.Major == 3) {
                return "Windows Phone 7";
            }

            // MORE HACKS
            var result = normalized;
            result = Regex.Replace(result, @"^net(?=\d)",          ".NET ");
            result = Regex.Replace(result, @"(\d+(?:\.\d+)*)-cf$", "CF $1");
            result = Regex.Replace(result, @"^(sl\d)\d$",          "$1"); // Silverlight normally uses one digit
            result = Regex.Replace(result, @"^sl(?=\d)",           "Silverlight ");
            result = Regex.Replace(result, @"^wp(?=\d)",           "Windows Phone ");
            result = Regex.Replace(result, @"^wp$",                "Windows Phone");
            result = Regex.Replace(result, @"^win(dows)?(8(0)?)?$", "Windows 8", RegexOptions.ExplicitCapture);
            result = Regex.Replace(result, @"^win81$",             "Windows 8.1");
            result = Regex.Replace(result, @"\d{2,}",              match => string.Join(".", match.Value.ToCharArray())); // 45 => 4.5, etc
            result = Regex.Replace(result, @"-Client",             " (Client Profile)");

            return result;
        }
        public LibraryDescription GetDescription(LibraryRange libraryRange, FrameworkName targetFramework)
        {
            if (libraryRange.IsGacOrFrameworkReference)
            {
                return null;
            }

            if (!DependencyTargets.SupportsProject(libraryRange.Target))
            {
                return null;
            }

            string name = libraryRange.Name;

            Runtime.Project project;

            // Can't find a project file with the name so bail
            if (!_projectResolver.TryResolveProject(name, out project))
            {
                return null;
            }

            // This never returns null
            var targetFrameworkInfo = project.GetCompatibleTargetFramework(targetFramework);

            var dependencies = project.Dependencies.Concat(targetFrameworkInfo.Dependencies).ToList();
            
            return new ProjectDescription(
                libraryRange,
                project,
                dependencies,
                Enumerable.Empty<string>(),
                targetFrameworkInfo,
                resolved: true);
        }
Ejemplo n.º 11
0
        public bool TryGetAssembly(string name, FrameworkName targetFramework, out string path, out Version version)
        {
            path = null;
            version = null;

            var information = _cache.GetOrAdd(targetFramework, GetFrameworkInformation);

            if (information == null || !information.Exists)
            {
                return false;
            }

            lock (information.Assemblies)
            {
                AssemblyEntry entry;
                if (information.Assemblies.TryGetValue(name, out entry))
                {
                    if (string.IsNullOrEmpty(entry.Path))
                    {
                        entry.Path = GetAssemblyPath(information.SearchPaths, name);
                    }

                    if (!string.IsNullOrEmpty(entry.Path) && entry.Version == null)
                    {
                        // This code path should only run on mono
                        entry.Version = VersionUtility.GetAssemblyVersion(entry.Path).Version;
                    }

                    path = entry.Path;
                    version = entry.Version;
                }
            }

            return !string.IsNullOrEmpty(path);
        }
 internal ReferenceTable(bool findDependencies, bool findSatellites, bool findSerializationAssemblies, bool findRelatedFiles, string[] searchPaths, string[] allowedAssemblyExtensions, string[] relatedFileExtensions, string[] candidateAssemblyFiles, string[] frameworkPaths, InstalledAssemblies installedAssemblies, System.Reflection.ProcessorArchitecture targetProcessorArchitecture, Microsoft.Build.Shared.FileExists fileExists, Microsoft.Build.Shared.DirectoryExists directoryExists, Microsoft.Build.Tasks.GetDirectories getDirectories, GetAssemblyName getAssemblyName, GetAssemblyMetadata getAssemblyMetadata, GetRegistrySubKeyNames getRegistrySubKeyNames, GetRegistrySubKeyDefaultValue getRegistrySubKeyDefaultValue, OpenBaseKey openBaseKey, GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntimeVersion, Version projectTargetFramework, FrameworkName targetFrameworkMoniker, TaskLoggingHelper log, string[] latestTargetFrameworkDirectories, bool copyLocalDependenciesWhenParentReferenceInGac, CheckIfAssemblyInGac checkIfAssemblyIsInGac)
 {
     this.log = log;
     this.findDependencies = findDependencies;
     this.findSatellites = findSatellites;
     this.findSerializationAssemblies = findSerializationAssemblies;
     this.findRelatedFiles = findRelatedFiles;
     this.frameworkPaths = frameworkPaths;
     this.allowedAssemblyExtensions = allowedAssemblyExtensions;
     this.relatedFileExtensions = relatedFileExtensions;
     this.installedAssemblies = installedAssemblies;
     this.targetProcessorArchitecture = targetProcessorArchitecture;
     this.fileExists = fileExists;
     this.directoryExists = directoryExists;
     this.getDirectories = getDirectories;
     this.getAssemblyName = getAssemblyName;
     this.getAssemblyMetadata = getAssemblyMetadata;
     this.getRuntimeVersion = getRuntimeVersion;
     this.projectTargetFramework = projectTargetFramework;
     this.targetedRuntimeVersion = targetedRuntimeVersion;
     this.openBaseKey = openBaseKey;
     this.targetFrameworkMoniker = targetFrameworkMoniker;
     this.latestTargetFrameworkDirectories = latestTargetFrameworkDirectories;
     this.copyLocalDependenciesWhenParentReferenceInGac = copyLocalDependenciesWhenParentReferenceInGac;
     this.checkIfAssemblyIsInGac = checkIfAssemblyIsInGac;
     this.compiledSearchPaths = AssemblyResolution.CompileSearchPaths(searchPaths, candidateAssemblyFiles, targetProcessorArchitecture, frameworkPaths, fileExists, getAssemblyName, getRegistrySubKeyNames, getRegistrySubKeyDefaultValue, openBaseKey, installedAssemblies, getRuntimeVersion, targetedRuntimeVersion);
 }
Ejemplo n.º 13
0
        public void TestIsCompatibleWithFrameworkName()
        {
            // Arrange 
            var profile = new NetPortableProfile(
                "ProfileXXX",
                new[] { 
                           new FrameworkName(".NETFramework, Version=4.5"), 
                           new FrameworkName("Silverlight, Version=4.0"), 
                           new FrameworkName("WindowsPhone, Version=7.1"), 
                      });

            var fw1 = new FrameworkName(".NETFramework, Version=4.0");
            var fw2 = new FrameworkName(".NETFramework, Version=4.5");
            var fw3 = new FrameworkName("Silverlight, Version=3.0");
            var fw4 = new FrameworkName("Silverlight, Version=5.0");
            var fw5 = new FrameworkName("WindowsPhone, Version=8.0");
            var fw6 = new FrameworkName("WindowsPhone, Version=7.0");
            var fw7 = new FrameworkName(".NETCore, Version=4.5");

            // Act & Assert
            Assert.False(profile.IsCompatibleWith(fw1));
            Assert.True(profile.IsCompatibleWith(fw2));
            Assert.False(profile.IsCompatibleWith(fw3));
            Assert.True(profile.IsCompatibleWith(fw4));
            Assert.True(profile.IsCompatibleWith(fw5));
            Assert.False(profile.IsCompatibleWith(fw6));
            Assert.False(profile.IsCompatibleWith(fw7));
        }
        public static string GetDisplayOrder(FrameworkName version)
        {
            var normalized = VersionUtility.GetShortFrameworkName(version);
            var order = "";
            if (normalized.StartsWith("net")) {
                order = "1-";
            }
            else if (normalized.StartsWith("win")) {
                order = "2-";
            }
            else if (normalized.StartsWith("wpa")) {
                order = "4-";
            }
            else if (normalized.StartsWith("wp")) {
                order = "3-";
            }
            else if (normalized.StartsWith("sl")) {
                order = "5-";
            }
            else if (normalized.StartsWith("mono", StringComparison.InvariantCultureIgnoreCase)) {
                order = "6-";
            }

            order += version.Version.Major + "." + version.Version.Minor;
            return order;
        }
Ejemplo n.º 15
0
 public LibraryExporter(LibraryManager manager, CompilationEngine compilationEngine, FrameworkName targetFramework, string configuration)
 {
     _manager = manager;
     _compilationEngine = compilationEngine;
     _targetFramework = targetFramework;
     _configuration = configuration;
 }
Ejemplo n.º 16
0
        public UninstallWalker(IPackageRepository repository,
                               IDependentsResolver dependentsResolver,
                               FrameworkName targetFramework,
                               ILogger logger,
                               bool removeDependencies,
                               bool forceRemove) 
            : base(targetFramework)
        {
            if (dependentsResolver == null)
            {
                throw new ArgumentNullException("dependentsResolver");
            }
            if (repository == null)
            {
                throw new ArgumentNullException("repository");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            Logger = logger;
            Repository = repository;
            DependentsResolver = dependentsResolver;
            Force = forceRemove;
            ThrowOnConflicts = true;
            Operations = new Stack<PackageOperation>();
            _removeDependencies = removeDependencies;
        }
 public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
 {
     var stringValue = (string) value;
     if (!String.IsNullOrEmpty(stringValue))
     {
         string[] parts = stringValue.Split(new[] {';', ','}, StringSplitOptions.RemoveEmptyEntries);
         if (parts.Length > 0)
         {
             var names = new FrameworkName[parts.Length];
             for (int i = 0; i < parts.Length; i++)
             {
                 try
                 {
                     names[i] = VersionUtility.ParseFrameworkName(parts[i]);
                     if (names[i] == VersionUtility.UnsupportedFrameworkName)
                     {
                         return DependencyProperty.UnsetValue;
                     }
                 }
                 catch (ArgumentException)
                 {
                     return DependencyProperty.UnsetValue;
                 }
             }
             return names;
         }
     }
     return new FrameworkName[0];
 }
Ejemplo n.º 18
0
        public InstallWalker(IPackageRepository localRepository,
                             IDependencyResolver2 dependencyResolver,
                             IPackageConstraintProvider constraintProvider,
                             FrameworkName targetFramework,
                             ILogger logger,
                             bool ignoreDependencies,
                             bool allowPrereleaseVersions,
                             DependencyVersion dependencyVersion)
            : base(targetFramework)
        {

            if (dependencyResolver == null)
            {
                throw new ArgumentNullException("dependencyResolver");
            }
            if (localRepository == null)
            {
                throw new ArgumentNullException("localRepository");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            Repository = localRepository;
            Logger = logger;
            DependencyResolver = dependencyResolver;
            _ignoreDependencies = ignoreDependencies;
            ConstraintProvider = constraintProvider;
            _operations = new OperationLookup();
            _allowPrereleaseVersions = allowPrereleaseVersions;
            DependencyVersion = dependencyVersion;
            CheckDowngrade = true;
        }
		public FakePackageManagementProject(string name)
		{
			FakeInstallPackageAction = new FakeInstallPackageAction(this);
			FakeUninstallPackageAction = new FakeUninstallPackageAction(this);
			
			this.Name = name;
			
			ConstraintProvider = NullConstraintProvider.Instance;
			TargetFramework = new FrameworkName(".NETFramework", new Version("4.0"));
			
			InstallPackageAction = (package, installAction) => {
				PackagePassedToInstallPackage = package;
				PackageOperationsPassedToInstallPackage = installAction.Operations;
				IgnoreDependenciesPassedToInstallPackage = installAction.IgnoreDependencies;
				AllowPrereleaseVersionsPassedToInstallPackage = installAction.AllowPrereleaseVersions;
			};
			
			UpdatePackageAction = (package, updateAction) => {
				PackagePassedToUpdatePackage = package;
				PackageOperationsPassedToUpdatePackage = updateAction.Operations;
				UpdateDependenciesPassedToUpdatePackage = updateAction.UpdateDependencies;
				AllowPrereleaseVersionsPassedToUpdatePackage = updateAction.AllowPrereleaseVersions;
				IsUpdatePackageCalled = true;
			};
		}
Ejemplo n.º 20
0
        public static IEnumerable<FrameworkName> SelectFrameworks(Runtime.Project project,
                                                                  IEnumerable<string> userSelection,
                                                                  FrameworkName fallbackFramework,
                                                                  out string errorMessage)
        {
            var specifiedFrameworks = userSelection.ToDictionary(f => f, FrameworkNameHelper.ParseFrameworkName);

            var projectFrameworks = new HashSet<FrameworkName>(
                project.GetTargetFrameworks()
                       .Select(c => c.FrameworkName));

            IEnumerable<FrameworkName> frameworks = null;

            if (projectFrameworks.Count > 0)
            {
                // Specified target frameworks have to be a subset of the project frameworks
                if (!ValidateFrameworks(projectFrameworks, specifiedFrameworks, out errorMessage))
                {
                    return null;
                }

                frameworks = specifiedFrameworks.Count > 0 ? specifiedFrameworks.Values : (IEnumerable<FrameworkName>)projectFrameworks;
            }
            else
            {
                frameworks = new[] { fallbackFramework };
            }

            errorMessage = string.Empty;
            return frameworks;
        }
        private bool GetActiveProject(out EnvDTE.Project project, out FrameworkName frameworkName)
        {
            project = null;
            frameworkName = null;

            IntPtr hierarchyPointer = IntPtr.Zero;
            IntPtr selectionContainerPointer = IntPtr.Zero;

            try
            {
                uint itemid;
                IVsMultiItemSelect multiItemSelect;

                Marshal.ThrowExceptionForHR(
                    _monitorSelection.GetCurrentSelection(
                        out hierarchyPointer,
                        out itemid,
                        out multiItemSelect,
                        out selectionContainerPointer));

                if (itemid != (uint)VSConstants.VSITEMID.Root)
                {
                    return false;
                }

                var hierarchy = Marshal.GetObjectForIUnknown(hierarchyPointer) as IVsHierarchy;
                if (hierarchy == null)
                {
                    return false;
                }

                object extensibilityObject;
                object targetFrameworkVersion;
                object targetFrameworkMonikerObject;
                Marshal.ThrowExceptionForHR(
                    hierarchy.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_ExtObject, out extensibilityObject));
                Marshal.ThrowExceptionForHR(
                    hierarchy.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID3.VSHPROPID_TargetFrameworkVersion, out targetFrameworkVersion));
                Marshal.ThrowExceptionForHR(
                    hierarchy.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID4.VSHPROPID_TargetFrameworkMoniker, out targetFrameworkMonikerObject));

                string targetFrameworkMoniker = targetFrameworkMonikerObject as string;
                frameworkName = new System.Runtime.Versioning.FrameworkName(targetFrameworkMoniker);

                project = extensibilityObject as EnvDTE.Project;
                return true;
            }
            finally
            {
                if (hierarchyPointer != IntPtr.Zero)
                {
                    Marshal.Release(hierarchyPointer);
                }

                if (selectionContainerPointer != IntPtr.Zero)
                {
                    Marshal.Release(selectionContainerPointer);
                }
            }
        }
Ejemplo n.º 22
0
        public async Task<WalkProviderMatch> FindLibrary(LibraryRange libraryRange, FrameworkName targetFramework)
        {
            var results = await _source.FindPackagesByIdAsync(libraryRange.Name);
            PackageInfo bestResult = null;
            foreach (var result in results)
            {
                if (VersionUtility.ShouldUseConsidering(
                    current: bestResult?.Version,
                    considering: result.Version,
                    ideal: libraryRange.VersionRange))
                {
                    bestResult = result;
                }
            }

            if (bestResult == null)
            {
                return null;
            }

            return new WalkProviderMatch
            {
                Library = new Library
                {
                    Name = bestResult.Id,
                    Version = bestResult.Version
                },
                Path = bestResult.ContentUri,
                Provider = this,
            };
        }
Ejemplo n.º 23
0
 public async Task<IEnumerable<LibraryDependency>> GetDependencies(WalkProviderMatch match, FrameworkName targetFramework)
 {
     using (var stream = await _source.OpenNuspecStreamAsync(new PackageInfo
     {
         Id = match.Library.Name,
         Version = match.Library.Version,
         ContentUri = match.Path
     }))
     {
         var metadata = (IPackageMetadata)Manifest.ReadFrom(stream, validateSchema: false).Metadata;
         IEnumerable<PackageDependencySet> dependencySet;
         if (VersionUtility.TryGetCompatibleItems(targetFramework, metadata.DependencySets, out dependencySet))
         {
             return dependencySet
                 .SelectMany(ds => ds.Dependencies)
                 .Select(d => new LibraryDependency
                 {
                     LibraryRange = new LibraryRange
                     {
                         Name = d.Id,
                         VersionRange = d.VersionSpec == null ? null : new SemanticVersionRange(d.VersionSpec)
                     }
                 })
                 .ToList();
         }
     }
     return Enumerable.Empty<LibraryDependency>();
 }
Ejemplo n.º 24
0
        public async Task<WalkProviderMatch> FindLibrary(LibraryRange libraryRange, FrameworkName targetFramework, bool includeUnlisted)
        {
            var results = await _source.FindPackagesByIdAsync(libraryRange.Name);
            PackageInfo bestResult = null;
            if(!includeUnlisted)
            {
                results = results.Where(p => p.Listed);
            }

            foreach (var result in results)
            {
                if (VersionUtility.ShouldUseConsidering(
                    current: bestResult?.Version,
                    considering: result.Version,
                    ideal: libraryRange.VersionRange))
                {
                    bestResult = result;
                }
            }

            if (bestResult == null)
            {
                return null;
            }

            return new WalkProviderMatch
            {
                Library = new LibraryIdentity(bestResult.Id, bestResult.Version, isGacOrFrameworkReference: false),
                Path = bestResult.ContentUri,
                Provider = this,
            };
        }
Ejemplo n.º 25
0
        public void GetFrameworkStringFromFrameworkName()
        {
            // Arrange
            var net40 = new FrameworkName(".NETFramework", new Version(4, 0));
            var net40Client = new FrameworkName(".NETFramework", new Version(4, 0), "Client");
            var sl3 = new FrameworkName("Silverlight", new Version(3, 0));
            var sl4 = new FrameworkName("Silverlight", new Version(4, 0));
            var wp7 = new FrameworkName("Silverlight", new Version(4, 0), "WindowsPhone");
            var netMicro41 = new FrameworkName(".NETMicroFramework", new Version(4, 1));

            // Act
            string net40Value = VersionUtility.GetFrameworkString(net40);
            string net40ClientValue = VersionUtility.GetFrameworkString(net40Client);
            string sl3Value = VersionUtility.GetFrameworkString(sl3);
            string sl4Value = VersionUtility.GetFrameworkString(sl4);
            string wp7Value = VersionUtility.GetFrameworkString(wp7);
            string netMicro41Value = VersionUtility.GetFrameworkString(netMicro41);

            // Assert
            Assert.AreEqual(".NETFramework4.0", net40Value);
            Assert.AreEqual(".NETFramework4.0-Client", net40ClientValue);
            Assert.AreEqual("Silverlight3.0", sl3Value);
            Assert.AreEqual("Silverlight4.0", sl4Value);
            Assert.AreEqual("Silverlight4.0-WindowsPhone", wp7Value);
            Assert.AreEqual(".NETMicroFramework4.1", netMicro41Value);
        }
        public LibraryDescription GetDescription(LibraryRange libraryRange, FrameworkName targetFramework)
        {
            if (!libraryRange.IsGacOrFrameworkReference)
            {
                return null;
            }

            var name = libraryRange.GetReferenceAssemblyName();
            var version = libraryRange.VersionRange?.MinVersion;

            string path;
            Version assemblyVersion;

            if (!FrameworkResolver.TryGetAssembly(name, targetFramework, out path, out assemblyVersion))
            {
                return null;
            }

            if (version == null || version.Version == assemblyVersion)
            {
                return new LibraryDescription(
                    libraryRange,
                    new LibraryIdentity(libraryRange.Name, new SemanticVersion(assemblyVersion), isGacOrFrameworkReference: true),
                    path,
                    LibraryTypes.ReferenceAssembly,
                    Enumerable.Empty<LibraryDependency>(),
                    new[] { name },
                    framework: targetFramework);
            }

            return null;
        }
Ejemplo n.º 27
0
 public BuildProjectSystem(string root, FrameworkName targetFramework, ITaskItem[] currentReferences)
     : base(root)
 {
     _targetFramework = targetFramework;
     _currentReferences = currentReferences;
     OutputReferences = new List<string>();
 }
Ejemplo n.º 28
0
 public PackageReference(string packageId, FrameworkName frameworkName, Version version, string specialVersion)
 {
     FrameworkName = frameworkName;
     PackageId = packageId;
     Version = version;
     SpecialVersion = specialVersion;
 }
Ejemplo n.º 29
0
        public InstallWalker(IPackageRepository localRepository,
                             IPackageRepository sourceRepository,
                             IPackageConstraintProvider constraintProvider,
                             FrameworkName targetFramework,
                             ILogger logger,
                             bool ignoreDependencies,
                             bool allowPrereleaseVersions)
            : base(targetFramework)
        {

            if (sourceRepository == null)
            {
                throw new ArgumentNullException("sourceRepository");
            }
            if (localRepository == null)
            {
                throw new ArgumentNullException("localRepository");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            Repository = localRepository;
            Logger = logger;
            SourceRepository = sourceRepository;
            _ignoreDependencies = ignoreDependencies;
            ConstraintProvider = constraintProvider;
            _operations = new OperationLookup();
            _allowPrereleaseVersions = allowPrereleaseVersions;
        }
Ejemplo n.º 30
0
        public static bool IsSatellitePackage(
            IPackage package, 
            IPackageRepository repository,
            FrameworkName targetFramework,
            out IPackage runtimePackage)
        {
            // A satellite package has the following properties:
            //     1) A package suffix that matches the package's language, with a dot preceding it
            //     2) A dependency on the package with the same Id minus the language suffix
            //     3) The dependency can be found by Id in the repository (as its path is needed for installation)
            // Example: foo.ja-jp, with a dependency on foo

            runtimePackage = null;

            if (package.IsSatellitePackage())
            {
                string runtimePackageId = package.Id.Substring(0, package.Id.Length - (package.Language.Length + 1));
                PackageDependency dependency = package.FindDependency(runtimePackageId, targetFramework);

                if (dependency != null)
                {
                    runtimePackage = repository.FindPackage(runtimePackageId, versionSpec: dependency.VersionSpec, allowPrereleaseVersions: true, allowUnlisted: true);
                }
            }

            return runtimePackage != null;
        }
Ejemplo n.º 31
0
        private void ExtractDependentPackages(IEnumerable <IPackage> dependencies, DirectoryInfo tempPath, FrameworkName framework)
        {
            dependencies.ForEach(
                pkg =>
            {
                Log.InfoFormat("Scanning {0}", pkg.Id);

                pkg.GetLibFiles()
                .ForEach(
                    file =>
                {
                    var outPath = new FileInfo(Path.Combine(tempPath.FullName, file.Path));

                    if (!VersionUtility.IsCompatible(framework, new[] { file.TargetFramework }))
                    {
                        Log.InfoFormat("Ignoring {0} as the target framework is not compatible", outPath);
                        return;
                    }

                    Directory.CreateDirectory(outPath.Directory.FullName);

                    using (var of = File.Create(outPath.FullName))
                    {
                        Log.InfoFormat("Writing {0} to {1}", file.Path, outPath);
                        file.GetStream().CopyTo(of);
                    }
                });
            });
        }
Ejemplo n.º 32
0
 public ICompilerOptions GetCompilerOptions(FrameworkName targetFramework, string configuration)
 {
     throw new NotImplementedException();
 }
 private static IList <string> GetPathToReferenceAssemblies(FrameworkName frameworkName)
 {
     return(ToolLocationHelper.GetPathToReferenceAssemblies(frameworkName));
 }
Ejemplo n.º 34
0
 /// <summary>
 /// Determines if there is a facade with the simple assembly name for the given target .NET Framework.
 /// </summary>
 /// <param name="simpleAssemblyName">The simple assembly name (e.g.:  System.Runtime) without file extension.</param>
 /// <param name="targetFrameworkName">The target .NET Framework.</param>
 /// <returns><c>true</c> if the assembly is a .NET Framework facade assembly; otherwise, <c>false</c>.</returns>
 public static bool IsFrameworkFacade(string simpleAssemblyName, FrameworkName targetFrameworkName)
 {
     return(IsFrameworkFacade(simpleAssemblyName, targetFrameworkName,
                              ToolLocationHelper.GetPathToReferenceAssemblies, FrameworkAssembliesDictionary));
 }
        public LibraryDescription GetDescription(LibraryRange libraryRange, FrameworkName targetFramework)
        {
            if (libraryRange.IsGacOrFrameworkReference)
            {
                return(null);
            }

            string name = libraryRange.Name;

            Project project;

            // Can't find a project file with the name so bail
            if (!_projectResolver.TryResolveProject(name, out project))
            {
                return(null);
            }

            // This never returns null
            var targetFrameworkInfo         = project.GetTargetFramework(targetFramework);
            var targetFrameworkDependencies = new List <LibraryDependency>(targetFrameworkInfo.Dependencies);

            if (VersionUtility.IsDesktop(targetFramework))
            {
                targetFrameworkDependencies.Add(new LibraryDependency
                {
                    LibraryRange = new LibraryRange("mscorlib", frameworkReference: true)
                });

                targetFrameworkDependencies.Add(new LibraryDependency
                {
                    LibraryRange = new LibraryRange("System", frameworkReference: true)
                });

                targetFrameworkDependencies.Add(new LibraryDependency
                {
                    LibraryRange = new LibraryRange("System.Core", frameworkReference: true)
                });

                targetFrameworkDependencies.Add(new LibraryDependency
                {
                    LibraryRange = new LibraryRange("Microsoft.CSharp", frameworkReference: true)
                });
            }

            var dependencies = project.Dependencies.Concat(targetFrameworkDependencies).ToList();

            var loadableAssemblies = new List <string>();

            if (project.IsLoadable)
            {
                loadableAssemblies.Add(project.Name);
            }

            // Mark the library as unresolved if there were specified frameworks
            // and none of them resolved
            bool unresolved = targetFrameworkInfo.FrameworkName == null &&
                              project.GetTargetFrameworks().Any();

            return(new LibraryDescription
            {
                LibraryRange = libraryRange,
                Identity = new Library
                {
                    Name = project.Name,
                    Version = project.Version
                },
                Type = "Project",
                Path = project.ProjectFilePath,
                Framework = targetFrameworkInfo.FrameworkName,
                Dependencies = dependencies,
                LoadableAssemblies = loadableAssemblies,
                Resolved = !unresolved
            });
        }
Ejemplo n.º 36
0
 public ReferenceAssemblyContext(Microsoft.Expression.Project.ReferenceAssemblyMode referenceAssemblyMode, FrameworkName targetFramework)
 {
     this.identifier                      = Guid.NewGuid();
     this.referenceAssemblyMode           = referenceAssemblyMode;
     this.targetFramework                 = targetFramework;
     this.defaultUniverse                 = new ReferenceAssemblyContext.ReferenceAssemblyUniverse(this);
     this.defaultUniverse.OnResolveEvent += new EventHandler <ResolveAssemblyNameEventArgs>(this.DefaultUniverse_OnResolveEvent);
 }
Ejemplo n.º 37
0
 public async Task <IEnumerable <LibraryDependency> > GetDependencies(WalkProviderMatch match, FrameworkName targetFramework)
 {
     using (var stream = await _source.OpenNuspecStreamAsync(new PackageInfo
     {
         Id = match.Library.Name,
         Version = match.Library.Version,
         ContentUri = match.Path
     }))
     {
         var metadata = (IPackageMetadata)Manifest.ReadFrom(stream, validateSchema: false).Metadata;
         IEnumerable <PackageDependencySet> dependencySet;
         if (VersionUtility.GetNearest(targetFramework, metadata.DependencySets, out dependencySet))
         {
             return(dependencySet
                    .SelectMany(ds => ds.Dependencies)
                    .Select(d => new LibraryDependency
             {
                 LibraryRange = new LibraryRange(d.Id, frameworkReference: false)
                 {
                     VersionRange = d.VersionSpec == null ? null : new SemanticVersionRange(d.VersionSpec)
                 }
             })
                    .ToList());
         }
     }
     return(Enumerable.Empty <LibraryDependency>());
 }
Ejemplo n.º 38
0
        private static bool IsSupportedOnTarget(IApiCatalogLookup catalog, string memberDocId, FrameworkName target, out Version status)
        {
            status = null;

            // If the member is part of the API surface, no need to report it.
            if (catalog.IsMemberInTarget(memberDocId, target, out status))
            {
                return(true);
            }

            var sourceEquivalent = catalog.GetSourceCompatibilityEquivalent(memberDocId);

            if (!string.IsNullOrEmpty(sourceEquivalent) && catalog.IsMemberInTarget(sourceEquivalent, target, out status))
            {
                return(true);
            }

            return(false);
        }
Ejemplo n.º 39
0
 public static RuntimeFramework FromFrameworkName(FrameworkName frameworkName)
 {
     return(new RuntimeFramework(Runtime.FromFrameworkIdentifier(frameworkName.Identifier), frameworkName.Version, frameworkName.Profile));
 }
Ejemplo n.º 40
0
 public static string ToShortNameOrNull(this FrameworkName frameworkName)
 {
     return(frameworkName == null ? null : VersionUtility.GetShortFrameworkName(frameworkName));
 }
Ejemplo n.º 41
0
        private static Version GetEffectiveFrameworkVersion(FrameworkName projectFramework, FrameworkName targetFrameworkVersion)
        {
            if (targetFrameworkVersion.IsPortableFramework())
            {
                NetPortableProfile profile = NetPortableProfile.Parse(targetFrameworkVersion.Profile);
                if (profile != null)
                {
                    // if it's a portable library, return the version of the matching framework
                    var compatibleFramework = profile.SupportedFrameworks.FirstOrDefault(f => VersionUtility.IsCompatible(projectFramework, f));
                    if (compatibleFramework != null)
                    {
                        return(compatibleFramework.Version);
                    }
                }
            }

            return(targetFrameworkVersion.Version);
        }
 public virtual void Initialize(IEnumerable <LibraryDescription> dependencies, FrameworkName targetFramework, string runtimeIdentifier)
 {
     Dependencies = dependencies;
 }
Ejemplo n.º 43
0
        /// <summary>
        /// Attempt to calculate how compatible a portable framework folder is to a portable project.
        /// The two portable frameworks passed to this method MUST be compatible with each other.
        /// </summary>
        /// <remarks>
        /// The returned score will be negative value.
        /// </remarks>
        internal static int GetCompatibilityBetweenPortableLibraryAndPortableLibrary(FrameworkName frameworkName, FrameworkName targetFrameworkName)
        {
            // Algorithms: Give a score from 0 to N indicating how close *in version* each package platform is the project’s platforms
            // and then choose the folder with the lowest score. If the score matches, choose the one with the least platforms.
            //
            // For example:
            //
            // Project targeting: .NET 4.5 + SL5 + WP71
            //
            // Package targeting:
            // .NET 4.5 (0) + SL5 (0) + WP71 (0)                            == 0
            // .NET 4.5 (0) + SL5 (0) + WP71 (0) + Win8 (0)                 == 0
            // .NET 4.5 (0) + SL4 (1) + WP71 (0) + Win8 (0)                 == 1
            // .NET 4.0 (1) + SL4 (1) + WP71 (0) + Win8 (0)                 == 2
            // .NET 4.0 (1) + SL4 (1) + WP70 (1) + Win8 (0)                 == 3
            //
            // Above, there’s two matches with the same result, choose the one with the least amount of platforms.
            //
            // There will be situations, however, where there is still undefined behavior, such as:
            //
            // .NET 4.5 (0) + SL4 (1) + WP71 (0)                            == 1
            // .NET 4.0 (1) + SL5 (0) + WP71 (0)                            == 1

            NetPortableProfile frameworkProfile = NetPortableProfile.Parse(frameworkName.Profile);

            Debug.Assert(frameworkName != null);

            NetPortableProfile targetFrameworkProfile = NetPortableProfile.Parse(targetFrameworkName.Profile);

            Debug.Assert(targetFrameworkName != null);

            int score = 0;

            foreach (var framework in targetFrameworkProfile.SupportedFrameworks)
            {
                var matchingFramework = frameworkProfile.SupportedFrameworks.FirstOrDefault(f => IsCompatible(f, framework));
                if (matchingFramework != null && matchingFramework.Version > framework.Version)
                {
                    score++;
                }
            }

            // This is to ensure that if two portable frameworks have the same score,
            // we pick the one that has less number of supported platforms.
            score = score * 50 + targetFrameworkProfile.SupportedFrameworks.Count;

            // Our algorithm returns lowest score for the most compatible framework.
            // However, the caller of this method expects it to have the highest score.
            // Hence, we return the negative value of score here.
            return(-score);
        }
 public IEnumerable <string> GetAttemptedPaths(FrameworkName targetFramework)
 {
     return(_projectResolver.SearchPaths.Select(p => Path.Combine(p, "{name}", "project.json")));
 }
Ejemplo n.º 45
0
        private FrameworkVersion GetFrameworkVersionFromFrameworkName(FrameworkName frameworkName, TargetPlatform targetPlatform)
        {
            if (targetPlatform == TargetPlatform.WinRT)
            {
                if (frameworkName.Identifier == ".NETPortable")
                {
                    if (frameworkName.Version == new Version(4, 0))
                    {
                        return(FrameworkVersion.NetPortableV4_0);
                    }
                    else if (frameworkName.Version == new Version(4, 6))
                    {
                        return(FrameworkVersion.NetPortableV4_6);
                    }
                    else if (frameworkName.Version == new Version(4, 5))
                    {
                        return(FrameworkVersion.NetPortableV4_5);
                    }
                    else if (frameworkName.Version == new Version(5, 0))
                    {
                        return(FrameworkVersion.NetPortableV5_0);
                    }
                }
                else if (frameworkName.Identifier == ".NETCore")
                {
                    if (frameworkName.Version == new Version(4, 5))
                    {
                        return(FrameworkVersion.WinRT_4_5);
                    }
                    else if (frameworkName.Version == new Version(4, 5, 1))
                    {
                        return(FrameworkVersion.WinRT_4_5_1);
                    }
                    else if (frameworkName.Version == new Version(5, 0))
                    {
                        return(FrameworkVersion.UWP);
                    }
                }
                else if (frameworkName.Identifier == "WindowsPhoneApp")
                {
                    return(FrameworkVersion.WindowsPhone);
                }
            }
            else if (targetPlatform == TargetPlatform.NetCore)
            {
                if (frameworkName.Identifier == ".NETCoreApp")
                {
                    /* AGPL */
                    if (frameworkName.Version == new Version(5, 0))
                    {
                        return(FrameworkVersion.NetCoreV5_0);
                    }
                    else if (frameworkName.Version == new Version(3, 1))
                    {
                        return(FrameworkVersion.NetCoreV3_1);
                    }
                    else if (frameworkName.Version == new Version(3, 0))
                    {
                        return(FrameworkVersion.NetCoreV3_0);
                    }
                    else if (frameworkName.Version == new Version(2, 2))
                    {
                        return(FrameworkVersion.NetCoreV2_2);
                    }
                    /* End AGPL */
                    else if (frameworkName.Version == new Version(2, 1))
                    {
                        return(FrameworkVersion.NetCoreV2_1);
                    }
                    else if (frameworkName.Version == new Version(2, 0))
                    {
                        return(FrameworkVersion.NetCoreV2_0);
                    }
                    else if (frameworkName.Version == new Version(1, 1))
                    {
                        return(FrameworkVersion.NetCoreV1_1);
                    }
                    else if (frameworkName.Version == new Version(1, 0))
                    {
                        return(FrameworkVersion.NetCoreV1_0);
                    }
                }
            }
            /* AGPL */
            else if (targetPlatform == TargetPlatform.NetStandard)
            {
                if (frameworkName.Identifier == ".NETStandard")
                {
                    if (frameworkName.Version == new Version(2, 1))
                    {
                        return(FrameworkVersion.NetStandardV2_1);
                    }
                    else if (frameworkName.Version == new Version(2, 0))
                    {
                        return(FrameworkVersion.NetStandardV2_0);
                    }
                    else if (frameworkName.Version == new Version(1, 6))
                    {
                        return(FrameworkVersion.NetStandardV1_6);
                    }
                    else if (frameworkName.Version == new Version(1, 5))
                    {
                        return(FrameworkVersion.NetStandardV1_5);
                    }
                    else if (frameworkName.Version == new Version(1, 4))
                    {
                        return(FrameworkVersion.NetStandardV1_4);
                    }
                    else if (frameworkName.Version == new Version(1, 3))
                    {
                        return(FrameworkVersion.NetStandardV1_3);
                    }
                    else if (frameworkName.Version == new Version(1, 2))
                    {
                        return(FrameworkVersion.NetStandardV1_2);
                    }
                    else if (frameworkName.Version == new Version(1, 1))
                    {
                        return(FrameworkVersion.NetStandardV1_1);
                    }
                    else if (frameworkName.Version == new Version(1, 0))
                    {
                        return(FrameworkVersion.NetStandardV1_0);
                    }
                }
            }
            /* End AGPL */
            else if (targetPlatform == TargetPlatform.Xamarin)
            {
                if (frameworkName.Identifier == "MonoAndroid")
                {
                    return(FrameworkVersion.XamarinAndroid);
                }
                else if (frameworkName.Identifier == "Xamarin.iOS")
                {
                    return(FrameworkVersion.XamarinIOS);
                }
            }

            return(this.DefaultFrameworkVersion);
        }
Ejemplo n.º 46
0
 public override string ToString()
 {
     return(FrameworkName.GetShortFolderName());
 }
Ejemplo n.º 47
0
        /// <summary>
        /// Read everything from the assembly in a single stream.
        /// </summary>
        /// <returns></returns>
        private void CorePopulateMetadata()
        {
            if (_metadataRead)
            {
                return;
            }

            lock (this)
            {
                if (_metadataRead)
                {
                    return;
                }

                using (var stream = File.OpenRead(_sourceFile))
                    using (var peFile = new PEReader(stream))
                    {
                        var metadataReader = peFile.GetMetadataReader();

                        var assemblyReferences = metadataReader.AssemblyReferences;

                        List <AssemblyNameExtension> ret = new List <AssemblyNameExtension>(assemblyReferences.Count);

                        foreach (var handle in assemblyReferences)
                        {
                            var assemblyName = GetAssemblyName(metadataReader, handle);
                            ret.Add(new AssemblyNameExtension(assemblyName));
                        }

                        _assemblyDependencies = ret.ToArray();

                        foreach (var attrHandle in metadataReader.GetAssemblyDefinition().GetCustomAttributes())
                        {
                            var attr = metadataReader.GetCustomAttribute(attrHandle);

                            var ctorHandle = attr.Constructor;
                            if (ctorHandle.Kind != HandleKind.MemberReference)
                            {
                                continue;
                            }

                            var container = metadataReader.GetMemberReference((MemberReferenceHandle)ctorHandle).Parent;
                            var name      = metadataReader.GetTypeReference((TypeReferenceHandle)container).Name;
                            if (!string.Equals(metadataReader.GetString(name), "TargetFrameworkAttribute"))
                            {
                                continue;
                            }

                            var arguments = GetFixedStringArguments(metadataReader, attr);
                            if (arguments.Count == 1)
                            {
                                _frameworkName = new FrameworkName(arguments[0]);
                            }
                        }

                        var assemblyFilesCollection = metadataReader.AssemblyFiles;

                        List <string> assemblyFiles = new List <string>(assemblyFilesCollection.Count);

                        foreach (var fileHandle in assemblyFilesCollection)
                        {
                            assemblyFiles.Add(metadataReader.GetString(metadataReader.GetAssemblyFile(fileHandle).Name));
                        }

                        _assemblyFiles = assemblyFiles.ToArray();
                    }

                _metadataRead = true;
            }
        }
Ejemplo n.º 48
0
        public void It_implicitly_defines_compilation_constants_for_the_target_framework(string targetFramework, string[] expectedDefines, bool buildOnlyOnWindows)
        {
            bool shouldCompile = true;

            var testAsset = _testAssetsManager
                            .CopyTestAsset("AppWithLibrary", "ImplicitFrameworkConstants", targetFramework)
                            .WithSource()
                            .WithProjectChanges(project =>
            {
                //  Update target framework in project
                var ns = project.Root.Name.Namespace;
                var targetFrameworkProperties = project.Root
                                                .Elements(ns + "PropertyGroup")
                                                .Elements(ns + "TargetFramework")
                                                .ToList();

                targetFrameworkProperties.Count.Should().Be(1);

                if (targetFramework.Contains(",Version="))
                {
                    //  We use the full TFM for frameworks we don't have built-in support for targeting, so we don't want to run the Compile target
                    shouldCompile = false;

                    var frameworkName = new FrameworkName(targetFramework);

                    var targetFrameworkProperty = targetFrameworkProperties.Single();
                    targetFrameworkProperty.AddBeforeSelf(new XElement(ns + "TargetFrameworkIdentifier", frameworkName.Identifier));
                    targetFrameworkProperty.AddBeforeSelf(new XElement(ns + "TargetFrameworkVersion", "v" + frameworkName.Version.ToString()));
                    if (!string.IsNullOrEmpty(frameworkName.Profile))
                    {
                        targetFrameworkProperty.AddBeforeSelf(new XElement(ns + "TargetFrameworkProfile", frameworkName.Profile));
                    }

                    //  For the NuGet restore task to work with package references, it needs the TargetFramework property to be set.
                    //  Otherwise we would just remove the property.
                    targetFrameworkProperty.SetValue(targetFramework);
                }
                else
                {
                    shouldCompile = true;
                    targetFrameworkProperties.Single().SetValue(targetFramework);
                }
            });

            if (buildOnlyOnWindows && !RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                shouldCompile = false;
            }

            var libraryProjectDirectory = Path.Combine(testAsset.TestRoot, "TestLibrary");

            var getValuesCommand = new GetValuesCommand(Log, libraryProjectDirectory,
                                                        targetFramework, "DefineConstants")
            {
                ShouldCompile = shouldCompile
            };

            getValuesCommand
            .Execute()
            .Should()
            .Pass();

            var definedConstants = getValuesCommand.GetValues();

            definedConstants.Should().BeEquivalentTo(new[] { "DEBUG", "TRACE" }.Concat(expectedDefines).ToArray());
        }
Ejemplo n.º 49
0
 private static bool IsDesktop(FrameworkName frameworkName)
 {
     return(frameworkName.Identifier == ".NETFramework" ||
            frameworkName.Identifier == "Asp.Net" ||
            frameworkName.Identifier == "DNX");
 }
Ejemplo n.º 50
0
        /// <summary>
        /// Get the framework name from the assembly.
        /// </summary>
        private FrameworkName GetFrameworkName()
        {
// Disabling use of System.Reflection in case of MONO, because
// Assembly.GetCustomAttributes* for an attribute which belongs
// to an assembly that mono cannot find, causes a crash!
// Instead, opt for using PEReader and friends to get that info
#if FEATURE_ASSEMBLY_LOADFROM && !MONO
            if (!NativeMethodsShared.IsWindows)
            {
                if (String.Equals(Environment.GetEnvironmentVariable("MONO29679"), "1", StringComparison.OrdinalIgnoreCase))
                {
                    // Getting custom attributes in CoreFx contract assemblies is busted
                    // https://bugzilla.xamarin.com/show_bug.cgi?id=29679
                    return(null);
                }

                CustomAttributeData attr = null;

                foreach (CustomAttributeData a in _assembly.GetCustomAttributesData())
                {
                    try
                    {
                        if (a.AttributeType == typeof(TargetFrameworkAttribute))
                        {
                            attr = a;
                            break;
                        }
                    }
                    catch
                    {
                    }
                }

                string name = null;
                if (attr != null)
                {
                    name = (string)attr.ConstructorArguments[0].Value;
                }
                return(name == null ? null : new FrameworkName(name));
            }

            FrameworkName frameworkAttribute = null;
            try
            {
                var import2 = (IMetaDataImport2)_assemblyImport;

                _assemblyImport.GetAssemblyFromScope(out uint assemblyScope);
                int hr = import2.GetCustomAttributeByName(assemblyScope, s_targetFrameworkAttribute, out IntPtr data, out uint valueLen);

                // get the AssemblyTitle
                if (hr == NativeMethodsShared.S_OK)
                {
                    // if an AssemblyTitle exists, parse the contents of the blob
                    if (NativeMethods.TryReadMetadataString(_sourceFile, data, valueLen, out string frameworkNameAttribute))
                    {
                        if (!String.IsNullOrEmpty(frameworkNameAttribute))
                        {
                            frameworkAttribute = new FrameworkName(frameworkNameAttribute);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (ExceptionHandling.IsCriticalException(e))
                {
                    throw;
                }
            }

            return(frameworkAttribute);
#else
            CorePopulateMetadata();
            return(_frameworkName);
#endif
        }
Ejemplo n.º 51
0
 protected PackageWalker(FrameworkName targetFramework)
 {
     _targetFramework  = targetFramework;
     Marker            = new PackageMarker();
     DependencyVersion = DependencyVersion.Lowest;
 }
Ejemplo n.º 52
0
        private static CompilationSettings ToCompilationSettings(ICompilerOptions compilerOptions, FrameworkName targetFramework)
        {
            var options = GetCompilationOptions(compilerOptions);

            // Disable 1702 until roslyn turns this off by default
            options = options.WithSpecificDiagnosticOptions(new Dictionary <string, ReportDiagnostic>
            {
                { "CS1702", ReportDiagnostic.Suppress },
                { "CS1705", ReportDiagnostic.Suppress }
            });
            AssemblyIdentityComparer assemblyIdentityComparer =
#if DNX451
                IsDesktop(targetFramework) ?
                DesktopAssemblyIdentityComparer.Default :
#endif
                null;

            options = options.WithAssemblyIdentityComparer(assemblyIdentityComparer);
            LanguageVersion languageVersion;

            if (!Enum.TryParse(value: compilerOptions.LanguageVersion, ignoreCase: true, result: out languageVersion))
            {
                languageVersion = LanguageVersion.CSharp6;
            }
            var settings = new CompilationSettings
            {
                LanguageVersion    = languageVersion,
                Defines            = compilerOptions.Defines ?? Enumerable.Empty <string>(),
                CompilationOptions = options
            };

            return(settings);
        }
Ejemplo n.º 53
0
 /// <summary>
 /// Sets the built framework.
 /// </summary>
 /// <param name="builtFramework">The target framework.</param>
 public void SetBuiltFramework(FrameworkName builtFramework)
 {
     Runtime.BuiltFramework = builtFramework;
 }
Ejemplo n.º 54
0
 /// <summary>
 /// This function checks if there is a framework assembly of assemblyName and of version > availableVersion
 /// in targetFramework. NOTE that this function is only applicable for .NETFramework and returns false for
 /// all the other targetFrameworks
 /// </summary>
 public static bool IsHigherAssemblyVersionInFramework(string simpleAssemblyName, Version availableVersion, FrameworkName targetFrameworkName)
 {
     return(IsHigherAssemblyVersionInFramework(simpleAssemblyName, availableVersion, targetFrameworkName,
                                               ToolLocationHelper.GetPathToReferenceAssemblies, FrameworkAssembliesDictionary));
 }
Ejemplo n.º 55
0
        public ApplicationHostContext(IServiceProvider serviceProvider,
                                      string projectDirectory,
                                      string packagesDirectory,
                                      string configuration,
                                      FrameworkName targetFramework,
                                      ICache cache,
                                      ICacheContextAccessor cacheContextAccessor,
                                      INamedCacheDependencyProvider namedCacheDependencyProvider,
                                      IAssemblyLoadContextFactory loadContextFactory = null)
        {
            ProjectDirectory           = projectDirectory;
            RootDirectory              = Runtime.ProjectResolver.ResolveRootDirectory(ProjectDirectory);
            ProjectResolver            = new ProjectResolver(ProjectDirectory, RootDirectory);
            FrameworkReferenceResolver = new FrameworkReferenceResolver();
            _serviceProvider           = new ServiceProvider(serviceProvider);

            PackagesDirectory = packagesDirectory ?? NuGetDependencyResolver.ResolveRepositoryPath(RootDirectory);

            var referenceAssemblyDependencyResolver = new ReferenceAssemblyDependencyResolver(FrameworkReferenceResolver);

            NuGetDependencyProvider = new NuGetDependencyResolver(PackagesDirectory, RootDirectory);
            var gacDependencyResolver = new GacDependencyResolver();

            ProjectDepencyProvider       = new ProjectReferenceDependencyProvider(ProjectResolver);
            UnresolvedDependencyProvider = new UnresolvedDependencyProvider();

            DependencyWalker = new DependencyWalker(new IDependencyProvider[] {
                ProjectDepencyProvider,
                NuGetDependencyProvider,
                referenceAssemblyDependencyResolver,
                gacDependencyResolver,
                UnresolvedDependencyProvider
            });

            UnresolvedDependencyProvider.AttemptedProviders = DependencyWalker.DependencyProviders;

            var compositeDependencyExporter = new CompositeLibraryExportProvider(new ILibraryExportProvider[] {
                new ProjectLibraryExportProvider(ProjectResolver, ServiceProvider),
                referenceAssemblyDependencyResolver,
                gacDependencyResolver,
                NuGetDependencyProvider
            });

            LibraryManager = new LibraryManager(targetFramework, configuration, DependencyWalker,
                                                compositeDependencyExporter, cache);

            AssemblyLoadContextFactory = loadContextFactory ?? new AssemblyLoadContextFactory(ServiceProvider);

            // Default services
            _serviceProvider.Add(typeof(IApplicationEnvironment), new ApplicationEnvironment(Project, targetFramework, configuration));
            _serviceProvider.Add(typeof(ILibraryExportProvider), compositeDependencyExporter);
            _serviceProvider.Add(typeof(IProjectResolver), ProjectResolver);
            _serviceProvider.Add(typeof(IFileWatcher), NoopWatcher.Instance);

            _serviceProvider.Add(typeof(NuGetDependencyResolver), NuGetDependencyProvider);
            _serviceProvider.Add(typeof(ProjectReferenceDependencyProvider), ProjectDepencyProvider);
            _serviceProvider.Add(typeof(ILibraryManager), LibraryManager);
            _serviceProvider.Add(typeof(ICache), cache);
            _serviceProvider.Add(typeof(ICacheContextAccessor), cacheContextAccessor);
            _serviceProvider.Add(typeof(INamedCacheDependencyProvider), namedCacheDependencyProvider);
            _serviceProvider.Add(typeof(IAssemblyLoadContextFactory), AssemblyLoadContextFactory);
        }
Ejemplo n.º 56
0
        public void ShortFrameworkNamesAreCorrect(string longName, string version, string shortName)
        {
            var fx = new FrameworkName(longName, Version.Parse(version));

            Assert.Equal(shortName, VersionUtility.GetShortFrameworkName(fx));
        }
Ejemplo n.º 57
0
        public override ConversionType GetVersion(ConversionTarget project)
        {
            ConversionType conversionType;

            this.silverlightSolution = false;
            this.sketchFlowSolution  = false;
            this.frameworkSolution   = false;
            if (!project.IsSolution)
            {
                return(ConversionType.Unknown);
            }
            using (IEnumerator <IProjectStore> enumerator = this.contextProjectStores.GetEnumerator())
            {
                do
                {
                    if (!enumerator.MoveNext())
                    {
                        break;
                    }
                    IProjectStore current             = enumerator.Current;
                    FrameworkName targetFrameworkName = ProjectStoreHelper.GetTargetFrameworkName(current);
                    if (targetFrameworkName == null)
                    {
                        continue;
                    }
                    if (!this.frameworkSolution && targetFrameworkName.Identifier == ".NETFramework")
                    {
                        this.frameworkSolution = true;
                    }
                    if (!this.silverlightSolution && targetFrameworkName.Identifier == "Silverlight")
                    {
                        this.silverlightSolution = true;
                    }
                    if (this.sketchFlowSolution || !ProjectStoreHelper.IsSketchFlowProject(current))
                    {
                        continue;
                    }
                    this.sketchFlowSolution = true;
                }while (!this.silverlightSolution || !this.sketchFlowSolution || !this.frameworkSolution);
            }
            if (!this.silverlightSolution && !this.frameworkSolution)
            {
                return(ConversionType.Unknown);
            }
            ILicenseService service = base.Services.GetService <ILicenseService>();

            if (this.sketchFlowSolution && service != null && !LicensingHelper.IsSketchFlowLicensed(service))
            {
                return(ConversionType.Unknown);
            }
            using (IEnumerator <ConversionTarget> enumerator1 = this.GetConversionTargets().GetEnumerator())
            {
                while (enumerator1.MoveNext())
                {
                    ConversionTarget conversionTarget = enumerator1.Current;
                    if (!ConversionHelper.CheckAndAddFile(conversionTarget, this.Converters, this.VersionMapping, true).Any <UpgradeAction>())
                    {
                        continue;
                    }
                    conversionType = ConversionType.SolutionBlendV3;
                    return(conversionType);
                }
                return(ConversionType.SolutionBlendV4);
            }
            return(conversionType);
        }
Ejemplo n.º 58
0
        internal UpgradeWizard.UpgradeResponse PromptToUpgrade(Dictionary <ConversionType, ConversionType> conversionMapping, out bool?doNotShowAgain, ref string backupLocation, out IEnumerable <UpgradeAction> proposedUpgrades)
        {
            doNotShowAgain   = null;
            proposedUpgrades = Enumerable.Empty <UpgradeAction>();
            List <UpgradeAction> list = this.GetProposedUpgrades(conversionMapping).ToList <UpgradeAction>();

            if (list.Count == 0)
            {
                return(UpgradeWizard.UpgradeResponse.DontUpgrade);
            }
            List <ConversionType> conversionTypes  = new List <ConversionType>();
            List <ConversionType> conversionTypes1 = new List <ConversionType>();
            bool flag  = false;
            bool flag1 = false;

            if (!this.sketchFlowSolution)
            {
                using (IEnumerator <ConversionTarget> enumerator = this.GetConversionTargets().GetEnumerator())
                {
                    do
                    {
Label0:
                        if (!enumerator.MoveNext())
                        {
                            break;
                        }
                        ConversionTarget current             = enumerator.Current;
                        FrameworkName    targetFrameworkName = ProjectStoreHelper.GetTargetFrameworkName(current.ProjectStore);
                        if (targetFrameworkName == null || targetFrameworkName.Version == CommonVersions.Version4_0)
                        {
                            goto Label0;
                        }
                        else if (flag || !ProjectStoreHelper.UsesSilverlight(current.ProjectStore) || targetFrameworkName.Version.Major <= 1)
                        {
                            if (flag1 || !ProjectStoreHelper.UsesWpf(current.ProjectStore) || !(targetFrameworkName.Version >= CommonVersions.Version3_0))
                            {
                                continue;
                            }
                            flag1 = true;
                        }
                        else
                        {
                            flag = true;
                        }
                    }while (!flag1 || !flag);
                }
                if (flag1)
                {
                    conversionTypes1.Add(ConversionType.ProjectWpf35);
                    conversionTypes1.Add(ConversionType.ProjectWpf40);
                }
                if (flag)
                {
                    conversionTypes.Add(ConversionType.ProjectSilverlight3);
                    conversionTypes.Add(ConversionType.ProjectSilverlight4);
                }
            }
            bool flag2 = this.targetStore != null;
            bool flag3 = !flag2;
            bool flag4 = !flag2;
            UpgradeProjectDialog upgradeProjectDialog = new UpgradeProjectDialog(base.Services.ExpressionInformationService(), conversionTypes, conversionTypes1, flag3, flag4);
            ProjectDialogResult  projectDialogResult  = upgradeProjectDialog.ShowProjectDialog();

            doNotShowAgain = new bool?(upgradeProjectDialog.DoNotShowAgain);
            if (upgradeProjectDialog.Backup && projectDialogResult == ProjectDialogResult.Yes)
            {
                string      parentDirectory              = Microsoft.Expression.Framework.Documents.PathHelper.GetParentDirectory(Microsoft.Expression.Framework.Documents.PathHelper.GetDirectory(base.Solution.DocumentReference.Path));
                CultureInfo invariantCulture             = CultureInfo.InvariantCulture;
                string      newNameCopyTemplate          = StringTable.NewNameCopyTemplate;
                object[]    fileNameWithoutExtension     = new object[] { Path.GetFileNameWithoutExtension(base.Solution.DocumentReference.DisplayName) };
                string      availableFileOrDirectoryName = string.Format(invariantCulture, newNameCopyTemplate, fileNameWithoutExtension);
                availableFileOrDirectoryName = Microsoft.Expression.Framework.Documents.PathHelper.GetAvailableFileOrDirectoryName(availableFileOrDirectoryName, null, parentDirectory, false);
                backupLocation = Path.Combine(parentDirectory, availableFileOrDirectoryName);
                string    str        = backupLocation;
                Exception exception1 = null;
                using (IDisposable disposable = TemporaryCursor.SetWaitCursor())
                {
                    ErrorHandling.HandleBasicExceptions(() => ProjectManager.CopyDirectory(Microsoft.Expression.Framework.Documents.PathHelper.GetDirectory(this.Solution.DocumentReference.Path), str), (Exception exception) => exception1 = exception);
                }
                if (exception1 != null)
                {
                    ErrorArgs errorArg = new ErrorArgs()
                    {
                        Message      = StringTable.UpgradeBackupFailed,
                        Exception    = exception1,
                        AutomationId = "BackupProjectErrorDialog"
                    };
                    base.Services.MessageDisplayService().ShowError(errorArg);
                    return(UpgradeWizard.UpgradeResponse.Cancel);
                }
            }
            switch (projectDialogResult)
            {
            case ProjectDialogResult.Yes:
            {
                if (this.sketchFlowSolution)
                {
                    proposedUpgrades = list;
                }
                else
                {
                    this.VersionMapping[ConversionType.ProjectSilverlight2] = upgradeProjectDialog.SelectedSilverlightVersion;
                    this.VersionMapping[ConversionType.ProjectSilverlight3] = upgradeProjectDialog.SelectedSilverlightVersion;
                    this.VersionMapping[ConversionType.ProjectWpf30]        = upgradeProjectDialog.SelectedDotNetVersion;
                    this.VersionMapping[ConversionType.ProjectWpf35]        = upgradeProjectDialog.SelectedDotNetVersion;
                    proposedUpgrades = this.GetProposedUpgrades(conversionMapping);
                }
                return(UpgradeWizard.UpgradeResponse.Upgrade);
            }

            case ProjectDialogResult.No:
            {
                return(UpgradeWizard.UpgradeResponse.DontUpgrade);
            }
            }
            return(UpgradeWizard.UpgradeResponse.Cancel);
        }
 private CompatibleFramework GetFullCompatFramework(FrameworkName frameworkName)
 {
     return(new CompatibleFramework {
         Version = frameworkName.Version.ToString(), SupportedRuntime = this.PatchCLRVersion(Util.GetClrVersion(frameworkName.Version.ToString())), Profile = "Full"
     });
 }
 public virtual void Initialize(IEnumerable <LibraryDescription> dependencies, FrameworkName targetFramework)
 {
     Dependencies = dependencies;
 }