Beispiel #1
0
        bool ValidateApiLevels()
        {
            // Priority:
            //    $(UseLatestAndroidPlatformSdk) > $(AndroidApiLevel) > $(TargetFrameworkVersion)
            //
            // If $(TargetFrameworkVersion) isn't set, and $(AndroidApiLevel) isn't
            // set, act as if $(UseLatestAndroidPlatformSdk) is True
            //
            // If $(UseLatestAndroidPlatformSdk) is true, we do as it says: use the
            // latest installed version.
            //
            // Otherwise, if $(AndroidApiLevel) is set, use it and set $(TargetFrameworkVersion).
            //    Rationale: monodroid/samples/xbuild.make uses $(AndroidApiLevel)
            //    to build for a specific API level.
            // Otherwise, if $(TargetFrameworkVersion) is set, use it and set $(AndroidApiLevel).

            UseLatestAndroidPlatformSdk = UseLatestAndroidPlatformSdk ||
                                          (string.IsNullOrWhiteSpace(AndroidApiLevel) && string.IsNullOrWhiteSpace(TargetFrameworkVersion));

            if (UseLatestAndroidPlatformSdk)
            {
                AndroidApiLevel   = GetMaxInstalledApiLevel().ToString();
                SupportedApiLevel = GetMaxSupportedApiLevel(AndroidApiLevel);
                int maxInstalled, maxSupported = 0;
                if (int.TryParse(AndroidApiLevel, out maxInstalled) && int.TryParse(SupportedApiLevel, out maxSupported) && maxInstalled > maxSupported)
                {
                    Log.LogDebugMessage($"API Level {AndroidApiLevel} is greater than the maximum supported API level of {SupportedApiLevel}. " +
                                        "Support for this API will be added in a future release.");
                    AndroidApiLevel = SupportedApiLevel;
                }
                TargetFrameworkVersion = GetTargetFrameworkVersionFromApiLevel();
                return(TargetFrameworkVersion != null);
            }

            if (!string.IsNullOrWhiteSpace(AndroidApiLevel))
            {
                AndroidApiLevel        = AndroidApiLevel.Trim();
                SupportedApiLevel      = GetMaxSupportedApiLevel(AndroidApiLevel);
                TargetFrameworkVersion = GetTargetFrameworkVersionFromApiLevel();
                return(TargetFrameworkVersion != null);
            }

            if (!string.IsNullOrWhiteSpace(TargetFrameworkVersion))
            {
                TargetFrameworkVersion = TargetFrameworkVersion.Trim();
                string apiLevel = MonoDroidSdk.GetApiLevelForFrameworkVersion(TargetFrameworkVersion);
                if (apiLevel == null)
                {
                    Log.LogCodedError("XA0000",
                                      "Could not determine API level for $(TargetFrameworkVersion) of '{0}'.",
                                      TargetFrameworkVersion);
                    return(false);
                }
                AndroidApiLevel   = apiLevel;
                SupportedApiLevel = apiLevel;
                return(true);
            }
            Log.LogCodedError("XA0000", "Could not determine $(AndroidApiLevel) or $(TargetFrameworkVersion); SHOULD NOT BE REACHED.");
            return(false);
        }
        public void target_framework_greater_than_with_null_returns_true()
        {
            TargetFrameworkVersion higherFramework = new TargetFrameworkVersion("v4.5.1");
            TargetFrameworkVersion lowerFramework = null;

            (higherFramework > lowerFramework).ShouldBeTrue();
        }
        public void target_framework_less_than_returns_false()
        {
            var higherFramework = new TargetFrameworkVersion("v4.5.1");
            var lowerFramework = new TargetFrameworkVersion("v2.0");

            (higherFramework < lowerFramework).ShouldBeFalse();
        }
        public void target_framework_greater_than_when_equal_returns_false()
        {
            var higherFramework = new TargetFrameworkVersion("v2.0");
            var lowerFramework = new TargetFrameworkVersion("v2.0");

            (higherFramework > lowerFramework).ShouldBeFalse();
        }
        public void target_framework_greater_than_with_null_returns_false()
        {
            TargetFrameworkVersion higherFramework = null;
            TargetFrameworkVersion lowerFramework = new TargetFrameworkVersion("v2.0");

            (higherFramework > lowerFramework).ShouldBeFalse();
        }
Beispiel #6
0
        public void target_framework_greater_than_with_null_returns_false()
        {
            TargetFrameworkVersion higherFramework = null;
            TargetFrameworkVersion lowerFramework  = new TargetFrameworkVersion("v2.0");

            (higherFramework > lowerFramework).ShouldBeFalse();
        }
        public void target_framework_greater_than_returns_true()
        {
            var higherFramework = new TargetFrameworkVersion("v4.5.1");
            var lowerFramework = new TargetFrameworkVersion("v2.0");

            (higherFramework > lowerFramework).ShouldBeTrue();
        }
Beispiel #8
0
        public void target_framework_less_than_returns_true()
        {
            var higherFramework = new TargetFrameworkVersion("v4.5.1");
            var lowerFramework  = new TargetFrameworkVersion("v2.0");

            (lowerFramework < higherFramework).ShouldBeTrue();
        }
