Ejemplo n.º 1
0
        public IEnumerable <FrameworkName> GetFrameworksSupportingNetStandard(FrameworkName frameworkName)
        {
            if (frameworkName == null)
            {
                throw new ArgumentNullException(nameof(frameworkName));
            }

            try
            {
                var nuGetFramework = NuGetFramework.ParseFrameworkName(frameworkName.ToString(), DefaultFrameworkNameProvider.Instance);

                if (!StringComparer.OrdinalIgnoreCase.Equals(
                        nuGetFramework.Framework,
                        FrameworkConstants.FrameworkIdentifiers.NetStandard))
                {
                    throw new ArgumentException(string.Format(
                                                    VsResources.InvalidNetStandardFramework,
                                                    frameworkName));
                }

                return(CompatibilityListProvider
                       .Default
                       .GetFrameworksSupporting(nuGetFramework)
                       .Select(framework => new FrameworkName(framework.DotNetFrameworkName))
                       .ToList());
            }
            catch (Exception exception)
            {
                _telemetryProvider.PostFault(exception, typeof(VsFrameworkCompatibility).FullName);
                throw;
            }
        }
Ejemplo n.º 2
0
        public string GetFriendlyFrameworkName(FrameworkName targetFramework)
        {
            // We don't have a friendly name for this anywhere on the machine so hard code it
            if (string.Equals(targetFramework.Identifier, "K", StringComparison.OrdinalIgnoreCase))
            {
                return(".NET Core Framework 4.5");
            }
            else if (string.Equals(targetFramework.Identifier, VersionUtility.AspNetCoreFrameworkIdentifier, StringComparison.OrdinalIgnoreCase))
            {
                return("ASP.NET Core 5.0");
            }
            else if (string.Equals(targetFramework.Identifier, VersionUtility.AspNetFrameworkIdentifier, StringComparison.OrdinalIgnoreCase))
            {
                return("ASP.NET 5.0");
            }

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

            if (information == null)
            {
                return(targetFramework.ToString());
            }

            return(information.Name);
        }
Ejemplo n.º 3
0
        public string GetShortFrameworkName(FrameworkName frameworkName)
        {
            if (frameworkName == null)
            {
                throw new ArgumentNullException(nameof(frameworkName));
            }

            var nuGetFramework = NuGetFramework.ParseFrameworkName(
                frameworkName.ToString(),
                DefaultFrameworkNameProvider.Instance);

            try
            {
                return(nuGetFramework.GetShortFolderName());
            }
            catch (FrameworkException e)
            {
                // Wrap this exception for two reasons:
                //
                // 1) FrameworkException is not a .NET Framework type and therefore is not
                //    recognized by other components in Visual Studio.
                //
                // 2) Changing our NuGet code to throw ArgumentException is not appropriate in
                //    this case because the failure does not occur in a method that has arguments!
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    VsResources.CouldNotGetShortFrameworkName,
                    frameworkName);
                throw new ArgumentException(message, e);
            }
        }
Ejemplo n.º 4
0
        private void PrintDependencyGraph(GraphNode root, FrameworkName frameworkName)
        {
            // Box Drawing Unicode characters:
            // http://www.unicode.org/charts/PDF/U2500.pdf
            const char LIGHT_HORIZONTAL         = '\u2500';
            const char LIGHT_UP_AND_RIGHT       = '\u2514';
            const char LIGHT_VERTICAL_AND_RIGHT = '\u251C';

            var frameworkSuffix = string.Format(" [{0}]", frameworkName.ToString());

            Reports.Verbose.WriteLine(root.Item.Match.Library.ToString() + frameworkSuffix);

            Func <GraphNode, bool> isValidDependency = d =>
                                                       (d != null && d.Library != null && d.Item != null && d.Item.Match != null);
            var dependencies  = root.Dependencies.Where(isValidDependency).ToList();
            var dependencyNum = dependencies.Count;

            for (int i = 0; i < dependencyNum; i++)
            {
                var branchChar = LIGHT_VERTICAL_AND_RIGHT;
                if (i == dependencyNum - 1)
                {
                    branchChar = LIGHT_UP_AND_RIGHT;
                }

                var name = dependencies[i].Item.Match.Library.ToString();
                var dependencyListStr = string.Join(", ", dependencies[i].Dependencies
                                                    .Where(isValidDependency)
                                                    .Select(d => d.Item.Match.Library.ToString()));
                var format = string.IsNullOrEmpty(dependencyListStr) ? "{0}{1} {2}{3}" : "{0}{1} {2} ({3})";
                Reports.Verbose.WriteLine(string.Format(format,
                                                        branchChar, LIGHT_HORIZONTAL, name, dependencyListStr));
            }
            Reports.Verbose.WriteLine();
        }
Ejemplo n.º 5
0
        public void Walk(IGraphNode <LibraryDescription> root)
        {
            _assemblyFilePaths         = new HashSet <string>(StringComparer.Ordinal);
            _dependencyAssemblySources = new Dictionary <string, HashSet <string> >(StringComparer.Ordinal);
            _dependencyPackageSources  = new Dictionary <string, HashSet <string> >(StringComparer.Ordinal);

            var libraries = new HashSet <LibraryDescription>();

            root.DepthFirstPreOrderWalk(visitNode: (node, _) => VisitLibrary(node, _, libraries));

            _reports.Information.WriteLine("\n[Target framework {0} ({1})]\n",
                                           _framework.ToString(), VersionUtility.GetShortFrameworkName(_framework));

            foreach (var assemblyFilePath in _assemblyFilePaths.OrderBy(assemblyName => assemblyName))
            {
                _reports.Information.WriteLine(assemblyFilePath);
                if (_showDetails)
                {
                    var assemblyName = Path.GetFileNameWithoutExtension(assemblyFilePath);

                    HashSet <string> packagesSources;
                    if (_dependencyPackageSources.TryGetValue(assemblyName, out packagesSources) && packagesSources.Any())
                    {
                        _reports.Information.WriteLine("    by package:  {0}", string.Join(", ", packagesSources));
                    }

                    HashSet <string> assemblySources;
                    if (_dependencyAssemblySources.TryGetValue(assemblyName, out assemblySources) && assemblySources.Any())
                    {
                        _reports.Information.WriteLine("    by assembly: {0}", string.Join(", ", assemblySources));
                    }
                }
            }
        }
