Example #1
0
        private void CopyFile(string filePath, string destPath)
        {
            var skeletonPath     = Path.GetFullPath("skel");
            var destFileName     = string.IsNullOrEmpty(destPath) ? filePath : destPath;
            var destFileNameFull = Path.GetFullPath(Path.Combine(ProjectRootDir, destFileName));

            if (File.Exists(destFileNameFull))
            {
                Logger.Info("skip  {0}", destFileName);
            }
            else
            {
                var version           = MaxLibVersion.ToString();
                var normalizedVersion = MaxLibVersion.ToNormalizedString();

                File.Copy(Path.Combine(skeletonPath, filePath), destFileNameFull);
                var fileContent = File.ReadAllText(destFileNameFull)
                                  .Replace("$safeprojectname$", SafeProjectName)
                                  .Replace("$guid1$", Guid.NewGuid().ToString())
                                  .Replace("$guid2$", Guid.NewGuid().ToString())
                                  .Replace("$nugetLibVersion$", version)
                                  .Replace("$gaugeprojectfile$", ProjectFilePath)
                                  .Replace("$nugetLibNormalizedVersion$", normalizedVersion);

                File.WriteAllText(destFileNameFull, fileContent);
                Logger.Info("create  {0}", destFileName);
            }
        }
Example #2
0
        public void Remove(string id, SemanticVersion version, bool enableDelisting)
        {
            if (enableDelisting)
            {
                if (_fileSystem is PhysicalFileSystem physicalFileSystem)
                {
                    var fileName = physicalFileSystem.GetFullPath(
                        GetPackageFileName(id, version.ToNormalizedString()));

                    if (File.Exists(fileName))
                    {
                        File.SetAttributes(fileName, File.GetAttributes(fileName) | FileAttributes.Hidden);
                    }
                    else
                    {
                        _logger.Log(
                            LogLevel.Error,
                            "Error removing package {0} {1} - could not find package file {2}",
                            id,
                            version,
                            fileName);
                    }
                }
            }
            else
            {
                var package = _repository.FindPackage(id, version);

                if (package != null)
                {
                    _repository.RemovePackage(package);
                }
            }
        }
        public AppInfo Create()
        {
            var assembly = Assembly.GetExecutingAssembly();
            var semVer   = new SemanticVersion(assembly.GetName().Version.ToStringInvariant());

            return(new AppInfo(assembly.GetName().Name, semVer.ToNormalizedString()));
        }
Example #4
0
        public virtual string GetPackageDirectory(string packageId, SemanticVersion version)
        {
            var directory = packageId;

            directory += "." + version.ToNormalizedString();
            return(directory);
        }
Example #5
0
        public virtual string GetPackageFileName(string packageId, SemanticVersion version)
        {
            var fileNameBase = packageId;

            fileNameBase += "." + version.ToNormalizedString();
            return(fileNameBase + PackageConstants.PackageExtension);
        }
Example #6
0
 public static NuGetVersion ToNuGetVersion([NotNull] this SemanticVersion version)
 {
     if (version == null)
     {
         throw new ArgumentNullException(nameof(version));
     }
     return(NuGetVersion.Parse(version.ToNormalizedString()));
 }
        public void ToStringReturnsDropsMetadata(string version)
        {
            // Act
            SemanticVersion semVer = new SemanticVersion(version);

            // Assert
            Assert.Equal(-1, semVer.ToString().IndexOf('+'));
            Assert.Equal(-1, semVer.ToNormalizedString().IndexOf('+'));
        }
        public override string ToString()
        {
            if (SemanticVersion != null)
            {
                return(SemanticVersion.ToNormalizedString());
            }

            return($"[{Version}]");
        }
        public void NormalizeVersion_NormalizesVersionTo3Digits(string versionString, string expected)
        {
            // Arrange
            var version = new SemanticVersion(versionString);

            // Act
            var result = version.ToNormalizedString();

            // Assert
            Assert.Equal(result, expected);
        }
        public string GetVersionString()
        {
            SemanticVersion version = GetVersion();

            if (version != null)
            {
                return(version.ToNormalizedString());
            }

            return(null);
        }
        public void ParseSemanticVersionStrict(string versionString)
        {
            // Act
            SemanticVersion semVer = null;

            SemanticVersion.TryParseStrict(versionString, out semVer);

            // Assert
            Assert.Equal <string>(versionString, semVer.ToFullString());
            Assert.Equal <string>(semVer.ToNormalizedString(), semVer.ToString());
        }
        private string GetNewVersion()
        {
            var existingVersion = SemanticVersion.Parse(_manifest.Metadata.Version);

            var newVersion = new SemanticVersion(
                existingVersion.Version.Major,
                existingVersion.Version.Minor,
                existingVersion.Version.Build + 1,
                existingVersion.SpecialVersion);

            return(newVersion.ToNormalizedString());
        }