Beispiel #9
0
        public void target_framework_greater_than_with_null_returns_true()
        {
            TargetFrameworkVersion higherFramework = new TargetFrameworkVersion("v4.5.1");
            TargetFrameworkVersion lowerFramework  = null;

            (higherFramework > lowerFramework).ShouldBeTrue();
        }
        public void can_compare_two_instances_of_target_version_using_icomparable()
        {
            var higherFramework = new TargetFrameworkVersion("v4.5.1");
            var lowerFramework = new TargetFrameworkVersion("v2.0");

            higherFramework.ShouldBeGreaterThan(lowerFramework);
        }
Beispiel #11
0
        public void target_framework_less_than_with_null_returns_true()
        {
            TargetFrameworkVersion higherFramework = null;
            TargetFrameworkVersion lowerFramework  = new TargetFrameworkVersion("v2.0");

            (higherFramework < lowerFramework).ShouldBeTrue();
        }
Beispiel #12
0
        public void target_framework_less_than_with_null_returns_false()
        {
            TargetFrameworkVersion higherFramework = new TargetFrameworkVersion("v4.5.1");
            TargetFrameworkVersion lowerFramework  = null;

            (higherFramework < lowerFramework).ShouldBeFalse();
        }
Beispiel #13
0
        public void can_compare_two_instances_of_target_version_using_icomparable()
        {
            var higherFramework = new TargetFrameworkVersion("v4.5.1");
            var lowerFramework  = new TargetFrameworkVersion("v2.0");

            higherFramework.ShouldBeGreaterThan(lowerFramework);
        }
Beispiel #14
0
        public void target_framework_less_than_when_equal_returns_false()
        {
            var higherFramework = new TargetFrameworkVersion("v2.0");
            var lowerFramework  = new TargetFrameworkVersion("v2.0");

            (higherFramework < lowerFramework).ShouldBeFalse();
        }
        bool ValidateApiLevels()
        {
            // Priority:
            //    $(UseLatestAndroidPlatformSdk) > $(AndroidApiLevel) > $(TargetFrameworkVersion)
            //
            // If $(TargetFrameworkVersion) isn't set, and $(AndroidApiLevel) isn't
            // set, act as if $(UseLatestAndroidPlatformSdk) is True
            //
            // If $(UseLatestAndroidPlatformSdk) is true, we do as it says: use the
            // latest installed version.
            //
            // Otherwise, if $(AndroidApiLevel) is set, use it and set $(TargetFrameworkVersion).
            //    Rationale: monodroid/samples/xbuild.make uses $(AndroidApiLevel)
            //    to build for a specific API level.
            // Otherwise, if $(TargetFrameworkVersion) is set, use it and set $(AndroidApiLevel).

            UseLatestAndroidPlatformSdk = UseLatestAndroidPlatformSdk ||
                                          (string.IsNullOrWhiteSpace(AndroidApiLevel) && string.IsNullOrWhiteSpace(TargetFrameworkVersion));

            if (UseLatestAndroidPlatformSdk)
            {
                AndroidApiLevel        = GetMaxInstalledApiLevel().ToString();
                SupportedApiLevel      = GetMaxSupportedApiLevel(AndroidApiLevel);
                TargetFrameworkVersion = GetTargetFrameworkVersionFromApiLevel();
                return(TargetFrameworkVersion != null);
            }

            if (!string.IsNullOrWhiteSpace(AndroidApiLevel))
            {
                AndroidApiLevel        = AndroidApiLevel.Trim();
                SupportedApiLevel      = GetMaxSupportedApiLevel(AndroidApiLevel);
                TargetFrameworkVersion = GetTargetFrameworkVersionFromApiLevel();
                return(TargetFrameworkVersion != null);
            }

            if (!string.IsNullOrWhiteSpace(TargetFrameworkVersion))
            {
                TargetFrameworkVersion = TargetFrameworkVersion.Trim();
                string apiLevel = MonoDroidSdk.GetApiLevelForFrameworkVersion(TargetFrameworkVersion);
                if (apiLevel == null)
                {
                    Log.LogCodedError("XA0000",
                                      "Could not determine API level for $(TargetFrameworkVersion) of '{0}'.",
                                      TargetFrameworkVersion);
                    return(false);
                }
                AndroidApiLevel   = apiLevel;
                SupportedApiLevel = apiLevel;
                return(true);
            }
            Log.LogCodedError("XA0000", "Could not determine $(AndroidApiLevel) or $(TargetFrameworkVersion); SHOULD NOT BE REACHED.");
            return(false);
        }
        private string GetRuntimeVersion()
        {
            /*string version = "2.0.0";
             * AssemblyReference dotNet30AssemblyReference = ApplicationManifest.AssemblyReferences.Find(DOTNET30AssemblyIdentity);
             * if (dotNet30AssemblyReference != null && dotNet30AssemblyReference.IsPrerequisite)
             * {
             *  version = "3.0.0";
             * }
             * AssemblyReference dotNet35AssemblyReference = ApplicationManifest.AssemblyReferences.Find(DOTNET35AssemblyIdentity);
             * if (dotNet35AssemblyReference != null && dotNet35AssemblyReference.IsPrerequisite)
             * {
             *  version = "3.5.0";
             * }
             *
             * return version;*/

            //Version targetVersion = new Version(TargetFramework >> 16, TargetFramework & 0xffff, 0);
            Version targetVersion = new Version(TargetFrameworkVersion[0] == 'v' ? TargetFrameworkVersion.Substring(1) : TargetFrameworkVersion);

            if (targetVersion.Build == -1)
            {
                targetVersion = new Version(targetVersion.Major, targetVersion.Minor, 0);
            }
            if (targetVersion == new Version(3, 5, 0))
            {
                using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5", false))
                {
                    if ((key != null) && (key.GetValueKind("Version") == RegistryValueKind.String))
                    {
                        try
                        {
                            targetVersion = new Version((string)key.GetValue("Version"));
                        }
                        catch
                        {
                            //TODO: log error?
                        }
                    }
                }
            }
            return(targetVersion.ToString(3));
        }