Ejemplo n.º 6
0
 private static void VerifyConstructor(FrameworkName name, string expectedName, string expectedIdentifier, Version expectedVersion, string expectedProfile)
 {
     Assert.Equal(expectedName, name.FullName);
     Assert.Equal(expectedName, name.ToString());
     Assert.Equal(expectedIdentifier, name.Identifier);
     Assert.Equal(expectedProfile, name.Profile);
     Assert.Equal(expectedVersion, name.Version);
 }
        private static AssemblyInfo GetAssemblyInfo(string assemblyName, string version)
        {
            var name = new FrameworkName(assemblyName, Version.Parse(version));

            return(new AssemblyInfo {
                AssemblyIdentity = name.ToString()
            });
        }
        private static AssemblyInfo GetAssemblyInfo(string assemblyName, string version, bool isExplicitlySpecified)
        {
            var name = new FrameworkName(assemblyName, Version.Parse(version));

            return(new AssemblyInfo {
                AssemblyIdentity = name.ToString(), IsExplicitlySpecified = isExplicitlySpecified
            });
        }
        private FrameworkName GetNearestImpl(FrameworkName targetFramework, IEnumerable <FrameworkName> fallbackTargetFrameworks, IEnumerable <FrameworkName> frameworks)
        {
            if (targetFramework == null)
            {
                throw new ArgumentNullException(nameof(targetFramework));
            }

            if (fallbackTargetFrameworks == null)
            {
                throw new ArgumentNullException(nameof(fallbackTargetFrameworks));
            }

            if (frameworks == null)
            {
                throw new ArgumentNullException(nameof(frameworks));
            }

            IEnumerable <NuGetFramework> ParseAllFrameworks(IEnumerable <FrameworkName> frameworks)
            {
                foreach (FrameworkName frameworkName in frameworks)
                {
                    if (frameworkName == null)
                    {
                        throw new ArgumentException(message: VsResourcesFormat.PropertyCannotBeNull(nameof(FrameworkName)), paramName: nameof(frameworks));
                    }

                    NuGetFramework nugetFramework = NuGetFramework.ParseFrameworkName(frameworkName.ToString(), DefaultFrameworkNameProvider.Instance);
                    yield return(nugetFramework);
                }
            }

            var nuGetTargetFramework          = NuGetFramework.ParseFrameworkName(targetFramework.ToString(), DefaultFrameworkNameProvider.Instance);
            var nuGetFallbackTargetFrameworks = ParseAllFrameworks(fallbackTargetFrameworks).ToList();
            var nuGetFrameworks = ParseAllFrameworks(frameworks).ToList();

            try
            {
                if (nuGetFallbackTargetFrameworks.Any())
                {
                    nuGetTargetFramework = new FallbackFramework(nuGetTargetFramework, nuGetFallbackTargetFrameworks);
                }

                var reducer = new FrameworkReducer();
                var nearest = reducer.GetNearest(nuGetTargetFramework, nuGetFrameworks);

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

                return(new FrameworkName(nearest.DotNetFrameworkName));
            }
            catch (Exception exception)
            {
                _telemetryProvider.PostFault(exception, typeof(VsFrameworkCompatibility).FullName);
                throw;
            }
        }
Ejemplo n.º 10
0
        public void ToStringTest()
        {
            var fn = new FrameworkName(".NETFramework,Version=v2.0.1");

            Assert.AreEqual(".NETFramework,Version=v2.0.1", fn.FullName, "#A1-1");
            Assert.AreEqual(fn.FullName, fn.ToString(), "#A1-2");

            fn = new FrameworkName(".NETFramework,Version=v2.0.1.0");
            Assert.AreEqual(".NETFramework,Version=v2.0.1.0", fn.FullName, "#A2-1");
            Assert.AreEqual(fn.FullName, fn.ToString(), "#A2-2");
        }
