示例#1
0
        private async Task PostDownloadStatistics(string id, string version, string ipAddress, string userAgent, string operation, string dependentPackage, string projectGuids)
        {
            if (_config == null || _config.MetricsServiceUri == null)
            {
                return;
            }

            try
            {
                var jObject = GetJObject(id, version, ipAddress, userAgent, operation, dependentPackage, projectGuids);

                using (var httpClient = new System.Net.Http.HttpClient())
                {
                    await httpClient.PostAsync(new Uri(_config.MetricsServiceUri, MetricsDownloadEventMethod), new StringContent(jObject.ToString(), Encoding.UTF8, ContentTypeJson));
                }
            }
            catch (WebException ex)
            {
                QuietLog.LogHandledException(ex);
            }
            catch (AggregateException ex)
            {
                QuietLog.LogHandledException(ex.InnerException ?? ex);
            }
        }
        public async Task <StatisticsReportResult> LoadNuGetClientVersion()
        {
            try
            {
                var reportName    = (StatisticsReportName.NuGetClientVersion + ".json").ToLowerInvariant();
                var reportContent = await _reportService.Load(reportName);

                if (reportContent == null)
                {
                    return(StatisticsReportResult.Failed);
                }

                var array = JArray.Parse(reportContent.Content);
                var statisticsNuGetUsageItems = (List <StatisticsNuGetUsageItem>)NuGetClientVersion;
                statisticsNuGetUsageItems.Clear();

                foreach (JObject item in array)
                {
                    statisticsNuGetUsageItems.Add(
                        new StatisticsNuGetUsageItem
                    {
                        Version   = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", item["Major"], item["Minor"]),
                        Downloads = (int)item["Downloads"]
                    });
                }

                return(StatisticsReportResult.Success(reportContent.LastUpdatedUtc));
            }
            catch (Exception e)
            {
                QuietLog.LogHandledException(e);
                return(StatisticsReportResult.Failed);
            }
        }
 private void SendMessage(MailMessage mailMessage, bool copySender = false)
 {
     try
     {
         MailSender.Send(mailMessage);
         if (copySender)
         {
             var senderCopy = new MailMessage(
                 Config.GalleryOwner,
                 mailMessage.ReplyToList.First())
             {
                 Subject = mailMessage.Subject + " [Sender Copy]",
                 Body    = String.Format(
                     CultureInfo.CurrentCulture,
                     "You sent the following message via {0}: {1}{1}{2}",
                     Config.GalleryOwner.DisplayName,
                     Environment.NewLine,
                     mailMessage.Body),
             };
             senderCopy.ReplyToList.Add(mailMessage.ReplyToList.First());
             MailSender.Send(senderCopy);
         }
     }
     catch (SmtpException ex)
     {
         // Log but swallow the exception
         QuietLog.LogHandledException(ex);
     }
 }
示例#4
0
        private async Task PostDownloadStatistics(string id, string version, string ipAddress, string userAgent, string operation, string dependentPackage, string projectGuids, CancellationToken cancellationToken)
        {
            if (_config == null || _config.MetricsServiceUri == null || cancellationToken.IsCancellationRequested)
            {
                return;
            }

            try
            {
                var jObject = GetJObject(id, version, ipAddress, userAgent, operation, dependentPackage, projectGuids);

                await HttpClient.PostAsync(new Uri(_config.MetricsServiceUri, MetricsDownloadEventMethod), new StringContent(jObject.ToString(), Encoding.UTF8, ContentTypeJson), cancellationToken);
            }
            catch (WebException ex)
            {
                QuietLog.LogHandledException(ex);
            }
            catch (AggregateException ex)
            {
                QuietLog.LogHandledException(ex.InnerException ?? ex);
            }
            catch (TaskCanceledException)
            {
                // noop
            }
        }