Beispiel #17
0
 public void can_parse_version_format_from_csproj_file()
 {
     var targetFramework = new TargetFrameworkVersion("v4.5.1");
 }
        public void target_framework_less_than_with_null_returns_true()
        {
            TargetFrameworkVersion higherFramework = null;
            TargetFrameworkVersion lowerFramework = new TargetFrameworkVersion("v2.0");

            (higherFramework < lowerFramework).ShouldBeTrue();
        }
        public void target_framework_less_than_with_null_returns_false()
        {
            TargetFrameworkVersion higherFramework = new TargetFrameworkVersion("v4.5.1");
            TargetFrameworkVersion lowerFramework = null;

            (higherFramework < lowerFramework).ShouldBeFalse();
        }
 public void Can_implicitly_convert_from_targetframework_to_string()
 {
     string framework = new TargetFrameworkVersion("v4.5.1");
     framework.ShouldEqual("v4.5.1");
 }
 public void To_string_should_output_in_msbuild_format()
 {
     var targetFramework = new TargetFrameworkVersion("v4.5.1");
     targetFramework.ToString().ShouldEqual("v4.5.1");
 }
 public void can_parse_version_format_from_csproj_file()
 {
     var targetFramework = new TargetFrameworkVersion("v4.5.1");
 }
Beispiel #23
0
        protected override string GenerateCommandLineCommands()
        {
            var  args = new ProcessArgumentBuilder();
            bool msym;

            args.Add("/verbose");

            if (Debug)
            {
                args.Add("/debug");
            }

            if (!string.IsNullOrEmpty(OutputPath))
            {
                args.AddQuoted("/output:" + Path.GetFullPath(OutputPath));
            }

            if (!string.IsNullOrEmpty(ApplicationName))
            {
                args.AddQuoted("/name:" + ApplicationName);
            }

            if (TargetFrameworkIdentifier == "Xamarin.Mac")
            {
                args.Add("/profile:Xamarin.Mac");
            }
            else if (TargetFrameworkVersion.StartsWith("v", StringComparison.Ordinal))
            {
                args.Add("/profile:" + TargetFrameworkVersion.Substring(1));
            }

            XamMacArch arch;

            if (!Enum.TryParse(Architecture, true, out arch))
            {
                arch = XamMacArch.Default;
            }

            if (arch == XamMacArch.Default)
            {
                arch = XamMacArch.x86_64;
            }

            if (arch.HasFlag(XamMacArch.i386))
            {
                args.Add("/arch:i386");
            }

            if (arch.HasFlag(XamMacArch.x86_64))
            {
                args.Add("/arch:x86_64");
            }

            if (!string.IsNullOrEmpty(ArchiveSymbols) && bool.TryParse(ArchiveSymbols.Trim(), out msym))
            {
                args.Add("--msym:" + (msym ? "yes" : "no"));
            }

            args.Add(string.Format("--http-message-handler={0}", HttpClientHandler));

            if (AppManifest != null)
            {
                try {
                    var plist = PDictionary.FromFile(AppManifest.ItemSpec);

                    PString v;
                    string  minimumDeploymentTarget;

                    if (!plist.TryGetValue(ManifestKeys.LSMinimumSystemVersion, out v) || string.IsNullOrEmpty(v.Value))
                    {
                        minimumDeploymentTarget = SdkVersion;
                    }
                    else
                    {
                        minimumDeploymentTarget = v.Value;
                    }

                    args.Add(string.Format("/minos={0}", minimumDeploymentTarget));
                }
                catch (Exception ex) {
                    Log.LogWarning(null, null, null, AppManifest.ItemSpec, 0, 0, 0, 0, "Error loading '{0}': {1}", AppManifest.ItemSpec, ex.Message);
                }
            }

            if (Profiling)
            {
                args.Add("/profiling");
            }

            if (EnableSGenConc)
            {
                args.Add("/sgen-conc");
            }

            switch ((LinkMode ?? string.Empty).ToLower())
            {
            case "full":
                break;

            case "sdkonly":
                args.Add("/linksdkonly");
                break;

            default:
                args.Add("/nolink");
                break;
            }

            if (!string.IsNullOrEmpty(I18n))
            {
                args.AddQuoted("/i18n:" + I18n);
            }

            if (ExplicitReferences != null)
            {
                foreach (var asm in ExplicitReferences)
                {
                    args.AddQuoted("/assembly:" + Path.GetFullPath(asm.ItemSpec));
                }
            }

            if (!string.IsNullOrEmpty(ApplicationAssembly.ItemSpec))
            {
                args.AddQuoted(Path.GetFullPath(ApplicationAssembly.ItemSpec));
            }

            if (!string.IsNullOrWhiteSpace(ExtraArguments))
            {
                args.Add(ExtraArguments);
            }

            if (NativeReferences != null)
            {
                foreach (var nr in NativeReferences)
                {
                    args.AddQuoted("/native-reference:" + Path.GetFullPath(nr.ItemSpec));
                }
            }

            if (IsAppExtension)
            {
                args.AddQuoted("/extension");
            }

            args.Add("/sdkroot");
            args.AddQuoted(SdkRoot);

            if (!string.IsNullOrEmpty(IntermediateOutputPath))
            {
                Directory.CreateDirectory(IntermediateOutputPath);

                args.Add("--cache");
                args.AddQuoted(Path.GetFullPath(IntermediateOutputPath));
            }

            return(args.ToString());
        }