Ejemplo n.º 11
0
        private string GetFriendlyFrameworkName(FrameworkReferenceResolver frameworkResolver, FrameworkName targetFramework)
        {
            // We don't have a friendly name for this anywhere on the machine so hard code it
            if (targetFramework.Identifier.Equals("K", StringComparison.OrdinalIgnoreCase))
            {
                // REVIEW: 4.5?
                return(".NET Core Framework 4.5");
            }

            return(frameworkResolver.GetFriendlyFrameworkName(targetFramework) ?? targetFramework.ToString());
        }
        public string GetShortFrameworkName(FrameworkName frameworkName)
        {
#pragma warning disable CS0618 // Type or member is obsolete
            const string eventName = nameof(IVsFrameworkParser) + "." + nameof(GetShortFrameworkName);
#pragma warning restore CS0618 // Type or member is obsolete
            using var _ = NuGetETW.ExtensibilityEventSource.StartStopEvent(eventName,
                                                                           new
            {
                Framework = frameworkName?.FullName
            });

            if (frameworkName == null)
            {
                throw new ArgumentNullException(nameof(frameworkName));
            }

            try
            {
                var nuGetFramework = NuGetFramework.ParseFrameworkName(
                    frameworkName.ToString(),
                    DefaultFrameworkNameProvider.Instance);

                try
                {
                    return(nuGetFramework.GetShortFolderName());
                }
                catch (FrameworkException e)
                {
                    // Wrap this exception for two reasons:
                    //
                    // 1) FrameworkException is not a .NET Framework type and therefore is not
                    //    recognized by other components in Visual Studio.
                    //
                    // 2) Changing our NuGet code to throw ArgumentException is not appropriate in
                    //    this case because the failure does not occur in a method that has arguments!
                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        VsResources.CouldNotGetShortFrameworkName,
                        frameworkName);
                    throw new ArgumentException(message, e);
                }
            }
            catch (ArgumentException)
            {
                throw;
            }
            catch (Exception exception)
            {
                _telemetryProvider.PostFault(exception, typeof(VsFrameworkParser).FullName);
                throw;
            }
        }
Ejemplo n.º 13
0
 private static string SynthesizeFrameworkFriendlyName(FrameworkName targetFramework)
 {
     // Names are not present in the RedistList.xml file for older frameworks or on Mono
     // We do some custom version string rendering to match how net40 is rendered (.NET Framework 4)
     if (targetFramework.Identifier.Equals(VersionUtility.NetFrameworkIdentifier))
     {
         string versionString = targetFramework.Version.Minor == 0 ?
                                targetFramework.Version.Major.ToString() :
                                targetFramework.Version.ToString();
         return(".NET Framework " + versionString);
     }
     return(targetFramework.ToString());
 }
Ejemplo n.º 14
0
 public string GetTemplatePath(FrameworkName frameworkName)
 {
     if (!this.SupportsFramework(frameworkName))
     {
         CultureInfo currentCulture = CultureInfo.CurrentCulture;
         string      unknownFrameworkEncountered = ExceptionStringTable.UnknownFrameworkEncountered;
         object[]    str = new object[] { frameworkName.ToString() };
         throw new ArgumentException(string.Format(currentCulture, unknownFrameworkEncountered, str));
     }
     if (string.IsNullOrEmpty(this.templatePath))
     {
         this.templatePath = this.GetRelativePath(frameworkName, this.TemplateRelativePathFormatString);
     }
     return(this.templatePath);
 }
Ejemplo n.º 15
0
        private void Render(IGraphNode <Library> root)
        {
            var renderer = new LibraryDependencyFlatRenderer(_options.HideDependents, _options.ResultsFilter, _options.Project.Dependencies.Select(dep => dep.LibraryRange.Name));
            var content  = renderer.GetRenderContent(root);

            if (content.Any())
            {
                _options.Reports.Information.WriteLine("\n[Target framework {0} ({1})]\n",
                                                       _framework.ToString(), VersionUtility.GetShortFrameworkName(_framework));

                foreach (var line in content)
                {
                    _options.Reports.Information.WriteLine(line);
                }
            }
        }
Ejemplo n.º 16
0
 public string GetFontTargetsFile(FrameworkName frameworkName)
 {
     if (!this.SupportsFramework(frameworkName))
     {
         CultureInfo currentCulture = CultureInfo.CurrentCulture;
         string      unknownFrameworkEncountered = ExceptionStringTable.UnknownFrameworkEncountered;
         object[]    str = new object[] { frameworkName.ToString() };
         throw new ArgumentException(string.Format(currentCulture, unknownFrameworkEncountered, str));
     }
     if (string.IsNullOrEmpty(this.fontTargetsFile))
     {
         CultureInfo invariantCulture                  = CultureInfo.InvariantCulture;
         string      fontTargetsFileFormatString       = this.FontTargetsFileFormatString;
         object[]    customIdentifierFromFrameworkName = new object[] { this.GetCustomIdentifierFromFrameworkName(frameworkName), frameworkName.Identifier, this.GetCustomVersionFromFrameworkName(frameworkName), frameworkName.Profile };
         this.fontTargetsFile = string.Format(invariantCulture, fontTargetsFileFormatString, customIdentifierFromFrameworkName);
     }
     return(this.fontTargetsFile);
 }
        public FrameworkName GetNearest(FrameworkName targetFramework, IEnumerable <FrameworkName> fallbackTargetFrameworks, IEnumerable <FrameworkName> frameworks)
        {
            if (targetFramework == null)
            {
                throw new ArgumentNullException(nameof(targetFramework));
            }

            if (fallbackTargetFrameworks == null)
            {
                throw new ArgumentNullException(nameof(fallbackTargetFrameworks));
            }

            if (frameworks == null)
            {
                throw new ArgumentNullException(nameof(frameworks));
            }

            var nuGetTargetFramework = NuGetFramework.ParseFrameworkName(targetFramework.ToString(), DefaultFrameworkNameProvider.Instance);

            var nuGetFallbackTargetFrameworks = fallbackTargetFrameworks
                                                .Select(framework => NuGetFramework.ParseFrameworkName(framework.ToString(), DefaultFrameworkNameProvider.Instance))
                                                .ToList();

            if (nuGetFallbackTargetFrameworks.Any())
            {
                nuGetTargetFramework = new FallbackFramework(nuGetTargetFramework, nuGetFallbackTargetFrameworks);
            }

            var nuGetFrameworks = frameworks
                                  .Select(framework => NuGetFramework.ParseFrameworkName(framework.ToString(), DefaultFrameworkNameProvider.Instance));

            var reducer = new FrameworkReducer();
            var nearest = reducer.GetNearest(nuGetTargetFramework, nuGetFrameworks);

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

            return(new FrameworkName(nearest.DotNetFrameworkName));
        }