示例#5
0
        public DependencySetsViewModel(IEnumerable <PackageDependency> packageDependencies)
        {
            try
            {
                DependencySets = new Dictionary <string, IEnumerable <DependencyViewModel> >();

                var dependencySets = packageDependencies
                                     .GroupBy(d => d.TargetFramework)
                                     .OrderBy(ds => ds.Key);

                OnlyHasAllFrameworks = dependencySets.Count() == 1 && dependencySets.First().Key == null;

                foreach (var dependencySet in dependencySets)
                {
                    var targetFramework = dependencySet.Key == null
                                              ? "All Frameworks"
                                              : NuGetFramework.Parse(dependencySet.Key).ToFriendlyName();

                    if (!DependencySets.ContainsKey(targetFramework))
                    {
                        DependencySets.Add(targetFramework,
                                           dependencySet.Select(d => d.Id == null ? null : new DependencyViewModel(d.Id, d.VersionSpec)));
                    }
                }
            }
            catch (Exception e)
            {
                DependencySets = null;
                QuietLog.LogHandledException(e);
                // Just set Dependency Sets to null but still render the package.
            }
        }
        public async Task <StatisticsReportResult> LoadLast6Weeks()
        {
            try
            {
                var reportName    = (StatisticsReportName.Last6Weeks + ".json").ToLowerInvariant();
                var reportContent = await _reportService.Load(reportName);

                if (reportContent == null)
                {
                    return(StatisticsReportResult.Failed);
                }

                var array = JArray.Parse(reportContent.Content);
                var statisticsMonthlyUsageItems = (List <StatisticsWeeklyUsageItem>)Last6Weeks;
                statisticsMonthlyUsageItems.Clear();

                foreach (JObject item in array)
                {
                    statisticsMonthlyUsageItems.Add(
                        new StatisticsWeeklyUsageItem
                    {
                        Year       = (int)item["Year"],
                        WeekOfYear = (int)item["WeekOfYear"],
                        Downloads  = (int)item["Downloads"]
                    });
                }

                return(StatisticsReportResult.Success(reportContent.LastUpdatedUtc));
            }
            catch (Exception e)
            {
                QuietLog.LogHandledException(e);
                return(StatisticsReportResult.Failed);
            }
        }
        public LuceneIndexingJob(TimeSpan frequence, Func <EntitiesContext> contextThunk, TimeSpan timeout, LuceneIndexLocation location)
            : base("Lucene", frequence, timeout)
        {
            _updateIndex = () =>
            {
                using (var context = contextThunk())
                {
                    var indexingService = new LuceneIndexingService(
                        new EntityRepository <Package>(context),
                        new EntityRepository <CuratedPackageVersion>(context),
                        LuceneCommon.GetDirectory(location),
                        null);
                    indexingService.UpdateIndex();
                }
            };

            // Updates the index synchronously first time job is created.
            // For startup code resiliency, we should handle exceptions for the database being down.
            try
            {
                _updateIndex();
            }
            catch (SqlException e)
            {
                QuietLog.LogHandledException(e);
            }
            catch (DataException e)
            {
                QuietLog.LogHandledException(e);
            }
        }
        private async Task <bool?> IsAzureStorageAvailable()
        {
            if (_config == null || _config.StorageType != StorageType.AzureStorage)
            {
                return(null);
            }

            bool storageAvailable = false;

            try
            {
                // Check Storage Availability
                var tasks         = _cloudStorageAvailabilityChecks.Select(s => s.IsAvailableAsync());
                var eachAvailable = await Task.WhenAll(tasks);

                storageAvailable = eachAvailable.All(a => a);
            }
            catch (Exception ex)
            {
                // Could catch Azure's StorageException alone. But, the status page is not supposed to throw at any cost
                // And, catching StorageException will compromise the IFileStorageService abstraction

                QuietLog.LogHandledException(ex);
            }

            return(storageAvailable);
        }
示例#9
0
        public async Task <StatisticsReportResult> LoadNuGetClientVersion()
        {
            try
            {
                var reportContent = await _reportService.Load(Reports.NuGetClientVersion.ToString() + ".json");

                if (reportContent == null)
                {
                    return(StatisticsReportResult.Failed);
                }

                JArray array = JArray.Parse(reportContent.Content);

                ((List <StatisticsNuGetUsageItem>)NuGetClientVersion).Clear();

                foreach (JObject item in array)
                {
                    ((List <StatisticsNuGetUsageItem>)NuGetClientVersion).Add(
                        new StatisticsNuGetUsageItem
                    {
                        Version   = string.Format("{0}.{1}", item["ClientMajorVersion"], item["ClientMinorVersion"]),
                        Downloads = (int)item["Downloads"]
                    });
                }

                return(StatisticsReportResult.Success(reportContent.LastUpdatedUtc));
            }
            catch (Exception e)
            {
                QuietLog.LogHandledException(e);
                return(StatisticsReportResult.Failed);
            }
        }
示例#10
0
        public async Task <StatisticsReportResult> LoadLast6Months()
        {
            try
            {
                var reportContent = await _reportService.Load(Reports.Last6Months.ToString() + ".json");

                if (reportContent == null)
                {
                    return(StatisticsReportResult.Failed);
                }

                JArray array = JArray.Parse(reportContent.Content);

                ((List <StatisticsMonthlyUsageItem>)Last6Months).Clear();

                foreach (JObject item in array)
                {
                    ((List <StatisticsMonthlyUsageItem>)Last6Months).Add(
                        new StatisticsMonthlyUsageItem
                    {
                        Year        = (int)item["Year"],
                        MonthOfYear = (int)item["MonthOfYear"],
                        Downloads   = (int)item["Downloads"]
                    });
                }

                return(StatisticsReportResult.Success(reportContent.LastUpdatedUtc));
            }
            catch (Exception e)
            {
                QuietLog.LogHandledException(e);
                return(StatisticsReportResult.Failed);
            }
        }