Beispiel #24
0
        public void Can_implicitly_convert_from_targetframework_to_string()
        {
            string framework = new TargetFrameworkVersion("v4.5.1");

            framework.ShouldEqual("v4.5.1");
        }
Beispiel #25
0
        public void CommitChanges()
        {
            XmlElement root = _xmlDocument.DocumentElement;

            Debug.Assert(root != null, "root != null");
            XmlNode firstPropertyGroup = root.SelectSingleNode("//root:Project/root:PropertyGroup[not(@Condition)]",
                                                               _nsmgr);

            // Save Project general properties
            if (firstPropertyGroup == null)
            {
                throw new InvalidOperationException("Couldn't find correct property group.");
            }
            XmlNode node = firstPropertyGroup.SelectSingleNode("root:RootNamespace", _nsmgr);

            if (node != null)
            {
                node.InnerText = RootNamespace;
            }
            node = firstPropertyGroup.SelectSingleNode("root:AssemblyName", _nsmgr);
            if (node != null)
            {
                node.InnerText = AssemblyName;
            }

            if (_isTargetFrameworkUpdated)
            {
                node = firstPropertyGroup.SelectSingleNode("root:TargetFrameworkVersion", _nsmgr);
                XmlNode nodeProfie = firstPropertyGroup.SelectSingleNode("root:TargetFrameworkProfile", _nsmgr);

                if (node != null && node.InnerText != TargetFrameworkVersion)
                {
                    if (TargetFrameworkVersion.IsInList("v4.5", "v4.5.1", "v4.5.2", "v4.6", "v4.6.1", "v4.6.2"))
                    {
                        node.InnerText = TargetFrameworkVersion;
                        if (nodeProfie != null)
                        {
                            nodeProfie.InnerXml = null;
                            var element = nodeProfie as XmlElement;
                            if (element != null)
                            {
                                element.IsEmpty = true;
                            }
                        }
                        XmlNodeList list = root.SelectNodes("//root:Project/root:PropertyGroup[(@Condition)]",
                                                            _nsmgr);
                        if (list != null)
                        {
                            foreach (XmlNode propertyNode in list)
                            {
                                node = propertyNode.SelectSingleNode("root:Prefer32Bit", _nsmgr);
                                if (node != null)
                                {
                                    continue;
                                }
                                Debug.Assert(root.OwnerDocument != null, "root.OwnerDocument!=null");
                                node           = root.OwnerDocument.CreateElement("Prefer32Bit", _nsmgr.LookupNamespace("root"));
                                node.InnerText = "false";
                                propertyNode.AppendChild(node);
                            }
                        }
                    }
                    else if (TargetFrameworkVersion.IsInList("v4.0", "v4.0 Client Profile"))
                    {
                        if (TargetFrameworkVersion == "v4.0")
                        {
                            node.InnerText = TargetFrameworkVersion;
                        }
                        else
                        {
                            node.InnerText = "v4.0";
                            Debug.Assert(root.OwnerDocument != null, "root.OwnerDocument!=null");
                            if (nodeProfie == null)
                            {
                                nodeProfie = root.OwnerDocument.CreateElement("", _nsmgr.LookupNamespace("root"));
                            }
                            nodeProfie.InnerText = "Client";
                        }
                        XmlNodeList list = root.SelectNodes("//root:Project/root:PropertyGroup[(@Condition)]",
                                                            _nsmgr);
                        if (list != null)
                        {
                            foreach (XmlNode propertyNode in list)
                            {
                                node = propertyNode.SelectSingleNode("root:Prefer32Bit", _nsmgr);
                                if (node == null)
                                {
                                    continue;
                                }
                                propertyNode.RemoveChild(node);
                            }
                        }
                    }
                    else
                    {
                        throw new ApplicationException($"Target framework update not implemented: {TargetFrameworkVersion}");
                    }
                }
            }


            foreach (BuildConfiguration buildConfiguration in BuildConfigurations)
            {
                buildConfiguration.CommitChanges();
            }

            foreach (Reference reference in References)
            {
                reference.CommitChanges();
            }

            _xmlDocument.Save(ProjectFilename);

            IsDirty = false;
        }