Ejemplo n.º 18
0
 public string GetHelpFileName(FrameworkName frameworkName)
 {
     if (!this.SupportsFramework(frameworkName))
     {
         CultureInfo currentCulture = CultureInfo.CurrentCulture;
         string      unknownFrameworkEncountered = ExceptionStringTable.UnknownFrameworkEncountered;
         object[]    str = new object[] { frameworkName.ToString() };
         throw new ArgumentException(string.Format(currentCulture, unknownFrameworkEncountered, str));
     }
     if (string.IsNullOrEmpty(this.helpFileName))
     {
         Version     customVersionFromFrameworkName = this.GetCustomVersionFromFrameworkName(frameworkName);
         CultureInfo invariantCulture         = CultureInfo.InvariantCulture;
         string      helpFileNameFormatString = this.HelpFileNameFormatString;
         object[]    identifier = new object[] { frameworkName.Identifier, null, null, null };
         int         major      = customVersionFromFrameworkName.Major;
         identifier[1] = major.ToString(CultureInfo.InvariantCulture);
         int minor = customVersionFromFrameworkName.Minor;
         identifier[2]     = minor.ToString(CultureInfo.InvariantCulture);
         identifier[3]     = frameworkName.Profile;
         this.helpFileName = string.Format(invariantCulture, helpFileNameFormatString, identifier);
     }
     return(this.helpFileName);
 }
        // ----------------------------------------------------------------------------------------------------------------------------------------
        private static Document CreateLuceneDocument(JObject package, string packageUrl)
        {
            Document doc = new Document();

            if (((IDictionary <string, JToken>)package).ContainsKey("supportedFrameworks"))
            {
                foreach (JToken fwk in package["supportedFrameworks"])
                {
                    string framework = (string)fwk;

                    FrameworkName frameworkName = VersionUtility.ParseFrameworkName(framework);

                    lock (_frameworkNames)
                    {
                        if (!_frameworkNames.ContainsKey(framework))
                        {
                            _frameworkNames.Add(framework, frameworkName.FullName);
                            Console.WriteLine("New framework string: {0}, {1}", framework, frameworkName.FullName);
                            using (var writer = File.AppendText("frameworks.txt"))
                            {
                                writer.WriteLine("{0}: {1}", framework, frameworkName.FullName);
                            }
                        }
                    }
                    Add(doc, "TargetFramework", framework == "any" ? "any" : frameworkName.ToString(), Field.Store.YES /* NO */, Field.Index.NO, Field.TermVector.NO);
                }
            }

            //  Query Fields

            float titleBoost = 3.0f;
            float idBoost    = 2.0f;

            if (package["tags"] == null)
            {
                titleBoost += 0.5f;
                idBoost    += 0.5f;
            }

            string title = (string)(package["title"] ?? package["id"]);

            Add(doc, "Id", (string)package["id"], Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS, idBoost);
            Add(doc, "IdAutocomplete", (string)package["id"], Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO);
            Add(doc, "TokenizedId", (string)package["id"], Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS, idBoost);
            Add(doc, "ShingledId", (string)package["id"], Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS, idBoost);
            Add(doc, "Version", (string)package["version"], Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS, idBoost);
            Add(doc, "Title", title, Field.Store.YES /* NO */, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS, titleBoost);
            Add(doc, "Tags", string.Join(", ", (package["tags"] ?? new JArray()).Select(s => (string)s)), Field.Store.YES /* NO */, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS, 1.5f);
            Add(doc, "Description", (string)package["description"], Field.Store.YES /* NO */, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS);
            Add(doc, "Authors", string.Join(", ", package["authors"].Select(s => (string)s)), Field.Store.YES /* NO */, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS);

            doc.Add(new NumericField("PublishedDate", Field.Store.YES, true).SetIntValue(int.Parse(package["published"].ToObject <DateTime>().ToString("yyyyMMdd"))));

            DateTime lastEdited = (DateTime)(package["lastEdited"] ?? package["published"]);

            doc.Add(new NumericField("EditedDate", Field.Store.YES, true).SetIntValue(int.Parse(lastEdited.ToString("yyyyMMdd"))));

            string displayName = String.IsNullOrEmpty((string)package["title"]) ? (string)package["id"] : (string)package["title"];

            displayName = displayName.ToLower(CultureInfo.CurrentCulture);
            Add(doc, "DisplayName", displayName, Field.Store.NO, Field.Index.NOT_ANALYZED, Field.TermVector.NO);

            Add(doc, "Url", packageUrl.ToString(), Field.Store.YES, Field.Index.NO, Field.TermVector.NO);

            doc.Boost = DetermineLanguageBoost((string)package["id"], (string)package["language"]);

            return(doc);
        }
 private IList<string> GetPaths(string rootPath, FrameworkName frameworkmoniker)
 {
     IList<string> pathToReferenceAssemblies = null;
     if (string.IsNullOrEmpty(rootPath))
     {
         pathToReferenceAssemblies = ToolLocationHelper.GetPathToReferenceAssemblies(frameworkmoniker);
     }
     else
     {
         pathToReferenceAssemblies = ToolLocationHelper.GetPathToReferenceAssemblies(rootPath, frameworkmoniker);
     }
     if (pathToReferenceAssemblies.Count == 0)
     {
         base.Log.LogWarningWithCodeFromResources("GetReferenceAssemblyPaths.NoReferenceAssemblyDirectoryFound", new object[] { frameworkmoniker.ToString() });
     }
     return pathToReferenceAssemblies;
 }
		public void TargetFramework_TargetFrameworkVersion35ClientProfileDefinedInProject_ReturnsClientProfileDotNetFramework35 ()
		{
			CreateTestProject ();
			project.TargetFrameworkMoniker = new TargetFrameworkMoniker (".NETFramework", "v3.5", "Client");
			CreateProjectSystem (project);

			FrameworkName expectedName = new FrameworkName (".NETFramework, Profile=Client, Version=v3.5");

			Assert.AreEqual (expectedName.ToString (), projectSystem.TargetFramework.ToString ());
		}
		public void TargetFramework_TargetFrameworkVersionIsSilverlight20DefinedInProject_ReturnsSilverlight ()
		{
			CreateTestProject ();
			project.TargetFrameworkMoniker = new TargetFrameworkMoniker ("Silverlight", "v2.0");
			CreateProjectSystem (project);

			FrameworkName expectedName = new FrameworkName ("Silverlight, Version=v2.0");

			Assert.AreEqual (expectedName.ToString (), projectSystem.TargetFramework.ToString ());
		}