Example #13
0
        /// <summary>
        /// Updates the global.json entries for tools.dotnet and sdk.version if they are older than an incoming version
        /// </summary>
        /// <param name="incomingDotnetVersion">version to compare against</param>
        /// <param name="repoGlobalJson">Global.Json file to update</param>
        /// <returns>Updated global.json file if was able to update, or the unchanged global.json if unable to</returns>
        private GitFile UpdateDotnetVersionGlobalJson(SemanticVersion incomingDotnetVersion, GitFile repoGlobalJson)
        {
            string repoGlobalJsonContent = repoGlobalJson.ContentEncoding == ContentEncoding.Base64 ?
                                           _gitClient.GetDecodedContent(repoGlobalJson.Content) :
                                           repoGlobalJson.Content;

            try
            {
                JObject parsedGlobalJson = JObject.Parse(repoGlobalJsonContent);
                if (SemanticVersion.TryParse(parsedGlobalJson.SelectToken("tools.dotnet").ToString(), out SemanticVersion repoDotnetVersion))
                {
                    if (repoDotnetVersion.CompareTo(incomingDotnetVersion) < 0)
                    {
                        parsedGlobalJson["tools"]["dotnet"] = incomingDotnetVersion.ToNormalizedString();

                        // Also update and keep sdk.version in sync.
                        JToken sdkVersion = parsedGlobalJson.SelectToken("sdk.version");
                        if (sdkVersion != null)
                        {
                            parsedGlobalJson["sdk"]["version"] = incomingDotnetVersion.ToNormalizedString();
                        }
                        return(new GitFile(VersionFiles.GlobalJson, parsedGlobalJson));
                    }
                    return(repoGlobalJson);
                }
                else
                {
                    _logger.LogError("Could not parse the repo's dotnet version from the global.json. Skipping update to dotnet version sections");
                    return(repoGlobalJson);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to update Dotnet version for global.json. Skipping update to version sections.");
                return(repoGlobalJson);
            }
        }
        /// <summary>
        /// Determines if a relative file path could have been generated by <see cref="ExpandedPackageRepository"/>.
        /// The path is assumed to be relative to the base of the package directory.
        /// </summary>
        /// <param name="path">The file path to parse.</param>
        /// <param name="id">The package ID found.</param>
        /// <param name="version">The package version found.</param>
        /// <returns>True if the file name is known.</returns>
        public static bool TryParseFileName(string path, out string id, out SemanticVersion version)
        {
            id      = null;
            version = null;

            if (path == null || Path.IsPathRooted(path))
            {
                return(false);
            }

            var pathPieces = path.Split(Path.DirectorySeparatorChar);

            if (pathPieces.Length != 3) // {id}\{version}\{file name}
            {
                return(false);
            }

            id = pathPieces[pathPieces.Length - 3];
            var unparsedVersion = pathPieces[pathPieces.Length - 2];
            var fileName        = pathPieces[pathPieces.Length - 1];

            if (!SemanticVersion.TryParse(unparsedVersion, out version) ||
                version.ToNormalizedString() != unparsedVersion)
            {
                return(false);
            }

            string expectedFileName;

            if (fileName.EndsWith(NuGet.Constants.PackageExtension))
            {
                expectedFileName = $"{id}.{version}{NuGet.Constants.PackageExtension}";
            }
            else if (fileName.EndsWith(NuGet.Constants.HashFileExtension))
            {
                expectedFileName = $"{id}.{version}{NuGet.Constants.HashFileExtension}";
            }
            else if (fileName.EndsWith(NuGet.Constants.ManifestExtension))
            {
                expectedFileName = $"{id}{NuGet.Constants.ManifestExtension}";
            }
            else
            {
                return(false);
            }

            return(expectedFileName == fileName);
        }
Example #15
0
        public Option <NugetPackage> Get(string id, SemanticVersion version)
        {
            try
            {
                const string sql = "SELECT * FROM dbo.NugetResultCache WHERE Id = @Id AND Version = @Version";
                using (var con = new SqlConnection(_connectionString))
                {
                    con.Open();
                    using (var cmd = new SqlCommand(sql, con))
                    {
                        cmd.Parameters.AddWithValue("Id", id);
                        cmd.Parameters.AddWithValue("Version", version.ToNormalizedString());
                        var reader = cmd.ExecuteReader();
                        if (reader.Read())
                        {
                            var dependencies = ((string)reader["Dependencies"])
                                               .Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

                            var frameworks = ((string)reader["Frameworks"])
                                             .Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)
                                             .Select(n => new FrameworkName(n)).ToArray();

                            var supportType = (SupportType)Enum.Parse(typeof(SupportType), (string)reader["SupportType"]);

                            return(new NugetPackage(
                                       (string)reader["Id"],
                                       dependencies,
                                       supportType,
                                       SemanticVersion.Parse((string)reader["Version"]),
                                       frameworks
                                       )
                            {
                                ProjectUrl = reader["ProjectUrl"] as string
                            });
                        }
                        else
                        {
                            return(Option <NugetPackage> .ToNone);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Warning(ex, "Could not retrieve {id} {version} in Nuget Package Cache", id, version);
                return(Option <NugetPackage> .ToNone);
            }
        }
        public PackageVersion(string packageId, SemanticVersion version)
        {
            if (version == null)
            {
                throw new ArgumentNullException(nameof(version));
            }

            if (string.IsNullOrWhiteSpace(packageId))
            {
                throw new ArgumentException("Argument is null or whitespace", nameof(packageId));
            }

            PackageId = packageId;
            Version   = version;
            Key       = $"{PackageId}_{Version.ToNormalizedString()}";
        }
        public async Task <MayBe <InstalledPackage> > InstallPackageAsync(
            DeploymentExecutionDefinition deploymentExecutionDefinition,
            DirectoryInfo tempDirectory,
            bool includeVersion                 = true,
            SemanticVersion explicitVersion     = null,
            CancellationToken cancellationToken = default)
        {
            if (deploymentExecutionDefinition == null)
            {
                throw new ArgumentNullException(nameof(deploymentExecutionDefinition));
            }

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

            string executePath = deploymentExecutionDefinition.NuGetExePath.WithDefault(_deployerConfiguration.NuGetExePath);

            if (string.IsNullOrWhiteSpace(executePath))
            {
                throw new InvalidOperationException("The NuGet executable file path is not defined");
            }

            if (!File.Exists(executePath))
            {
                throw new InvalidOperationException($"The NuGet executable file '{executePath}' does not exist");
            }

            var arguments = new List <string> {
                "install", deploymentExecutionDefinition.PackageId
            };

            void AddVersion(string value)
            {
                arguments.Add("-Version");
                arguments.Add(value);
            }

            if (explicitVersion != null)
            {
                AddVersion(explicitVersion.ToNormalizedString());
            }
            else if (deploymentExecutionDefinition.SemanticVersion is {})
Example #18
0
        private static string GetSimpleNuspecString(string packageId,
                                                    string packageVersion,
                                                    bool frameworkAssemblies,
                                                    SemanticVersion minClientVersion,
                                                    bool dependencies)
        {
            var frameworkAssemblyReferences = frameworkAssemblies ?
                                              string.Format(FrameworkAssembliesStringFormat, "System.Xml", "net45") : string.Empty;

            var minClientVersionString = minClientVersion == null ? string.Empty :
                                         string.Format(MinClientVersionStringFormat, minClientVersion.ToNormalizedString());

            var dependenciesString = dependencies ?
                                     string.Format(DependenciesStringFormat, "Owin", "1.0") : string.Empty;

            return(string.Format(NuspecStringFormat, packageId, packageVersion,
                                 string.Join(Environment.NewLine, frameworkAssemblyReferences, dependenciesString),
                                 minClientVersionString));
        }
Example #19
0
        public void Constructor_DeserializesSemVer2Version()
        {
            // Arrange
            var cacheFile  = "{\"SchemaVersion\":\"3.0.0\",\"Packages\":[{\"Id\":\"" + PackageId + "\",\"Version\":\"" + SemVer2VersionString + "\"}]}";
            var fileSystem = new Mock <IFileSystem>();

            fileSystem
            .Setup(x => x.FileExists(CacheFileName))
            .Returns(true);
            fileSystem
            .Setup(x => x.OpenFile(CacheFileName))
            .Returns(() => new MemoryStream(Encoding.UTF8.GetBytes(cacheFile)));

            // Act
            var actual = new ServerPackageCache(fileSystem.Object, CacheFileName);

            // Assert
            Assert.Equal(1, actual.GetAll().Count());
            var package = actual.GetAll().First();

            Assert.Equal(SemVer2Version.ToOriginalString(), package.Version.ToOriginalString());
            Assert.Equal(SemVer2Version.ToFullString(), package.Version.ToFullString());
            Assert.Equal(SemVer2Version.ToNormalizedString(), package.Version.ToNormalizedString());
        }
        private static void VerifyPreReleaseAllowed(
            SemanticVersion version,
            DeploymentTarget deploymentTarget,
            string packageId,
            ILogger logger)
        {
            if (version.IsPrerelease && !deploymentTarget.AllowPreRelease)
            {
                throw new DeployerAppException(
                          $"Could not deploy package with id '{packageId}' to target '{deploymentTarget}' because the package is a pre-release version and the target does not support it");
            }

            if (version.IsPrerelease)
            {
                if (logger.IsEnabled(LogEventLevel.Debug))
                {
                    logger.Debug(
                        "The deployment target '{DeploymentTarget}' allows package id '{PackageId}' version {Version}, pre-release",
                        deploymentTarget,
                        packageId,
                        version.ToNormalizedString());
                }
            }
        }
 public void NormalizesStringOutputForDisplayAndUniqueness(SemanticVersion version, string expected)
 {
     Assert.Equal(expected, version.ToNormalizedString(), StringComparer.Ordinal);
 }
Example #22
0
        async Task CheckForUpdates()
        {
            try
            {
                if (Config.Default.settings.update.isDisabled)
                {
                    Trace.TraceInformation("The software update check is disabled by the user; skipping check");
                    return;
                }

                // Remove any old ClickOnce installs
                try
                {
                    var uninstallInfo = UninstallInfo.Find("IPFilter Updater");
                    if (uninstallInfo != null)
                    {
                        Trace.TraceWarning("Old ClickOnce app installed! Trying to remove...");
                        var uninstaller = new Uninstaller();
                        uninstaller.Uninstall(uninstallInfo);
                        Trace.TraceInformation("Successfully removed ClickOnce app");
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Failed to remove old ClickOnce app: " + ex);
                }

                var applicationDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "IPFilter");
                var installerDir         = new DirectoryInfo(Path.Combine(applicationDirectory, "installer"));

                // Detect the current running version. The ProductVersion contains the informational, semantic version e.g. "3.0.0-beta"
                var versionInfo    = Process.GetCurrentProcess().MainModule.FileVersionInfo;
                var currentVersion = new SemanticVersion(versionInfo.ProductVersion);

                // Remove any old installers
                try
                {
                    if (!installerDir.Exists)
                    {
                        installerDir.Create();
                    }
                    else if (!Config.Default.settings.update.isCleanupDisabled)
                    {
                        // Don't delete the MSI for the current installed version
                        var currentMsiName = "IPFilter." + currentVersion.ToNormalizedString() + ".msi";

                        // Scan the directory for all installers
                        foreach (var fileInfo in installerDir.GetFiles("IPFilter.*.msi"))
                        {
                            // Don't remove the installer for the installed version
                            if (fileInfo.Name.Equals(currentMsiName, StringComparison.OrdinalIgnoreCase))
                            {
                                continue;
                            }

                            Trace.TraceInformation("Removing cached installer: " + fileInfo.Name);
                            fileInfo.SafeDelete();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Couldn't clean up old installers: " + ex);
                }

                Trace.TraceInformation("Checking for software updates...");
                progress.Report(new ProgressModel(UpdateState.Downloading, "Checking for software updates...", -1));

                var updater = new Updater();

                var result = await updater.CheckForUpdateAsync(Config.Default.settings.update.isPreReleaseEnabled);

                if (result == null)
                {
                    return;
                }

                var latestVersion = new SemanticVersion(result.Version);

                Update.IsUpdateAvailable = latestVersion > currentVersion;

                if (Update.IsUpdateAvailable)
                {
                    Update.AvailableVersion       = latestVersion;
                    Update.IsUpdateRequired       = true;
                    Update.MinimumRequiredVersion = latestVersion;
                    Update.UpdateSizeBytes        = 2000000;
                }

                Trace.TraceInformation("Current version: {0}", Update.CurrentVersion);
                Trace.TraceInformation("Available version: {0}", Update.AvailableVersion?.ToString() ?? "<no updates>");

                if (!Update.IsUpdateAvailable)
                {
                    return;
                }

                if (MessageBoxHelper.Show(dispatcher, "Update Available", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes,
                                          "An update to version {0} is available. Would you like to update now?", Update.AvailableVersion) != MessageBoxResult.Yes)
                {
                    return;
                }

                Trace.TraceInformation("Starting application update...");

                // If we're not "installed", then don't check for updates. This is so the
                // executable can be stand-alone. Stand-alone self-update to come later.
                using (var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\IPFilter"))
                {
                    var installPath = (string)key?.GetValue("InstallPath");
                    if (installPath == null)
                    {
                        using (var process = new Process())
                        {
                            process.StartInfo = new ProcessStartInfo("https://www.ipfilter.app/")
                            {
                                UseShellExecute = true
                            };

                            process.Start();
                            return;
                        }
                    }
                }

                // Download the MSI to the installer directory
                var msiPath = Path.Combine(installerDir.FullName, "IPFilter." + Update.AvailableVersion + ".msi");

                // Download the installer
                using (var handler = new WebRequestHandler())
                {
                    handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

                    var uri = new Uri($"{result.Uri}?{DateTime.Now.ToString("yyyyMMddHHmmss")}");

                    using (var httpClient = new HttpClient(handler))
                        using (var response = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken.Token))
                        {
                            if (cancellationToken.IsCancellationRequested)
                            {
                                progress.Report(new ProgressModel(UpdateState.Ready, "Update cancelled. Ready.", 100));
                                Update.IsUpdating = false;
                                return;
                            }

                            var    length          = response.Content.Headers.ContentLength;
                            double lengthInMb      = !length.HasValue ? -1 : (double)length.Value / 1024 / 1024;
                            double bytesDownloaded = 0;

                            using (var stream = await response.Content.ReadAsStreamAsync())
                                using (var msi = File.Open(msiPath, FileMode.Create, FileAccess.Write, FileShare.Read))
                                {
                                    var buffer = new byte[65535 * 4];

                                    int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken.Token);

                                    while (bytesRead != 0)
                                    {
                                        await msi.WriteAsync(buffer, 0, bytesRead, cancellationToken.Token);

                                        bytesDownloaded += bytesRead;

                                        if (length.HasValue)
                                        {
                                            double downloadedMegs = bytesDownloaded / 1024 / 1024;
                                            var    percent        = (int)Math.Floor((bytesDownloaded / length.Value) * 100);

                                            var status = string.Format(CultureInfo.CurrentUICulture, "Downloaded {0:F2} MB of {1:F2} MB", downloadedMegs, lengthInMb);

                                            Update.IsUpdating         = true;
                                            Update.DownloadPercentage = percent;
                                            progress.Report(new ProgressModel(UpdateState.Downloading, status, percent));
                                        }

                                        if (cancellationToken.IsCancellationRequested)
                                        {
                                            progress.Report(new ProgressModel(UpdateState.Ready, "Update cancelled. Ready.", 100));
                                            Update.IsUpdating = false;
                                            return;
                                        }

                                        bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken.Token);
                                    }
                                }
                        }
                }

                progress.Report(new ProgressModel(UpdateState.Ready, "Launching update...", 100));
                Update.IsUpdating = false;

                // Now run the installer
                var sb = new StringBuilder("msiexec.exe ");

                // Enable logging for the installer
                var installLog = Path.Combine(applicationDirectory, "install.log");
                sb.AppendFormat(" /l*v \"{0}\"", installLog);

                sb.AppendFormat(" /i \"{0}\"", msiPath);

                //sb.Append(" /passive");

                ProcessInformation processInformation = new ProcessInformation();
                StartupInfo        startupInfo        = new StartupInfo();
                SecurityAttributes processSecurity    = new SecurityAttributes();
                SecurityAttributes threadSecurity     = new SecurityAttributes();
                processSecurity.nLength = Marshal.SizeOf(processSecurity);
                threadSecurity.nLength  = Marshal.SizeOf(threadSecurity);

                const int NormalPriorityClass = 0x0020;

                if (!ProcessManager.CreateProcess(null, sb, processSecurity,
                                                  threadSecurity, false, NormalPriorityClass,
                                                  IntPtr.Zero, null, startupInfo, processInformation))
                {
                    throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
                }

                try
                {
                    //dispatcher.Invoke(DispatcherPriority.Normal, new Action(Application.Current.Shutdown));
                    Application.Current.Shutdown();
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Exception when shutting down app for update: " + ex);
                    Update.ErrorMessage = "Couldn't shutdown the app to apply update.";
                }
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("Application update check failed: " + ex);
            }
            finally
            {
                progress.Report(new ProgressModel(UpdateState.Ready, "Ready", 0));
            }
        }
 private string GetHashFileName(string packageId, SemanticVersion version)
 {
     return(string.Format(TemplateHashFilename, packageId, version.ToNormalizedString(), NuGet.Constants.HashFileExtension));
 }
 private string GetPackageFileName(string packageId, SemanticVersion version)
 {
     return(string.Format(TemplateNupkgFilename, packageId, version.ToNormalizedString()));
 }
 public static string ToNormalizedStringSafe(this SemanticVersion self)
 {
     return(self != null?self.ToNormalizedString() : String.Empty);
 }
 private string GetHashFileName(string packageId, SemanticVersion version)
 {
     return string.Format(TemplateHashFilename, packageId, version.ToNormalizedString(), NuGet.Constants.HashFileExtension);
 }
Example #27
0
 private static string GetPackagePath(string packageId, SemanticVersion version)
 {
     return(Path.Combine(
                GetPackageRoot(packageId, version),
                packageId + "." + version.ToNormalizedString() + Constants.PackageExtension));
 }
        public async Task Run()
        {
            // Gather download count data from statistics warehouse
            IReadOnlyCollection <DownloadCountData> downloadData;

            Trace.TraceInformation("Gathering Download Counts from {0}/{1}...", StatisticsDatabase.DataSource, StatisticsDatabase.InitialCatalog);
            using (var connection = await StatisticsDatabase.ConnectTo())
                using (var transaction = connection.BeginTransaction(IsolationLevel.Snapshot))
                {
                    downloadData = (await connection.QueryWithRetryAsync <DownloadCountData>(
                                        _storedProcedureName, commandType: CommandType.StoredProcedure, transaction: transaction, commandTimeout: _defaultCommandTimeout)).ToList();
                }

            Trace.TraceInformation("Gathered {0} rows of data.", downloadData.Count);

            if (downloadData.Any())
            {
                SemanticVersion semanticVersion = null;

                // Group based on Package Id
                var grouped       = downloadData.GroupBy(p => p.PackageId);
                var registrations = new JArray();
                foreach (var group in grouped)
                {
                    var details = new JArray();
                    details.Add(group.Key);
                    foreach (var gv in group)
                    {
                        // downloads.v1.json should only contain normalized versions - ignore others
                        if (!string.IsNullOrEmpty(gv.PackageVersion) &&
                            SemanticVersion.TryParse(gv.PackageVersion, out semanticVersion) &&
                            gv.PackageVersion == semanticVersion.ToNormalizedString())
                        {
                            var version = new JArray(gv.PackageVersion, gv.TotalDownloadCount);
                            details.Add(version);
                        }
                    }
                    registrations.Add(details);
                }

                var reportText = registrations.ToString(Formatting.None);

                foreach (var storageContainerTarget in Targets)
                {
                    try
                    {
                        var targetBlobContainer = await GetBlobContainer(storageContainerTarget);

                        var blob = targetBlobContainer.GetBlockBlobReference(ReportName);
                        Trace.TraceInformation("Writing report to {0}", blob.Uri.AbsoluteUri);
                        blob.Properties.ContentType = "application/json";
                        await blob.UploadTextAsync(reportText);

                        Trace.TraceInformation("Wrote report to {0}", blob.Uri.AbsoluteUri);
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("Error writing report to storage account {0}, container {1}. {2} {3}",
                                         storageContainerTarget.StorageAccount.Credentials.AccountName,
                                         storageContainerTarget.ContainerName, ex.Message, ex.StackTrace);
                    }
                }
            }
        }
Example #29
0
        private static void LoadPackages(IEnumerable <string> packagePaths, Dictionary <string, PackageInfo> packages, string tempDirectoryOpt, bool release)
        {
            bool readOnly = tempDirectoryOpt == null;

            foreach (var packagePath in packagePaths)
            {
                Package package;
                string  tempPathOpt;
                if (readOnly)
                {
                    tempPathOpt = null;
                    package     = Package.Open(packagePath, FileMode.Open, FileAccess.Read);
                }
                else
                {
                    tempPathOpt = Path.Combine(tempDirectoryOpt, Guid.NewGuid().ToString());
                    File.Copy(packagePath, tempPathOpt);
                    package = Package.Open(tempPathOpt, FileMode.Open, FileAccess.ReadWrite);
                }

                string    packageId    = null;
                Stream    nuspecStream = null;
                XDocument nuspecXml    = null;

                PackageInfo packageInfo = null;
                try
                {
                    SemanticVersion packageVersion    = null;
                    SemanticVersion newPackageVersion = null;
                    string          nuspecXmlns       = DefaultNuspecXmlns;

                    foreach (var part in package.GetParts())
                    {
                        string relativePath = part.Uri.OriginalString;
                        ParsePartName(relativePath, out var fileName, out var dirName);

                        if (dirName == "/" && fileName.EndsWith(".nuspec", StringComparison.OrdinalIgnoreCase))
                        {
                            nuspecStream = part.GetStream(FileMode.Open, readOnly ? FileAccess.Read : FileAccess.ReadWrite);
                            nuspecXml    = XDocument.Load(nuspecStream);

                            if (nuspecXml.Root.HasAttributes)
                            {
                                var xmlNsAttribute = nuspecXml.Root.Attributes("xmlns").SingleOrDefault();
                                if (xmlNsAttribute != null)
                                {
                                    nuspecXmlns = xmlNsAttribute.Value;
                                }
                            }
                            var metadata = nuspecXml.Element(XName.Get("package", nuspecXmlns))?.Element(XName.Get("metadata", nuspecXmlns));
                            if (metadata == null)
                            {
                                throw new InvalidDataException($"'{packagePath}' has invalid nuspec: missing 'metadata' element");
                            }

                            packageId = metadata.Element(XName.Get("id", nuspecXmlns))?.Value;
                            if (packageId == null)
                            {
                                throw new InvalidDataException($"'{packagePath}' has invalid nuspec: missing 'id' element");
                            }

                            var    versionElement    = metadata.Element(XName.Get("version", nuspecXmlns));
                            string packageVersionStr = versionElement?.Value;
                            if (packageVersionStr == null)
                            {
                                throw new InvalidDataException($"'{packagePath}' has invalid nuspec: missing 'version' element");
                            }

                            if (!SemanticVersion.TryParse(packageVersionStr, out packageVersion))
                            {
                                throw new InvalidDataException($"'{packagePath}' has invalid nuspec: invalid 'version' value '{packageVersionStr}'");
                            }

                            if (!packageVersion.IsPrerelease)
                            {
                                throw new InvalidOperationException($"Can only update pre-release packages: '{packagePath}' has release version");
                            }

                            // To strip build number take the first part of the pre-release label (e.g. "beta1-62030-10")
                            string releaseLabel = release ? null : packageVersion.Release.Split('-').First();

                            newPackageVersion = new SemanticVersion(packageVersion.Major, packageVersion.Minor, packageVersion.Patch, releaseLabel);

                            if (!readOnly)
                            {
                                versionElement.SetValue(newPackageVersion.ToNormalizedString());
                            }

                            break;
                        }
                    }

                    if (nuspecStream == null)
                    {
                        throw new InvalidDataException($"'{packagePath}' is missing .nuspec file");
                    }

                    if (packages.ContainsKey(packageId))
                    {
                        throw new InvalidDataException($"Multiple packages of name '{packageId}' specified");
                    }

                    if (!readOnly)
                    {
                        package.PackageProperties.Version = newPackageVersion.ToNormalizedString();
                    }

                    packageInfo = new PackageInfo(package, packageId, packageVersion, newPackageVersion, tempPathOpt, nuspecStream, nuspecXml, nuspecXmlns);
                }
                finally
                {
                    if (packageInfo == null)
                    {
                        nuspecStream.Dispose();
                        package.Close();

                        if (tempPathOpt != null)
                        {
                            File.Delete(tempPathOpt);
                        }
                    }
                }

                packages.Add(packageId, packageInfo);
            }
        }
        private AppInfoModel Create(Assembly assembly)
        {
            var semVer = new SemanticVersion(assembly.GetName().Version.ToStringInvariant());

            return(new AppInfoModel(assembly.GetName().Name, semVer.ToNormalizedString()));
        }
 private string GetPackageFileName(string packageId, SemanticVersion version)
 {
     return string.Format(TemplateNupkgFilename, packageId, version.ToNormalizedString());
 }
Example #32
0
        private async Task <bool?> CheckPackageExistsAsync(
            FileInfo nugetPackage,
            string nugetExePath,
            ILogger logger,
            string sourceName)
        {
            if (!File.Exists(nugetPackage.FullName))
            {
                logger.WriteError(
                    $"The NuGet package '{nugetPackage}' does not exist");
                return(null);
            }

            logger.WriteDebug($"Searching for existing NuGet package '{nugetPackage}'");

            string packageVersion;
            string packageId;

            using (var fs = new FileStream(nugetPackage.FullName, FileMode.Open, FileAccess.Read))
            {
                using (var archive = new ZipArchive(fs))
                {
                    ZipArchiveEntry nuspecEntry =
                        archive.Entries.SingleOrDefault(
                            entry =>
                            Path.GetExtension(entry.Name)
                            .Equals(".nuspec", StringComparison.InvariantCultureIgnoreCase));

                    if (nuspecEntry == null)
                    {
                        throw new InvalidOperationException("The nuget package does not contain any nuspec");
                    }

                    var          nuspecReader = new NuspecReader(nuspecEntry.Open());
                    NuGetVersion nuGetVersion = nuspecReader.GetVersion();

                    packageVersion = nuGetVersion.ToNormalizedString();
                    packageId      = nuspecReader.GetIdentity().Id;
                }
            }

            SemanticVersion expectedVersion = SemanticVersion.Parse(packageVersion);

            var packageInfo = new { Id = packageId, Version = expectedVersion };

            var args = new List <string>
            {
                "list",
                packageId
            };

            if (!string.IsNullOrWhiteSpace(sourceName))
            {
                logger.WriteVerbose($"Using specific source name '{sourceName}'");
                args.Add("-source");
                args.Add(sourceName);
            }

            args.Add("-verbosity");
            args.Add("normal");

            if (packageInfo.Version.IsPrerelease)
            {
                logger.WriteVerbose($"Package '{nugetPackage.Name}' is pre-release");
                args.Add("-prerelease");
            }

            var errorBuilder    = new StringBuilder();
            var standardBuilder = new List <string>();

            string expectedNameAndVersion = $"{packageInfo.Id} {expectedVersion.ToNormalizedString()}";

            logger.Write($"Looking for '{expectedNameAndVersion}' package");

            ExitCode exitCode =
                await
                ProcessRunner.ExecuteAsync(
                    nugetExePath,
                    arguments : args,
                    standardOutLog :
                    (message, prefix) =>
            {
                standardBuilder.Add(message);
                logger.Write(message, prefix);
            },
                    standardErrorAction : (message, prefix) =>
            {
                errorBuilder.AppendLine(message);
                logger.WriteError(message, prefix);
            },
                    toolAction : logger.Write,
                    addProcessNameAsLogCategory : true,
                    addProcessRunnerCategory : true);

            if (!exitCode.IsSuccess)
            {
                logger.WriteError($"Could not execute process to check if package '{expectedNameAndVersion}' exists");
                return(null);
            }

            bool foundSpecificPackage = standardBuilder.Any(
                line => line.Equals(expectedNameAndVersion, StringComparison.InvariantCultureIgnoreCase));

            if (foundSpecificPackage)
            {
                logger.Write($"Found existing package id '{expectedNameAndVersion}'");
            }
            else
            {
                logger.Write($"Could not find existing package id '{expectedNameAndVersion}'");
            }

            return(foundSpecificPackage);
        }
        /// <inheritdoc/>
        public AppInfoModel Create(Type type)
        {
            var semVer = new SemanticVersion(ReflectionHelper.GetAssemblyVersion(type));

            return(new AppInfoModel(ReflectionHelper.GetAssemblyName(type), semVer.ToNormalizedString()));
        }