Beispiel #26
0
        public override bool Execute()
        {
            string Pathify(string path)
            => string.IsNullOrEmpty(path) ? null : Regex.Replace(
                path,
                @"[\/\\]+",
                Path.DirectorySeparatorChar.ToString());

            string sdkVersion = null;

            if (SdkVersion != null)
            {
                if (SdkVersion.StartsWith("@", StringComparison.Ordinal))
                {
                    var parts = SdkVersion.Substring(1).Split(new [] { ',' }, 2);
                    switch (parts [0])
                    {
                    case "GlobalJsonSdkVersion":
                        sdkVersion = ReadGlobalJsonSdkVersion(Pathify(parts [1]));
                        break;

                    case "AssemblyInformationalVersion":
                        sdkVersion = AssemblyInformationalVersion(parts [1]);
                        break;

                    default:
                        throw new NotImplementedException($"Unable to handle SdkVersion style @{parts [0]}");
                    }

                    if (sdkVersion == null)
                    {
                        return(false);
                    }
                }
            }

            string targetFramework = null;

            TargetFrameworkVersion = TargetFrameworkVersion?.Trim().TrimStart('v');
            if (TargetFrameworkIdentifier != null && TargetFrameworkVersion != null)
            {
                targetFramework = $"{TargetFrameworkIdentifier},Version={TargetFrameworkVersion}";
            }

            var idParts = new List <string> (3)
            {
                Flavor
            };

            if (!string.IsNullOrEmpty(SdkName))
            {
                idParts.Add(SdkName);
            }
            if (!string.IsNullOrEmpty(SdkProfile))
            {
                idParts.Add(SdkProfile);
            }
            var id = string
                     .Join("-", idParts.Select(p => Regex.Replace(p, @"[^A-Za-z0-9]", "")))
                     .ToLowerInvariant();

            var manifest = new JObject {
                [id] = JObject.FromObject(new {
                    flavor             = Flavor,
                    order              = Order,
                    icon               = Icon,
                    appPath            = Pathify(AppPath),
                    appManagerAssembly = Pathify(AppManagerAssembly),
                    sdk = new {
                        name    = SdkName,
                        profile = SdkProfile,
                        version = sdkVersion,
                        targetFramework,
                        assemblySearchPaths = AssemblySearchPaths?.Select(Pathify)
                    },
                    optionalFeatures = OptionalFeatures
                })
            };

            var toRemove = manifest
                           .Descendants()
                           .Where(value => value.Type == JTokenType.Null)
                           .Select(value => value.Parent is JProperty property ? property : value)
                           .ToArray();

            foreach (var nullToken in toRemove)
            {
                nullToken.Remove();
            }

            Directory.CreateDirectory(Path.GetDirectoryName(ManifestOutputPath));

            var workbooks = File.Exists(ManifestOutputPath)
                ? JObject.Parse(File.ReadAllText(ManifestOutputPath))
                : new JObject();

            workbooks.Merge(manifest, new JsonMergeSettings {
                MergeArrayHandling = MergeArrayHandling.Union
            });

            Log.LogMessage(
                MessageImportance.Normal,
                $"Writing manifest entry ({id}): {ManifestOutputPath}");

            File.WriteAllText(
                ManifestOutputPath,
                workbooks.ToString(Formatting.Indented));

            return(true);
        }