Ejemplo n.º 23
0
        public string GetMissingDependenciesWarning(FrameworkName targetFramework)
        {
            var sb = new StringBuilder();

            // TODO: Localize messages

            sb.AppendFormat("Failed to resolve the following dependencies for target framework '{0}':", targetFramework.ToString());
            sb.AppendLine();

            foreach (var d in Libraries.Where(d => !d.Resolved).OrderBy(d => d.Identity.Name))
            {
                sb.Append("   " + d.Identity);
                if (!d.Compatible)
                {
                    sb.Append(" (incompatible)");
                }
                sb.AppendLine();
            }

            return(sb.ToString());
        }
		public void TargetFramework_TargetFrameworkVersion40DefinedInProject_ReturnsFullDotNetFramework40 ()
		{
			CreateTestProject ();
			project.TargetFrameworkMoniker = new TargetFrameworkMoniker ("v4.0");
			CreateProjectSystem (project);

			FrameworkName expectedName = new FrameworkName (".NETFramework, Version=v4.0");

			Assert.AreEqual (expectedName.ToString (), projectSystem.TargetFramework.ToString ());
		}
Ejemplo n.º 25
0
 private static string SynthesizeFrameworkFriendlyName(FrameworkName targetFramework)
 {
     // Names are not present in the RedistList.xml file for older frameworks or on Mono
     // We do some custom version string rendering to match how net40 is rendered (.NET Framework 4)
     if (targetFramework.Identifier.Equals(VersionUtility.NetFrameworkIdentifier))
     {
         string versionString = targetFramework.Version.Minor == 0 ?
             targetFramework.Version.Major.ToString() :
             targetFramework.Version.ToString();
         return ".NET Framework " + versionString;
     }
     return targetFramework.ToString();
 }
Ejemplo n.º 26
0
 private static void VerifyConstructor(FrameworkName name, string expectedName, string expectedIdentifier, Version expectedVersion, string expectedProfile)
 {
     Assert.Equal(expectedName, name.FullName);
     Assert.Equal(expectedName, name.ToString());
     Assert.Equal(expectedIdentifier, name.Identifier);
     Assert.Equal(expectedProfile, name.Profile);
     Assert.Equal(expectedVersion, name.Version);
 }
Ejemplo n.º 27
0
        public string GetFriendlyFrameworkName(FrameworkName targetFramework)
        {
            // We don't have a friendly name for this anywhere on the machine so hard code it
            if (string.Equals(targetFramework.Identifier, "K", StringComparison.OrdinalIgnoreCase))
            {
                return ".NET Core Framework 4.5";
            }
            else if (string.Equals(targetFramework.Identifier, VersionUtility.AspNetCoreFrameworkIdentifier, StringComparison.OrdinalIgnoreCase))
            {
                return "ASP.NET Core 5.0";
            }
            else if (string.Equals(targetFramework.Identifier, VersionUtility.AspNetFrameworkIdentifier, StringComparison.OrdinalIgnoreCase))
            {
                return "ASP.NET 5.0";
            }
            else if (string.Equals(targetFramework.Identifier, VersionUtility.DnxCoreFrameworkIdentifier, StringComparison.OrdinalIgnoreCase))
            {
                return "DNX Core 5.0";
            }
            else if (string.Equals(targetFramework.Identifier, VersionUtility.DnxFrameworkIdentifier, StringComparison.OrdinalIgnoreCase))
            {
                return "DNX " + targetFramework.Version.ToString();
            }
            else if (string.Equals(targetFramework.Identifier, VersionUtility.NetPlatformFrameworkIdentifier, StringComparison.OrdinalIgnoreCase))
            {
                return ".NET Platform";
            }

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

            if (information == null)
            {
                return targetFramework.ToString();
            }

            return information.Name;
        }
Ejemplo n.º 28
0
        private static IEnumerable <KeyValuePair <string, string> > UpdateFrameworkNames(IEnumerable <KeyValuePair <string, string> > properties)
        {
            foreach (var prop in properties)
            {
                if (StringComparer.Ordinal.Equals("targetframework", prop.Key))
                {
                    NuGetFramework nuFramework = NuGetFramework.Parse(prop.Value);

                    FrameworkName frameworkName = new FrameworkName(nuFramework.FullFrameworkName);

                    KeyValuePair <string, string> fixedProp = new KeyValuePair <string, string>(prop.Key, frameworkName.ToString());

                    yield return(fixedProp);
                }
                else
                {
                    yield return(prop);
                }
            }

            yield break;
        }