示例#11
0
        public virtual async Task <ActionResult> GetPackage(string id, string version)
        {
            // some security paranoia about URL hacking somehow creating e.g. open redirects
            // validate user input: explicit calls to the same validators used during Package Registrations
            // Ideally shouldn't be necessary?
            if (!PackageIdValidator.IsValidPackageId(id ?? ""))
            {
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, "The format of the package id is invalid"));
            }

            // if version is non-null, check if it's semantically correct and normalize it.
            if (!String.IsNullOrEmpty(version))
            {
                NuGetVersion dummy;
                if (!NuGetVersion.TryParse(version, out dummy))
                {
                    return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, "The package version is not a valid semantic version"));
                }

                // Normalize the version
                version = NuGetVersionNormalizer.Normalize(version);
            }
            else
            {
                // if version is null, get the latest version from the database.
                // This ensures that on package restore scenario where version will be non null, we don't hit the database.
                try
                {
                    var package = PackageService.FindPackageByIdAndVersion(id, version, allowPrerelease: false);
                    if (package == null)
                    {
                        return(new HttpStatusCodeWithBodyResult(HttpStatusCode.NotFound, String.Format(CultureInfo.CurrentCulture, Strings.PackageWithIdAndVersionNotFound, id, version)));
                    }
                    version = package.NormalizedVersion;
                }
                catch (SqlException e)
                {
                    QuietLog.LogHandledException(e);

                    // Database was unavailable and we don't have a version, return a 503
                    return(new HttpStatusCodeWithBodyResult(HttpStatusCode.ServiceUnavailable, Strings.DatabaseUnavailable_TrySpecificVersion));
                }
                catch (DataException e)
                {
                    QuietLog.LogHandledException(e);

                    // Database was unavailable and we don't have a version, return a 503
                    return(new HttpStatusCodeWithBodyResult(HttpStatusCode.ServiceUnavailable, Strings.DatabaseUnavailable_TrySpecificVersion));
                }
            }

            if (ConfigurationService.Features.TrackPackageDownloadCountInLocalDatabase)
            {
                await PackageService.IncrementDownloadCountAsync(id, version);
            }

            return(await PackageFileService.CreateDownloadPackageActionResultAsync(
                       HttpContext.Request.Url,
                       id, version));
        }
示例#12
0
        internal async Task <bool?> IsAzureStorageAvailable()
        {
            if (_config == null || _config.StorageType != StorageType.AzureStorage)
            {
                return(null);
            }

            bool storageAvailable = false;

            try
            {
                // Check Storage Availability
                BlobRequestOptions options = new BlobRequestOptions();
                // Used the LocationMode.SecondaryOnly and not PrimaryThenSecondary for two reasons:
                // 1. When the primary is down and secondary is up if PrimaryThenSecondary is used there will be an extra and not needed call to the primary.
                // 2. When the primary is up the secondary status check will return the primary status instead of secondary.
                options.LocationMode = _config.ReadOnlyMode ? LocationMode.SecondaryOnly : LocationMode.PrimaryOnly;
                var tasks         = _cloudStorageAvailabilityChecks.Select(s => s.IsAvailableAsync(options, operationContext: null));
                var eachAvailable = await Task.WhenAll(tasks);

                storageAvailable = eachAvailable.All(a => a);
            }
            catch (Exception ex)
            {
                // Could catch Azure's StorageException alone. But, the status page is not supposed to throw at any cost
                // And, catching StorageException will compromise the IFileStorageService abstraction

                QuietLog.LogHandledException(ex);
            }

            return(storageAvailable);
        }