Beispiel #27
0
        protected override bool ExecuteIsolated()
        {
            // technically all these checks are redundant as they exist in targets file as conditions,
            // but if we get called SOMEHOW accidentally let's not fail the whole build (return true) but give reason why task failed
            if (!IsExecutable)
            {
                Log.LogError("Can only generate Dockerfile for executable projects");
                return(true);
            }
            if (string.IsNullOrEmpty(SolutionPath) || SolutionPath == "*Undefined*")
            {
                Log.LogError("Can only generate Dockerfile if building from solution");
                return(true);
            }

            var imageVersion = TargetFrameworkVersion.Trim('v');

            if (TargetFrameworkIdentifier != ".NETCoreApp")
            {
                Log.LogMessage("Only .NET Core projects are supported");
                return(true);
            }
            if (!decimal.TryParse(imageVersion, out var imageVersionNum))
            {
                Log.LogWarning("Unsupported .NET Core version");
                return(true);
            }

            if (imageVersionNum < 2.1m || imageVersionNum == 2.2m || imageVersionNum == 3.0m)
            {
                Log.LogWarning($"Unsupported version: project is targeting .NET Core {TargetFrameworkVersion} which is end of life.");
                return(true);
            }
            var solutionFullPath       = (AbsolutePath)SolutionPath;
            var solutionFullDir        = solutionFullPath.Parent;
            var currentProjectFullPath = (AbsolutePath)MSBuildProjectFullPath;
            var currentProjectFullDir  = currentProjectFullPath.Parent;

            var assetsFile = Path.Combine(BaseIntermediateOutputPath, "project.assets.json");
            var assets     = JObject.Parse(File.ReadAllText(assetsFile));
            var projects   = assets
                             .SelectTokens("$..msbuildProject")
                             .OfType <JValue>()
                             .Select(x => currentProjectFullDir / (string)x)
                             .ToList();

            projects.Add(currentProjectFullPath);

            string runImageName = UsingMicrosoftNETSdkWeb ? "mcr.microsoft.com/dotnet/core/aspnet" : "mcr.microsoft.com/dotnet/core/runtime";

            var sb = new StringBuilder();

            sb.AppendLine($"FROM mcr.microsoft.com/dotnet/core/sdk:{imageVersion} AS build");
            sb.AppendLine("WORKDIR src");
            var projectNugetConfigs = projects
                                      .Union(new[] { solutionFullPath })
                                      .SelectMany(projFile =>
            {
                var projFullFolder = projFile.Parent;

                var nugetConfig = projFullFolder / "nuget.config";
                if (!File.Exists(nugetConfig))
                {
                    return(Enumerable.Empty <NugetSource>());
                }
                using (var nugetConfigStream = File.OpenRead(nugetConfig))
                {
                    var doc = new XPathDocument(nugetConfigStream);
                    var nav = doc.CreateNavigator();
                    return(nav.Select("/configuration/packageSources/add")
                           .Cast <XPathNavigator>()
                           .Select(x => x.GetAttribute("value", string.Empty))
                           .Where(x => !Path.IsPathRooted(x))
                           .Select(pkgSource => nugetConfig.Parent / pkgSource)                              // get absolute path to source
                           .Select(x => new NugetSource
                    {
                        NugetFile = nugetConfig,
                        SourceFolder = x
                    })
                           .ToList());
                }
            })
                                      .ToArray();
            var nugetConfigs = projectNugetConfigs.Select(x => x.NugetFile).Distinct();

            sb.AppendLine("# copy nuget.config files at solution and project levels");
            foreach (var nugetConfig in nugetConfigs.Select(x => solutionFullDir.GetRelativePathTo(x)))
            {
                sb.AppendLine($"COPY [\"{nugetConfig}\", \"{nugetConfig}\"]");
            }

            sb.AppendLine("# copy any local nuget sources that are subfolders of the solution");
            foreach (var nugetSource in projectNugetConfigs.Select(x => solutionFullDir.GetRelativePathTo(x.SourceFolder)))
            {
                sb.AppendLine($"COPY [\"{nugetSource}\", \"{nugetSource}\"]");
            }
            foreach (var project in projects)
            {
                var osFixedProject = solutionFullDir.GetUnixRelativePathTo(project);
                sb.AppendLine($"COPY [\"{osFixedProject}\", \"{osFixedProject}\"]");
            }
            sb.AppendLine($"RUN dotnet restore \"{solutionFullDir.GetRelativePathTo(currentProjectFullPath)}\"");
            sb.AppendLine($"COPY . .");
            //var projectPath = currentProject.Replace('\\', '/');
            sb.AppendLine($"RUN dotnet msbuild /p:RestorePackages=false /t:PublishLayer /p:PublishDir=/layer/ /p:DockerLayer=All \"{solutionFullDir.GetUnixRelativePathTo(currentProjectFullPath)}\"");

            sb.AppendLine($"FROM {runImageName}:{imageVersion} AS run");
            sb.AppendLine($"WORKDIR /app");
            foreach (var layer in KnownLayers.AllLayers)
            {
                var layerName = layer.ToString().ToLower();
                sb.AppendLine($"COPY --from=build /layer/{layerName} ./");
            }

            sb.AppendLine($"ENTRYPOINT [\"dotnet\", \"{AssemblyName}.dll\"]");

            var dockerfileName = Path.Combine(currentProjectFullDir, "Dockerfile");

            File.WriteAllText(dockerfileName, sb.ToString());
            Log.LogMessage(MessageImportance.High, $"Generated {dockerfileName}");

            var dockerIgnoreFile = Path.Combine(solutionFullDir, ".dockerignore");

            if (!File.Exists(dockerIgnoreFile))
            {
                File.WriteAllText(dockerIgnoreFile, "**/bin/\n**/obj/\n**/out/\n**/layer/\n**Dockerfile*\n*/*.md");
                Log.LogMessage(MessageImportance.High, "No existing .dockerignore file found");
                Log.LogMessage(MessageImportance.High, $"Generated {dockerIgnoreFile}");
            }

            return(true);
        }
Beispiel #28
0
        public override bool Execute()
        {
            Configuration = GetConfiguration();
            if (string.IsNullOrWhiteSpace(TargetFramework))
            {
                TargetFramework = TargetFrameworkVersion.Replace("v", "net").Replace(".", "");
            }
            if (string.IsNullOrWhiteSpace(PackageId))
            {
                PackageId = Path.GetFileNameWithoutExtension(TargetPath);
            }
            var releasePath = GetLatestReleasePath();

            if (string.IsNullOrWhiteSpace(releasePath) || !File.Exists(releasePath))
            {
                Log.LogMessage(MessageImportance.High, $"A release could not be located for {PackageId}; the assumption is that this will be the first published version for this framework.");
                HasDiverged = true;
                return(true);
            }
            var diversion = new AssemblyDiversionDiviner(new NvAssemblyInfoFactory(), new DiversionDiviner()).Divine(releasePath, TargetPath);

            if (Configuration.GenerateDiversionFile)
            {
                using (var writer = new StreamWriter(File.Create(Path.Combine(Path.GetDirectoryName(TargetPath), "diversion.output.json"))))
                    JsonSerializer.CreateDefault(new JsonSerializerSettings {
                        ContractResolver = new CustomContractResolver()
                    }).Serialize(writer, diversion);
                Log.LogMessage(MessageImportance.High, "Generated diversion.output.json.");
            }
            var nextVersion = new NextVersion().Determine(diversion);
            var version     = diversion.New.Version >= nextVersion ? diversion.New.Version : nextVersion;

            HasDiverged        = diversion.HasDiverged();
            Version            = version.ToString();
            Verified           = version == diversion.New.Version;
            RequiresCorrection = !Verified && Configuration.IsCorrectionEnabled;
            if (!HasDiverged)
            {
                Log.LogMessage(MessageImportance.High, $"{diversion.Identity} has not diverged from its latest release.");
            }
            if (!Verified && !Configuration.IsCorrectionEnabled)
            {
                var message = $"Based on diversion's semantic version rules, the version of {diversion.Identity} being built should be at least {nextVersion}, but is set at {diversion.New.Version}.";
                if (Configuration.Warn)
                {
                    Log.LogWarning(message);
                }
                else
                {
                    Log.LogError(message);
                }
            }
            if (Verified && HasDiverged)
            {
                Log.LogMessage(MessageImportance.High, $"Based on diversion's semantic version rules, the version of {diversion.Identity} being built has the correct version of {diversion.New.Version}.");
            }
            if (RequiresCorrection)
            {
                Log.LogMessage(MessageImportance.High, $"Based on diversion's semantic version rules, the version of {diversion.Identity} will be changed from {diversion.Old.Version} to {nextVersion}.");
            }
            return(Configuration.IsCorrectionEnabled || Verified || Configuration.Warn);
        }