Ejemplo n.º 29
0
        private IList <string> GetPaths(string rootPath, FrameworkName frameworkmoniker)
        {
            IList <string> pathToReferenceAssemblies = null;

            if (string.IsNullOrEmpty(rootPath))
            {
                pathToReferenceAssemblies = ToolLocationHelper.GetPathToReferenceAssemblies(frameworkmoniker);
            }
            else
            {
                pathToReferenceAssemblies = ToolLocationHelper.GetPathToReferenceAssemblies(rootPath, frameworkmoniker);
            }
            if (pathToReferenceAssemblies.Count == 0)
            {
                base.Log.LogWarningWithCodeFromResources("GetReferenceAssemblyPaths.NoReferenceAssemblyDirectoryFound", new object[] { frameworkmoniker.ToString() });
            }
            return(pathToReferenceAssemblies);
        }
        private static IEnumerable<KeyValuePair<string, string>> UpdateFrameworkNames(IEnumerable<KeyValuePair<string, string>> properties)
        {
            foreach (var prop in properties)
            {
                if (StringComparer.Ordinal.Equals("targetframework", prop.Key))
                {
                    NuGetFramework nuFramework = NuGetFramework.Parse(prop.Value);

                    FrameworkName frameworkName = new FrameworkName(nuFramework.FullFrameworkName);

                    KeyValuePair<string, string> fixedProp = new KeyValuePair<string,string>(prop.Key, frameworkName.ToString());

                    yield return fixedProp;
                }
                else
                {
                    yield return prop;
                }
            }

            yield break;
        }
Ejemplo n.º 31
0
        public string GetMissingDependenciesWarning(FrameworkName targetFramework)
        {
            var sb = new StringBuilder();

            // TODO: Localize messages

            sb.AppendFormat("Failed to resolve the following dependencies for target framework '{0}':", targetFramework.ToString());
            sb.AppendLine();

            foreach (var d in Libraries.Where(d => !d.Resolved).OrderBy(d => d.Identity.Name))
            {
                sb.AppendLine("   " + d.Identity.ToString());
            }

            sb.AppendLine();
            sb.AppendLine("Searched Locations:");

            foreach (var path in GetAttemptedPaths(targetFramework))
            {
                sb.AppendLine("  " + path);
            }

            sb.AppendLine();
            sb.AppendLine("Try running 'kpm restore'.");

            return(sb.ToString());
        }
Ejemplo n.º 32
0
        private void PrintDependencyGraph(GraphNode root, FrameworkName frameworkName)
        {
            // Box Drawing Unicode characters:
            // http://www.unicode.org/charts/PDF/U2500.pdf
            const char LIGHT_HORIZONTAL = '\u2500';
            const char LIGHT_UP_AND_RIGHT = '\u2514';
            const char LIGHT_VERTICAL_AND_RIGHT = '\u251C';

            var frameworkSuffix = string.Format(" [{0}]", frameworkName.ToString());
            Reports.Verbose.WriteLine(root.Item.Match.Library.ToString() + frameworkSuffix);

            Func<GraphNode, bool> isValidDependency = d => 
                (d != null && d.Library != null && d.Item != null && d.Item.Match != null);
            var dependencies = root.Dependencies.Where(isValidDependency).ToList();
            var dependencyNum = dependencies.Count;
            for (int i = 0; i < dependencyNum; i++)
            {
                var branchChar = LIGHT_VERTICAL_AND_RIGHT;
                if (i == dependencyNum - 1)
                {
                    branchChar = LIGHT_UP_AND_RIGHT;
                }

                var name = dependencies[i].Item.Match.Library.ToString();
                var dependencyListStr = string.Join(", ", dependencies[i].Dependencies
                    .Where(isValidDependency)
                    .Select(d => d.Item.Match.Library.ToString()));
                var format = string.IsNullOrEmpty(dependencyListStr) ? "{0}{1} {2}{3}" : "{0}{1} {2} ({3})";
                Reports.Verbose.WriteLine(string.Format(format,
                    branchChar, LIGHT_HORIZONTAL, name, dependencyListStr));
            }
            Reports.Verbose.WriteLine();
        }