示例#13
0
        public async Task <bool> LoadDownloadPackageVersions()
        {
            try
            {
                string json = await _reportService.Load(Reports.RecentPopularityDetail.ToString() + ".json");

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

                JArray array = JArray.Parse(json);

                ((List <StatisticsPackagesItemViewModel>)DownloadPackageVersionsAll).Clear();

                foreach (JObject item in array)
                {
                    ((List <StatisticsPackagesItemViewModel>)DownloadPackageVersionsAll).Add(new StatisticsPackagesItemViewModel
                    {
                        PackageId          = item["PackageId"].ToString(),
                        PackageVersion     = item["PackageVersion"].ToString(),
                        Downloads          = item["Downloads"].Value <int>(),
                        PackageTitle       = GetOptionalProperty("PackageTitle", item),
                        PackageDescription = GetOptionalProperty("PackageDescription", item),
                        PackageIconUrl     = GetOptionalProperty("PackageIconUrl", item)
                    });
                }

                int count = ((List <StatisticsPackagesItemViewModel>)DownloadPackageVersionsAll).Count;

                ((List <StatisticsPackagesItemViewModel>)DownloadPackageVersionsSummary).Clear();

                for (int i = 0; i < Math.Min(10, count); i++)
                {
                    ((List <StatisticsPackagesItemViewModel>)DownloadPackageVersionsSummary).Add(((List <StatisticsPackagesItemViewModel>)DownloadPackageVersionsAll)[i]);
                }

                return(true);
            }
            catch (NullReferenceException e)
            {
                QuietLog.LogHandledException(e);
                return(false);
            }
            catch (JsonReaderException e)
            {
                QuietLog.LogHandledException(e);
                return(false);
            }
            catch (StorageException e)
            {
                QuietLog.LogHandledException(e);
                return(false);
            }
            catch (ArgumentException e)
            {
                QuietLog.LogHandledException(e);
                return(false);
            }
        }
示例#14
0
        public async Task <StatisticsPackagesReport> GetPackageVersionDownloadsByClient(string packageId, string packageVersion)
        {
            try
            {
                if (string.IsNullOrEmpty(packageId) || string.IsNullOrEmpty(packageVersion))
                {
                    return(null);
                }

                string reportName = string.Format(CultureInfo.CurrentCulture, "{0}{1}.json", Reports.RecentPopularityDetail_, packageId);

                reportName = reportName.ToLowerInvariant();

                string json = await _reportService.Load(reportName);

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

                JObject content = JObject.Parse(json);

                StatisticsPackagesReport report = new StatisticsPackagesReport();

                IList <StatisticsFact> facts = new List <StatisticsFact>();

                foreach (StatisticsFact fact in CreateFacts(content))
                {
                    if (fact.Dimensions["Version"] == packageVersion)
                    {
                        facts.Add(fact);
                    }
                }

                report.Facts = facts;

                return(report);
            }
            catch (NullReferenceException e)
            {
                QuietLog.LogHandledException(e);
                return(null);
            }
            catch (JsonReaderException e)
            {
                QuietLog.LogHandledException(e);
                return(null);
            }
            catch (StorageException e)
            {
                QuietLog.LogHandledException(e);
                return(null);
            }
            catch (ArgumentException e)
            {
                QuietLog.LogHandledException(e);
                return(null);
            }
        }
        public async Task <StatisticsPackagesReport> GetPackageDownloadsByVersion(string packageId)
        {
            try
            {
                if (string.IsNullOrEmpty(packageId))
                {
                    return(null);
                }

                string reportName = string.Format(CultureInfo.CurrentCulture, "{0}{1}.json", Reports.RecentPopularityDetail_, packageId);

                reportName = reportName.ToLowerInvariant();

                var reportContent = await _reportService.Load(reportName);

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

                JObject content = JObject.Parse(reportContent.Content);

                StatisticsPackagesReport report = new StatisticsPackagesReport()
                {
                    LastUpdatedUtc = reportContent.LastUpdatedUtc
                };

                report.Facts = CreateFacts(content);

                return(report);
            }
            catch (StatisticsReportNotFoundException)
            {
                //do no logging and just return null. Since this exception will thrown for all packages which doesn't have downloads in last 6 weeks, we don't
                //want to flood the elmah logs.
                return(null);
            }
            catch (NullReferenceException e)
            {
                QuietLog.LogHandledException(e);
                return(null);
            }
            catch (JsonReaderException e)
            {
                QuietLog.LogHandledException(e);
                return(null);
            }
            catch (StorageException e)
            {
                QuietLog.LogHandledException(e);
                return(null);
            }
            catch (ArgumentException e)
            {
                QuietLog.LogHandledException(e);
                return(null);
            }
        }
        public async Task <StatisticsPackagesReport> GetPackageVersionDownloadsByClient(string packageId, string packageVersion)
        {
            try
            {
                if (string.IsNullOrEmpty(packageId) || string.IsNullOrEmpty(packageVersion))
                {
                    return(null);
                }

                var reportName = string.Format(CultureInfo.CurrentCulture, RecentpopularityDetailBlobNameFormat,
                                               StatisticsReportName.RecentPopularityDetail_, packageId).ToLowerInvariant();
                var reportContent = await _reportService.Load(reportName);

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

                var content = JObject.Parse(reportContent.Content);
                var report  = new StatisticsPackagesReport
                {
                    LastUpdatedUtc = reportContent.LastUpdatedUtc
                };

                var facts = new List <StatisticsFact>();
                foreach (var fact in CreateFacts(content))
                {
                    if (fact.Dimensions["Version"] == packageVersion)
                    {
                        facts.Add(fact);
                    }
                }

                report.Facts = facts;

                return(report);
            }
            catch (NullReferenceException e)
            {
                QuietLog.LogHandledException(e);
                return(null);
            }
            catch (JsonReaderException e)
            {
                QuietLog.LogHandledException(e);
                return(null);
            }
            catch (StorageException e)
            {
                QuietLog.LogHandledException(e);
                return(null);
            }
            catch (ArgumentException e)
            {
                QuietLog.LogHandledException(e);
                return(null);
            }
        }
        private async Task <DeleteUserAccountStatus> RunAccountDeletionTask(Func <Task> getTask, User userToBeDeleted, User requestingUser, bool commitAsTransaction)
        {
            try
            {
                // The support requests DB and gallery DB are different.
                // TransactionScope can be used for doing transaction actions across db on the same server but not on different servers.
                // The below code will clean the feature flags and suppport requests before the gallery data.
                // The order is important in order to allow the admin the opportunity to execute this step again.
                await _featureFlagService.RemoveUserAsync(userToBeDeleted);
                await RemoveSupportRequests(userToBeDeleted);

                if (commitAsTransaction)
                {
                    using (var strategy = new SuspendDbExecutionStrategy())
                        using (var transaction = _entitiesContext.GetDatabase().BeginTransaction())
                        {
                            await getTask();

                            transaction.Commit();
                        }
                }
                else
                {
                    await getTask();
                }

                await _auditingService.SaveAuditRecordAsync(new DeleteAccountAuditRecord(username : userToBeDeleted.Username,
                                                                                         status : DeleteAccountAuditRecord.ActionStatus.Success,
                                                                                         action : AuditedDeleteAccountAction.DeleteAccount,
                                                                                         adminUsername : requestingUser.Username));

                return(new DeleteUserAccountStatus()
                {
                    Success = true,
                    Description = string.Format(CultureInfo.CurrentCulture,
                                                Strings.AccountDelete_Success,
                                                userToBeDeleted.Username),
                    AccountName = userToBeDeleted.Username
                });
            }
            catch (Exception e)
            {
                QuietLog.LogHandledException(e);
                return(new DeleteUserAccountStatus()
                {
                    Success = false,
                    Description = string.Format(CultureInfo.CurrentCulture,
                                                Strings.AccountDelete_Fail,
                                                userToBeDeleted.Username, e),
                    AccountName = userToBeDeleted.Username
                });
            }
        }