Beispiel #29
0
        bool ValidateApiLevels()
        {
            // Priority:
            //    $(UseLatestAndroidPlatformSdk) > $(AndroidApiLevel) > $(TargetFrameworkVersion)
            //
            // If $(TargetFrameworkVersion) isn't set, and $(AndroidApiLevel) isn't
            // set, act as if $(UseLatestAndroidPlatformSdk) is True
            //
            // If $(UseLatestAndroidPlatformSdk) is true, we do as it says: use the
            // latest installed version.
            //
            // Otherwise, if $(AndroidApiLevel) is set, use it and set $(TargetFrameworkVersion).
            //    Rationale: monodroid/samples/xbuild.make uses $(AndroidApiLevel)
            //    to build for a specific API level.
            // Otherwise, if $(TargetFrameworkVersion) is set, use it and set $(AndroidApiLevel).

            UseLatestAndroidPlatformSdk = UseLatestAndroidPlatformSdk ||
                                          (string.IsNullOrWhiteSpace(AndroidApiLevel) && string.IsNullOrWhiteSpace(TargetFrameworkVersion));

            if (UseLatestAndroidPlatformSdk)
            {
                int maxInstalled = GetMaxInstalledApiLevel();
                int maxSupported = GetMaxStableApiLevel();
                AndroidApiLevel = maxInstalled.ToString();
                if (maxInstalled > maxSupported)
                {
                    Log.LogDebugMessage($"API Level {maxInstalled} is greater than the maximum supported API level of {maxSupported}. " +
                                        "Support for this API will be added in a future release.");
                }
                if (!string.IsNullOrWhiteSpace(TargetFrameworkVersion))
                {
                    var userSelected = MonoAndroidHelper.SupportedVersions.GetApiLevelFromFrameworkVersion(TargetFrameworkVersion);
                    // overwrite using user version only if it is
                    // above the maxStableApi and a valid apiLevel.
                    if (userSelected != null && userSelected > maxSupported && userSelected <= maxInstalled)
                    {
                        maxInstalled     =
                            maxSupported = userSelected.Value;
                        AndroidApiLevel  = userSelected.ToString();
                    }
                }

                for (int apiLevel = maxSupported; apiLevel >= MonoAndroidHelper.SupportedVersions.MinStableVersion.ApiLevel; apiLevel--)
                {
                    var id             = MonoAndroidHelper.SupportedVersions.GetIdFromApiLevel(apiLevel);
                    var apiPlatformDir = MonoAndroidHelper.AndroidSdk.TryGetPlatformDirectoryFromApiLevel(id, MonoAndroidHelper.SupportedVersions);
                    if (apiPlatformDir != null && Directory.Exists(apiPlatformDir))
                    {
                        var targetFramework = MonoAndroidHelper.SupportedVersions.GetFrameworkVersionFromId(id);
                        if (targetFramework != null && MonoAndroidHelper.SupportedVersions.InstalledBindingVersions.Any(b => b.FrameworkVersion == targetFramework))
                        {
                            AndroidApiLevel        = apiLevel.ToString();
                            TargetFrameworkVersion = targetFramework;
                            break;
                        }
                    }
                }
                return(TargetFrameworkVersion != null);
            }

            if (!string.IsNullOrWhiteSpace(TargetFrameworkVersion))
            {
                TargetFrameworkVersion = TargetFrameworkVersion.Trim();
                string id = MonoAndroidHelper.SupportedVersions.GetIdFromFrameworkVersion(TargetFrameworkVersion);
                if (id == null)
                {
                    Log.LogCodedError("XA0000", Properties.Resources.XA0000_API_for_TargetFrameworkVersion, TargetFrameworkVersion);
                    return(false);
                }
                AndroidApiLevel = MonoAndroidHelper.SupportedVersions.GetApiLevelFromId(id).ToString();
                return(true);
            }

            if (!string.IsNullOrWhiteSpace(AndroidApiLevel))
            {
                AndroidApiLevel        = AndroidApiLevel.Trim();
                TargetFrameworkVersion = GetTargetFrameworkVersionFromApiLevel();
                return(TargetFrameworkVersion != null);
            }

            Log.LogCodedError("XA0000", Properties.Resources.XA0000_API_or_TargetFrameworkVersion_Fail);
            return(false);
        }
Beispiel #30
0
        public void To_string_should_output_in_msbuild_format()
        {
            var targetFramework = new TargetFrameworkVersion("v4.5.1");

            targetFramework.ToString().ShouldEqual("v4.5.1");
        }