Ejemplo n.º 33
0
        public string GetMissingDependenciesWarning(FrameworkName targetFramework)
        {
            var sb = new StringBuilder();

            // TODO: Localize messages

            sb.AppendFormat("Failed to resolve the following dependencies for target framework '{0}':", targetFramework.ToString());
            sb.AppendLine();

            foreach (var d in GetLibraryDescriptions().Where(d => !d.Resolved).OrderBy(d => d.Identity.Name))
            {
                sb.Append("   " + d.Identity);
                if (!d.Compatible)
                {
                    sb.Append(" (incompatible)");
                }
                sb.AppendLine();
            }

            return sb.ToString();
        }
        protected virtual void ExtractPackageFilesToProject(IPackage package)
        {
            // BUG 491: Installing a package with incompatible binaries still does a partial install.
            // Resolve assembly references and content files first so that if this fails we never do anything to the project
            List <IPackageAssemblyReference>  assemblyReferences  = Project.GetCompatibleItemsCore(package.AssemblyReferences).ToList();
            List <FrameworkAssemblyReference> frameworkReferences = Project.GetCompatibleItemsCore(package.FrameworkAssemblies).ToList();
            List <IPackageFile> contentFiles = Project.GetCompatibleItemsCore(package.GetContentFiles()).ToList();
            List <IPackageFile> buildFiles   = Project.GetCompatibleItemsCore(package.GetBuildFiles()).ToList();

            // If the package doesn't have any compatible assembly references or content files,
            // throw, unless it's a meta package.
            if (assemblyReferences.Count == 0 && frameworkReferences.Count == 0 && contentFiles.Count == 0 && buildFiles.Count == 0 &&
                (package.FrameworkAssemblies.Any() || package.AssemblyReferences.Any() || package.GetContentFiles().Any() || package.GetBuildFiles().Any()))
            {
                // for portable framework, we want to show the friendly short form (e.g. portable-win8+net45+wp8) instead of ".NETPortable, Profile=Profile104".
                FrameworkName targetFramework       = Project.TargetFramework;
                string        targetFrameworkString = targetFramework.IsPortableFramework()
                                                    ? VersionUtility.GetShortFrameworkName(targetFramework)
                                                    : targetFramework != null?targetFramework.ToString() : null;

                throw new InvalidOperationException(
                          String.Format(CultureInfo.CurrentCulture,
                                        NuGetResources.UnableToFindCompatibleItems, package.GetFullName(), targetFrameworkString));
            }

            // IMPORTANT: this filtering has to be done AFTER the 'if' statement above,
            // so that we don't throw the exception in case the <References> filters out all assemblies.
            FilterAssemblyReferences(assemblyReferences, package.PackageAssemblyReferences);

            try
            {
                // Log target framework info for debugging
                LogTargetFrameworkInfo(package, assemblyReferences, contentFiles, buildFiles);

                // Add content files
                Project.AddFiles(contentFiles, _fileTransformers);

                // Add the references to the reference path
                foreach (IPackageAssemblyReference assemblyReference in assemblyReferences)
                {
                    if (assemblyReference.IsEmptyFolder())
                    {
                        continue;
                    }

                    // Get the physical path of the assembly reference
                    string referencePath         = Path.Combine(PathResolver.GetInstallPath(package), assemblyReference.Path);
                    string relativeReferencePath = PathUtility.GetRelativePath(Project.Root, referencePath);

                    if (Project.ReferenceExists(assemblyReference.Name))
                    {
                        Project.RemoveReference(assemblyReference.Name);
                    }

                    Project.AddReference(relativeReferencePath);
                }

                // Add GAC/Framework references
                foreach (FrameworkAssemblyReference frameworkReference in frameworkReferences)
                {
                    if (!Project.ReferenceExists(frameworkReference.AssemblyName))
                    {
                        Project.AddFrameworkReference(frameworkReference.AssemblyName);
                    }
                }

                foreach (var importFile in buildFiles)
                {
                    string fullImportFilePath = Path.Combine(PathResolver.GetInstallPath(package), importFile.Path);
                    Project.AddImport(
                        fullImportFilePath,
                        importFile.Path.EndsWith(".props", StringComparison.OrdinalIgnoreCase) ? ProjectImportLocation.Top : ProjectImportLocation.Bottom);
                }
            }
            finally
            {
                if (_packageReferenceRepository != null)
                {
                    // save the used project's framework if the repository supports it.
                    _packageReferenceRepository.AddPackage(package.Id, package.Version, package.DevelopmentDependency, Project.TargetFramework);
                }
                else
                {
                    // Add package to local repository in the finally so that the user can uninstall it
                    // if any exception occurs. This is easier than rolling back since the user can just
                    // manually uninstall things that may have failed.
                    // If this fails then the user is out of luck.
                    LocalRepository.AddPackage(package);
                }
            }
        }
Ejemplo n.º 35
0
 internal static string GenerateReferenceAssemblyPath(string targetFrameworkRootPath, FrameworkName frameworkName)
 {
     ErrorUtilities.VerifyThrowArgumentNull(targetFrameworkRootPath, "targetFrameworkRootPath");
     ErrorUtilities.VerifyThrowArgumentNull(frameworkName, "frameworkName");
     try
     {
         string str = targetFrameworkRootPath;
         str = Path.Combine(Path.Combine(str, frameworkName.Identifier), "v" + frameworkName.Version.ToString());
         if (!string.IsNullOrEmpty(frameworkName.Profile))
         {
             str = Path.Combine(Path.Combine(str, "Profile"), frameworkName.Profile);
         }
         return(Path.GetFullPath(str));
     }
     catch (Exception exception)
     {
         if (ExceptionHandling.NotExpectedException(exception))
         {
             throw;
         }
         ErrorUtilities.ThrowInvalidOperation("ToolsLocationHelper.CouldNotGenerateReferenceAssemblyDirectory", new object[] { targetFrameworkRootPath, frameworkName.ToString(), exception.Message });
         return(null);
     }
 }