示例#18
0
        /// <summary>
        /// Will clean-up the data related with an user account.
        /// The result will be:
        /// 1. The user will be removed as owner from its owned packages.
        /// 2. Any of the packages that become orphaned as its result will be unlisted if the unlistOrphanPackages is set to true.
        /// 3. Any owned namespaces will be released.
        /// 4. The user credentials will be cleaned.
        /// 5. The user data will be cleaned.
        /// </summary>
        /// <param name="userToBeDeleted">The user to be deleted.</param>
        /// <param name="admin">The admin that will perform the delete action.</param>
        /// <param name="signature">The admin signature.</param>
        /// <param name="unlistOrphanPackages">If the orphaned packages will unlisted.</param>
        /// <param name="commitAsTransaction">If the data will be persisted as a transaction.</param>
        /// <returns></returns>
        public async Task <DeleteUserAccountStatus> DeleteGalleryUserAccountAsync(User userToBeDeleted, User admin, string signature, bool unlistOrphanPackages, bool commitAsTransaction)
        {
            if (userToBeDeleted == null)
            {
                throw new ArgumentNullException(nameof(userToBeDeleted));
            }
            if (admin == null)
            {
                throw new ArgumentNullException(nameof(admin));
            }
            if (userToBeDeleted.IsDeleted)
            {
                return(new DeleteUserAccountStatus()
                {
                    Success = false,
                    Description = string.Format(Strings.AccountDelete_AccountAlreadyDeleted, userToBeDeleted.Username),
                    AccountName = userToBeDeleted.Username
                });
            }
            try
            {
                if (commitAsTransaction)
                {
                    using (var strategy = new SuspendDbExecutionStrategy())
                        using (var transaction = _entitiesContext.GetDatabase().BeginTransaction())
                        {
                            await DeleteGalleryUserAccountImplAsync(userToBeDeleted, admin, signature, unlistOrphanPackages);

                            transaction.Commit();
                        }
                }
                else
                {
                    await DeleteGalleryUserAccountImplAsync(userToBeDeleted, admin, signature, unlistOrphanPackages);
                }
                return(new DeleteUserAccountStatus()
                {
                    Success = true,
                    Description = string.Format(Strings.AccountDelete_Success, userToBeDeleted.Username),
                    AccountName = userToBeDeleted.Username
                });
            }
            catch (Exception e)
            {
                QuietLog.LogHandledException(e);
                return(new DeleteUserAccountStatus()
                {
                    Success = true,
                    Description = string.Format(Strings.AccountDelete_Fail, userToBeDeleted.Username, e),
                    AccountName = userToBeDeleted.Username
                });
            }
        }
        public virtual async Task <ActionResult> VerifyPackage()
        {
            var currentUser = GetCurrentUser();

            IPackageMetadata packageMetadata;

            using (Stream uploadFile = await _uploadFileService.GetUploadFileAsync(currentUser.Key))
            {
                if (uploadFile == null)
                {
                    return(RedirectToRoute(RouteName.UploadPackage));
                }

                try
                {
                    using (INupkg package = CreatePackage(uploadFile))
                    {
                        packageMetadata = package.Metadata;
                    }
                }
                catch (InvalidDataException e)
                {
                    // Log the exception in case we get support requests about it.
                    QuietLog.LogHandledException(e);

                    return(View("UnverifiablePackage"));
                }
            }

            var model = new VerifyPackageRequest
            {
                Id         = packageMetadata.Id,
                Version    = packageMetadata.Version.ToNormalizedStringSafe(),
                LicenseUrl = packageMetadata.LicenseUrl.ToEncodedUrlStringOrNull(),
                Listed     = true,
                Edit       = new EditPackageVersionRequest
                {
                    Authors      = packageMetadata.Authors.Flatten(),
                    Copyright    = packageMetadata.Copyright,
                    Description  = packageMetadata.Description,
                    IconUrl      = packageMetadata.IconUrl.ToEncodedUrlStringOrNull(),
                    LicenseUrl   = packageMetadata.LicenseUrl.ToEncodedUrlStringOrNull(),
                    ProjectUrl   = packageMetadata.ProjectUrl.ToEncodedUrlStringOrNull(),
                    ReleaseNotes = packageMetadata.ReleaseNotes,
                    RequiresLicenseAcceptance = packageMetadata.RequireLicenseAcceptance,
                    Summary      = packageMetadata.Summary,
                    Tags         = PackageHelper.ParseTags(packageMetadata.Tags),
                    VersionTitle = packageMetadata.Title,
                }
            };

            return(View(model));
        }