Beispiel #31
0
        /// <summary>
        /// Executes the task.
        /// </summary>
        public override bool Execute()
        {
            CommandLineBuilder commandLine = new CommandLineBuilder();

            commandLine.AppendSwitchIfNotNull("/attr:", _attributeFile);
            if (Closed)
            {
                commandLine.AppendSwitch("/closed");
            }
            if (CopyAttributes)
            {
                commandLine.AppendSwitch("/copyattrs");
            }
            if (DebugInfo)
            {
                commandLine.AppendSwitch("/ndebug");
            }
            if (Internalize)
            {
                commandLine.AppendSwitch("/internalize:" + ExcludeFile);
            }
            if (ShouldLog)
            {
                if (LogFile == null)
                {
                    commandLine.AppendSwitch("/log");
                }
                else
                {
                    commandLine.AppendSwitch("/log:");
                    commandLine.AppendFileNameIfNotNull(LogFile);
                }
            }
            commandLine.AppendSwitchIfNotNull("/keyfile:", SnkFile);
            commandLine.AppendSwitchIfNotNull("/target:", TargetKind);
            if (MergeXml)
            {
                commandLine.AppendSwitch("/xmldocs");
            }

            TargetDotNetFrameworkVersion frameworkVersion;
            string framework;

            switch (TargetFrameworkVersion?.Trim().ToLowerInvariant())
            {
            //v2.0, v3.0, v3.5, v4.0, v4.5, and v4.5.1.
            case "v2.0":
                frameworkVersion = TargetDotNetFrameworkVersion.Version20;
                framework        = "v2";
                break;

            case "v3.0":
                frameworkVersion = TargetDotNetFrameworkVersion.Version30;
                framework        = "v2";
                break;

            case "v3.5":
                frameworkVersion = TargetDotNetFrameworkVersion.Version35;
                framework        = "v2";
                break;

            case "v4.0":
                frameworkVersion = TargetDotNetFrameworkVersion.Version40;
                framework        = "v4";
                break;

            // ReSharper disable RedundantCaseLabel
            case "v4.5":
            case "v4.5.1":
            case "v4.5.2":
            case "v4.6":
            // ReSharper restore RedundantCaseLabel
            default:
                frameworkVersion = TargetDotNetFrameworkVersion.Version45;
                framework        = "v4";
                break;
            }

            DotNetFrameworkArchitecture platformArchitecture;

            switch (TargetPlatform?.Trim().ToLowerInvariant())
            {
            case "x86":
                platformArchitecture = DotNetFrameworkArchitecture.Bitness32;
                break;

            case "x64":
                platformArchitecture = DotNetFrameworkArchitecture.Bitness64;
                break;

            default:
                platformArchitecture = DotNetFrameworkArchitecture.Current;
                break;
            }

            string toolPath = ToolLocationHelper.GetPathToDotNetFramework(
                frameworkVersion,
                platformArchitecture);

            Debug.Assert(Log != null);

            Log.LogMessage(
                MessageImportance.Normal,
                "Merge Framework: {0}, {1}",
                TargetFrameworkVersion,
                toolPath);

            commandLine.AppendSwitch($"/targetplatform:{framework},{toolPath}");

            if (LibraryPath != null)
            {
                List <string> list = new List <string>(LibraryPath.Select(taskItem => taskItem.ItemSpec))
                {
                    "."
                };
                foreach (string dir in list)
                {
                    commandLine.AppendSwitchIfNotNull("/lib:", dir);
                }
            }

            commandLine.AppendSwitchIfNotNull("/out:", OutputFile);

            commandLine.AppendFileNamesIfNotNull(InputAssemblies, " ");

            try
            {
                Log.LogMessage(
                    MessageImportance.Normal,
                    "Merging {0} assembl{1} to '{2}'.",
                    InputAssemblies.Length,
                    InputAssemblies.Length != 1 ? "ies" : "y",
                    _outputFile);

                Log.LogMessage(MessageImportance.Low, ILMergeTool + " " + commandLine);

                Process proc = new Process
                {
                    StartInfo = new ProcessStartInfo(ILMergeTool, commandLine.ToString())
                    {
                        RedirectStandardError  = true,
                        RedirectStandardOutput = true,
                        UseShellExecute        = false
                    }
                };
                proc.OutputDataReceived += (sender, args) =>
                {
                    Debug.Assert(args != null);

                    // Null is sent when the stream closes, so skip it
                    if (!string.IsNullOrEmpty(args.Data))
                    {
                        Log.LogMessage(args.Data);
                    }
                };
                proc.ErrorDataReceived += (sender, args) =>
                {
                    Debug.Assert(args != null);

                    // Null is sent when the stream closes, so skip it
                    if (!string.IsNullOrEmpty(args.Data))
                    {
                        Log.LogError(args.Data);
                    }
                };
                proc.Start();
                proc.BeginOutputReadLine();
                proc.BeginErrorReadLine();
                proc.WaitForExit();
                if (proc.ExitCode != 0)
                {
                    Log.LogError("ILMerge exited with error code {0}.", proc.ExitCode);
                }
                else
                {
                    Log.LogMessage("ILMerge completed successfully.");
                }
                return(proc.ExitCode == 0);
            }
            catch (Exception ex)
            {
                Log.LogErrorFromException(ex);
                return(false);
            }
        }
Beispiel #32
0
        public void Can_implicitly_convert_from_string_to_targetframework()
        {
            TargetFrameworkVersion framework = "v4.5.1";

            framework.ShouldNotBeNull();
        }