Ejemplo n.º 36
0
        public string GetMissingDependenciesWarning(FrameworkName targetFramework)
        {
            var sb = new StringBuilder();

            // TODO: Localize messages

            sb.AppendFormat("Failed to resolve the following dependencies for target framework '{0}':", targetFramework.ToString());
            sb.AppendLine();

            foreach (var d in Libraries.Where(d => !d.Resolved).OrderBy(d => d.Identity.Name))
            {
                sb.AppendLine("   " + d.Identity.ToString());
            }

            sb.AppendLine();
            sb.AppendLine("Searched Locations:");

            foreach (var path in GetAttemptedPaths(targetFramework))
            {
                sb.AppendLine("  " + path);
            }

            sb.AppendLine();
            sb.AppendLine("Try running 'dnu restore'.");

            return sb.ToString();
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Take the parts of the Target framework moniker and formulate the reference assembly path based on the the following pattern:
        /// For a framework and version:
        ///     $(TargetFrameworkRootPath)\$(TargetFrameworkIdentifier)\$(TargetFrameworkVersion)
        /// For a subtype:
        ///     $(TargetFrameworkRootPath)\$(TargetFrameworkIdentifier)\$(TargetFrameworkVersion)\SubType\$(TargetFrameworkSubType)
        /// e.g.NET Framework v4.0 would locate its reference assemblies in:
        ///     \Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0
        /// e.g.Silverlight v2.0 would locate its reference assemblies in:
        ///     \Program Files\Reference Assemblies\Microsoft\Framework\Silverlight\v2.0
        /// e.g.NET Compact Framework v3.5, subtype PocketPC would locate its reference assemblies in:
        ///     \Program Files\Reference Assemblies\Microsoft\Framework\.NETCompactFramework\v3.5\SubType\PocketPC
        /// </summary>
        /// <returns>The path to the reference assembly location</returns>
        internal static string GenerateReferenceAssemblyPath(string targetFrameworkRootPath, FrameworkName frameworkName)
        {
            ErrorUtilities.VerifyThrowArgumentNull(targetFrameworkRootPath, "targetFrameworkRootPath");
            ErrorUtilities.VerifyThrowArgumentNull(frameworkName, "frameworkName");

            try
            {
                string path = targetFrameworkRootPath;
                path = Path.Combine(path, frameworkName.Identifier);
                path = Path.Combine(path, "v" + frameworkName.Version.ToString());
                if (!String.IsNullOrEmpty(frameworkName.Profile))
                {
                    path = Path.Combine(path, "Profile");
                    path = Path.Combine(path, frameworkName.Profile);
                }

                path = Path.GetFullPath(path);
                return path;
            }
            catch (Exception e) when (ExceptionHandling.IsIoRelatedException(e))
            {
                ErrorUtilities.ThrowInvalidOperation("FrameworkLocationHelper.CouldNotGenerateReferenceAssemblyDirectory", targetFrameworkRootPath, frameworkName.ToString(), e.Message);
                // The compiler does not see the massage above an as exception;
                return null;
            }
        }
Ejemplo n.º 38
0
 private static JToken WriteFrameworkName(FrameworkName item)
 {
     return(item != null ? new JValue(item.ToString()) : JValue.CreateNull());
 }
Ejemplo n.º 39
0
        protected virtual void ExtractPackageFilesToProject(IPackage package)
        {
            List <IPackageAssemblyReference>  assemblyReferences = this.Project.GetCompatibleItemsCore <IPackageAssemblyReference>(package.AssemblyReferences).ToList <IPackageAssemblyReference>();
            List <FrameworkAssemblyReference> list2 = this.Project.GetCompatibleItemsCore <FrameworkAssemblyReference>(package.FrameworkAssemblies).ToList <FrameworkAssemblyReference>();
            List <IPackageFile> contentFiles        = this.Project.GetCompatibleItemsCore <IPackageFile>(package.GetContentFiles()).ToList <IPackageFile>();
            List <IPackageFile> buildFiles          = this.Project.GetCompatibleItemsCore <IPackageFile>(package.GetBuildFiles()).ToList <IPackageFile>();

            if ((assemblyReferences.Count == 0) && ((list2.Count == 0) && ((contentFiles.Count == 0) && ((buildFiles.Count == 0) && (package.FrameworkAssemblies.Any <FrameworkAssemblyReference>() || (package.AssemblyReferences.Any <IPackageAssemblyReference>() || (package.GetContentFiles().Any <IPackageFile>() || package.GetBuildFiles().Any <IPackageFile>())))))))
            {
                FrameworkName targetFramework = this.Project.TargetFramework;
                string        str             = targetFramework.IsPortableFramework() ? VersionUtility.GetShortFrameworkName(targetFramework) : targetFramework?.ToString();
                object[]      args            = new object[] { package.GetFullName(), str };
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, NuGetResources.UnableToFindCompatibleItems, args));
            }
            this.FilterAssemblyReferences(assemblyReferences, package.PackageAssemblyReferences);
            try
            {
                this.LogTargetFrameworkInfo(package, assemblyReferences, contentFiles, buildFiles);
                this.Project.AddFiles(contentFiles, this._fileTransformers);
                foreach (IPackageAssemblyReference reference in assemblyReferences)
                {
                    if (!reference.IsEmptyFolder())
                    {
                        string str2         = Path.Combine(this.PathResolver.GetInstallPath(package), reference.Path);
                        string relativePath = PathUtility.GetRelativePath(this.Project.Root, str2);
                        if (this.Project.ReferenceExists(reference.Name))
                        {
                            this.Project.RemoveReference(reference.Name);
                        }
                        this.Project.AddReference(relativePath);
                    }
                }
                foreach (FrameworkAssemblyReference reference2 in list2)
                {
                    if (!this.Project.ReferenceExists(reference2.AssemblyName))
                    {
                        this.Project.AddFrameworkReference(reference2.AssemblyName);
                    }
                }
                foreach (IPackageFile file in buildFiles)
                {
                    string targetFullPath = Path.Combine(this.PathResolver.GetInstallPath(package), file.Path);
                    this.Project.AddImport(targetFullPath, file.Path.EndsWith(".props", StringComparison.OrdinalIgnoreCase) ? ProjectImportLocation.Top : ProjectImportLocation.Bottom);
                }
            }
            finally
            {
                if (this._packageReferenceRepository != null)
                {
                    this._packageReferenceRepository.AddPackage(package.Id, package.Version, package.DevelopmentDependency, this.Project.TargetFramework);
                }
                else
                {
                    this.LocalRepository.AddPackage(package);
                }
            }
        }