示例#20
0
        public async Task <StatisticsPackagesReport> GetPackageDownloadsByVersion(string packageId)
        {
            try
            {
                if (string.IsNullOrEmpty(packageId))
                {
                    return(null);
                }

                string reportName = string.Format(CultureInfo.CurrentCulture, "{0}{1}.json", Reports.RecentPopularityDetail_, packageId);

                reportName = reportName.ToLowerInvariant();

                var reportContent = await _reportService.Load(reportName);

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

                JObject content = JObject.Parse(reportContent.Content);

                StatisticsPackagesReport report = new StatisticsPackagesReport()
                {
                    LastUpdatedUtc = reportContent.LastUpdatedUtc
                };

                report.Facts = CreateFacts(content);

                return(report);
            }
            catch (NullReferenceException e)
            {
                QuietLog.LogHandledException(e);
                return(null);
            }
            catch (JsonReaderException e)
            {
                QuietLog.LogHandledException(e);
                return(null);
            }
            catch (StorageException e)
            {
                QuietLog.LogHandledException(e);
                return(null);
            }
            catch (ArgumentException e)
            {
                QuietLog.LogHandledException(e);
                return(null);
            }
        }
示例#21
0
        public static void Log(this Exception self)
        {
            IUserSafeException uvex = self as IUserSafeException;

            if (uvex != null)
            {
                // Log the exception that the User-Visible wrapper marked as to-be-logged
                QuietLog.LogHandledException(uvex.LoggedException);
            }
            else
            {
                QuietLog.LogHandledException(self);
            }
        }
        public void LogDecreaseHealth(Uri endpoint, int health, Exception exception)
        {
            var telemetryClient = new TelemetryClient();

            telemetryClient.TrackEvent("Endpoint Health Changed",
                                       new Dictionary <string, string>()
            {
                { "Endpoint", endpoint.ToString() },
                { "Event", "Decrease" }
            }, new Dictionary <string, double>()
            {
                { "Endpoint Health", health }
            });

            QuietLog.LogHandledException(exception);
        }
示例#23
0
 protected override void SendMessage(MailMessage mailMessage, bool copySender)
 {
     try
     {
         base.SendMessage(mailMessage, copySender);
     }
     catch (InvalidOperationException ex)
     {
         // Log but swallow the exception
         QuietLog.LogHandledException(ex);
     }
     catch (SmtpException ex)
     {
         // Log but swallow the exception
         QuietLog.LogHandledException(ex);
     }
 }
示例#24
0
        public virtual async Task <ActionResult> VerifyPackage()
        {
            var currentUser = _userService.FindByUsername(GetIdentity().Name);

            IPackageMetadata packageMetadata;

            using (Stream uploadFile = await _uploadFileService.GetUploadFileAsync(currentUser.Key))
            {
                if (uploadFile == null)
                {
                    return(RedirectToRoute(RouteName.UploadPackage));
                }

                try
                {
                    using (INupkg package = CreatePackage(uploadFile))
                    {
                        packageMetadata = package.Metadata;
                    }
                }
                catch (InvalidDataException e)
                {
                    // Log the exception in case we get support requests about it.
                    QuietLog.LogHandledException(e);

                    return(View(Views.UnverifiablePackage));
                }
            }

            return(View(
                       new VerifyPackageViewModel
            {
                Id = packageMetadata.Id,
                Version = packageMetadata.Version.ToStringSafe(),
                Title = packageMetadata.Title,
                Summary = packageMetadata.Summary,
                Description = packageMetadata.Description,
                RequiresLicenseAcceptance = packageMetadata.RequireLicenseAcceptance,
                LicenseUrl = packageMetadata.LicenseUrl.ToStringSafe(),
                Tags = PackageHelper.ParseTags(packageMetadata.Tags),
                ProjectUrl = packageMetadata.ProjectUrl.ToStringSafe(),
                Authors = packageMetadata.Authors.Flatten(),
                Listed = true
            }));
        }
示例#25
0
        public async Task <StatisticsReportResult> LoadDownloadPackageVersions()
        {
            try
            {
                var reportContent = await _reportService.Load(Reports.RecentPopularityDetail.ToString() + ".json");

                if (reportContent == null)
                {
                    return(StatisticsReportResult.Failed);
                }

                JArray array = JArray.Parse(reportContent.Content);

                ((List <StatisticsPackagesItemViewModel>)DownloadPackageVersionsAll).Clear();

                foreach (JObject item in array)
                {
                    ((List <StatisticsPackagesItemViewModel>)DownloadPackageVersionsAll).Add(new StatisticsPackagesItemViewModel
                    {
                        PackageId          = item["PackageId"].ToString(),
                        PackageVersion     = item["PackageVersion"].ToString(),
                        Downloads          = item["Downloads"].Value <int>(),
                        PackageTitle       = GetOptionalProperty("PackageTitle", item),
                        PackageDescription = GetOptionalProperty("PackageDescription", item),
                        PackageIconUrl     = GetOptionalProperty("PackageIconUrl", item)
                    });
                }

                int count = ((List <StatisticsPackagesItemViewModel>)DownloadPackageVersionsAll).Count;

                ((List <StatisticsPackagesItemViewModel>)DownloadPackageVersionsSummary).Clear();

                for (int i = 0; i < Math.Min(10, count); i++)
                {
                    ((List <StatisticsPackagesItemViewModel>)DownloadPackageVersionsSummary).Add(((List <StatisticsPackagesItemViewModel>)DownloadPackageVersionsAll)[i]);
                }

                return(StatisticsReportResult.Success(reportContent.LastUpdatedUtc));
            }
            catch (Exception e)
            {
                QuietLog.LogHandledException(e);
                return(StatisticsReportResult.Failed);
            }
        }
示例#26
0
        public async Task <bool> LoadLast6Months()
        {
            try
            {
                string json = await _reportService.Load(Reports.Last6Months.ToString() + ".json");

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

                JArray array = JArray.Parse(json);

                ((List <StatisticsMonthlyUsageItem>)Last6Months).Clear();

                foreach (JObject item in array)
                {
                    ((List <StatisticsMonthlyUsageItem>)Last6Months).Add(
                        new StatisticsMonthlyUsageItem
                    {
                        Year        = (int)item["Year"],
                        MonthOfYear = (int)item["MonthOfYear"],
                        Downloads   = (int)item["Downloads"]
                    });
                }

                return(true);
            }
            catch (JsonReaderException e)
            {
                QuietLog.LogHandledException(e);
                return(false);
            }
            catch (StorageException e)
            {
                QuietLog.LogHandledException(e);
                return(false);
            }
            catch (ArgumentException e)
            {
                QuietLog.LogHandledException(e);
                return(false);
            }
        }
示例#27
0
        private static ApplicationVersion LoadVersion()
        {
            try
            {
                var metadata = typeof(ApplicationVersionHelper)
                               .Assembly
                               .GetCustomAttributes <AssemblyMetadataAttribute>()
                               .ToDictionary(a => a.Key, a => a.Value, StringComparer.OrdinalIgnoreCase);
                var infoVer = typeof(ApplicationVersionHelper)
                              .Assembly
                              .GetCustomAttribute <AssemblyInformationalVersionAttribute>();
                string ver = infoVer == null ?
                             typeof(ApplicationVersionHelper).Assembly.GetName().Version.ToString() :
                             infoVer.InformationalVersion;

                string branch        = TryGet(metadata, "Branch");
                string commit        = TryGet(metadata, "CommitId");
                string dateString    = TryGet(metadata, "BuildDateUtc");
                string repoUriString = TryGet(metadata, "RepositoryUrl");

                DateTime buildDate;
                if (!DateTime.TryParse(dateString, out buildDate))
                {
                    buildDate = DateTime.MinValue;
                }
                Uri repoUri;
                if (!Uri.TryCreate(repoUriString, UriKind.Absolute, out repoUri))
                {
                    repoUri = null;
                }
                return(new ApplicationVersion(
                           repoUri,
                           new SemanticVersion(ver),
                           branch,
                           commit,
                           buildDate));
            }
            catch (Exception ex)
            {
                QuietLog.LogHandledException(ex);
                return(ApplicationVersion.Empty);
            }
        }
        public async Task <StatisticsReportResult> LoadDownloadPackageVersions()
        {
            try
            {
                var reportName    = (StatisticsReportName.RecentPopularityDetail + ".json").ToLowerInvariant();
                var reportContent = await _reportService.Load(reportName);

                if (reportContent == null)
                {
                    return(StatisticsReportResult.Failed);
                }

                var array = JArray.Parse(reportContent.Content);
                var statisticsPackagesItemViewModels = (List <StatisticsPackagesItemViewModel>)DownloadPackageVersionsAll;
                statisticsPackagesItemViewModels.Clear();

                foreach (JObject item in array)
                {
                    statisticsPackagesItemViewModels.Add(new StatisticsPackagesItemViewModel
                    {
                        PackageId      = item["PackageId"].ToString(),
                        PackageVersion = item["PackageVersion"].ToString(),
                        Downloads      = item["Downloads"].Value <int>(),
                    });
                }

                var count = statisticsPackagesItemViewModels.Count;
                var downloadPackageVersionsSummary = (List <StatisticsPackagesItemViewModel>)DownloadPackageVersionsSummary;
                downloadPackageVersionsSummary.Clear();

                for (var i = 0; i < Math.Min(10, count); i++)
                {
                    downloadPackageVersionsSummary.Add(statisticsPackagesItemViewModels[i]);
                }

                return(StatisticsReportResult.Success(reportContent.LastUpdatedUtc));
            }
            catch (Exception e)
            {
                QuietLog.LogHandledException(e);
                return(StatisticsReportResult.Failed);
            }
        }
示例#29
0
        public async Task <bool> LoadNuGetClientVersion()
        {
            try
            {
                string json = await _reportService.Load(Reports.NuGetClientVersion.ToString() + ".json");

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

                JArray array = JArray.Parse(json);

                ((List <StatisticsNuGetUsageItem>)NuGetClientVersion).Clear();

                foreach (JObject item in array)
                {
                    ((List <StatisticsNuGetUsageItem>)NuGetClientVersion).Add(
                        new StatisticsNuGetUsageItem
                    {
                        Version   = string.Format("{0}.{1}", item["ClientMajorVersion"], item["ClientMinorVersion"]),
                        Downloads = (int)item["Downloads"]
                    });
                }

                return(true);
            }
            catch (JsonReaderException e)
            {
                QuietLog.LogHandledException(e);
                return(false);
            }
            catch (StorageException e)
            {
                QuietLog.LogHandledException(e);
                return(false);
            }
            catch (ArgumentException e)
            {
                QuietLog.LogHandledException(e);
                return(false);
            }
        }
        public LuceneIndexingJob(TimeSpan frequence, TimeSpan timeout, LuceneIndexingService indexingService)
            : base("Lucene", frequence, timeout)
        {
            _indexingService = indexingService;

            // Updates the index synchronously first time job is created.
            // For startup code resiliency, we should handle exceptions for the database being down.
            try
            {
                _indexingService.UpdateIndex();
            }
            catch (SqlException e)
            {
                QuietLog.LogHandledException(e);
            }
            catch (DataException e)
            {
                QuietLog.LogHandledException(e);
            }
        }