Наследование: DbContext, IWorkItemsContext, IEntitiesContext
        public static List<Package> GetEditedPackagesSince(string sqlConnectionString, int highestPackageKey, DateTime lastEditsIndexTime, TextWriter log = null, bool verbose = false)
        {
            log = log ?? DefaultTraceWriter;

            EntitiesContext context = new EntitiesContext(sqlConnectionString, readOnly: true);
            IEntityRepository<Package> packageRepository = new EntityRepository<Package>(context);

            IQueryable<Package> set = packageRepository.GetAll();

            //  older edits can be reapplied so duplicates don't matter
            TimeSpan delta = TimeSpan.FromMinutes(2);
            DateTime startOfWindow = DateTime.MinValue;
            if (lastEditsIndexTime > DateTime.MinValue + delta)
            {
                startOfWindow = lastEditsIndexTime - delta;
            }

            //  we want to make sure we only apply edits for packages that we actually have in the index - to avoid a publish thread overwriting
            set = set.Where(p => p.LastEdited > startOfWindow && p.Key <= highestPackageKey);
            set = set.OrderBy(p => p.LastEdited);

            set = set
                .Include(p => p.PackageRegistration)
                .Include(p => p.PackageRegistration.Owners)
                .Include(p => p.SupportedFrameworks)
                .Include(p => p.Dependencies);

            return ExecuteQuery(set, log, verbose);
        }
        public AggregateStats GetAggregateStats()
        {
            using (var dbContext = new EntitiesContext())
            {
                var database = dbContext.Database;
                using (var command = database.Connection.CreateCommand())
                {
                    command.CommandText = @"Select
                    (Select Count([Key]) from PackageRegistrations) as UniquePackages,
                    (Select Count([Key]) from Packages where Listed = 1) as TotalPackages,
                    (
                        (Select Sum(DownloadCount) from Packages) +
                        (Select Count([Key]) from PackageStatistics where [Key] >
                            (Select DownloadStatsLastAggregatedId FROM GallerySettings)
                        )
                    ) as DownloadCount";

                    database.Connection.Open();
                    using (var reader = command.ExecuteReader(CommandBehavior.CloseConnection | CommandBehavior.SingleRow))
                    {
                        bool hasData = reader.Read();
                        if (!hasData)
                            return new AggregateStats();
                        return new AggregateStats
                        {
                            UniquePackages = reader.IsDBNull(0) ? 0 : reader.GetInt32(0),
                            TotalPackages = reader.IsDBNull(1) ? 0 : reader.GetInt32(1),
                            Downloads = reader.IsDBNull(2) ? 0 : reader.GetInt32(2),
                        };
                    }
                }
            }
        }
        public AggregateStats GetAggregateStats()
        {
            return Cache.Get("aggregatestats",
                    DateTime.UtcNow.AddMinutes(5),
                    () =>
                    {
                        using (var dbContext = new EntitiesContext())
                        {
                            var database = dbContext.Database;
                            using (var command = database.Connection.CreateCommand())
                            {
                                command.CommandText = @"Select 
                    (Select Count([Key]) from PackageRegistrations pr 
                            where exists (Select 1 from Packages p where p.PackageRegistrationKey = pr.[Key] and p.Listed = 1)) as UniquePackages,
                    (Select Count([Key]) from Packages where Listed = 1) as TotalPackages,
                    (Select Sum(DownloadCount) from Packages) as DownloadCount";

                                database.Connection.Open();
                                using (var reader = command.ExecuteReader(CommandBehavior.CloseConnection | CommandBehavior.SingleRow))
                                {
                                    bool hasData = reader.Read();
                                    if (!hasData) return new AggregateStats();

                                    return new AggregateStats
                                    {
                                        UniquePackages = reader.IsDBNull(0) ? 0 : reader.GetInt32(0),
                                        TotalPackages = reader.IsDBNull(1) ? 0 : reader.GetInt32(1),
                                        Downloads = reader.IsDBNull(2) ? 0 : reader.GetInt32(2),
                                    };
                                }
                            }
                        }
                    });
        }
        public Task<AggregateStats> GetAggregateStats()
        {
            using (var dbContext = new EntitiesContext(configuration.SqlConnectionString, readOnly: true)) // true - set readonly but it is ignored anyway, as this class doesn't call EntitiesContext.SaveChanges()
            {
                var database = dbContext.Database;
                using (var command = database.Connection.CreateCommand())
                {
                    command.CommandText = GetStatisticsSql;
                    database.Connection.Open();
                    using (var reader = command.ExecuteReader(CommandBehavior.CloseConnection | CommandBehavior.SingleRow))
                    {
                        bool hasData = reader.Read();
                        if (!hasData)
                        {
                            return Task.FromResult(new AggregateStats());
                        }

                        return Task.FromResult(new AggregateStats
                            {
                                UniquePackages = reader.IsDBNull(0) ? 0 : reader.GetInt32(0),
                                TotalPackages = reader.IsDBNull(1) ? 0 : reader.GetInt32(1),
                                Downloads = reader.IsDBNull(2) ? 0 : reader.GetInt64(2),
                            });
                    }
                }
            }
        }
        public AggregateStats GetAggregateStats()
        {
            using (var dbContext = new EntitiesContext(configuration.SqlConnectionString, readOnly: true)) // true - set readonly but it is ignored anyway, as this class doesn't call EntitiesContext.SaveChanges()
            {
                var database = dbContext.Database;
                using (var command = database.Connection.CreateCommand())
                {
                    command.CommandText = @"SELECT 
                    (SELECT COUNT([Key]) FROM PackageRegistrations pr 
                            WHERE EXISTS (SELECT 1 FROM Packages p WHERE p.PackageRegistrationKey = pr.[Key] AND p.Listed = 1)) AS UniquePackages,
                    (SELECT COUNT([Key]) FROM Packages WHERE Listed = 1) AS TotalPackages,
                    (SELECT TotalDownloadCount FROM GallerySettings) AS DownloadCount";

                    database.Connection.Open();
                    using (var reader = command.ExecuteReader(CommandBehavior.CloseConnection | CommandBehavior.SingleRow))
                    {
                        bool hasData = reader.Read();
                        if (!hasData)
                        {
                            return new AggregateStats();
                        }
                        return new AggregateStats
                            {
                                UniquePackages = reader.IsDBNull(0) ? 0 : reader.GetInt32(0),
                                TotalPackages = reader.IsDBNull(1) ? 0 : reader.GetInt32(1),
                                Downloads = reader.IsDBNull(2) ? 0 : reader.GetInt64(2),
                            };
                    }
                }
            }
        }
Пример #6
0
        private static void UpdateDatabase()
        {
            var dbMigrator = new DbMigrator(new Settings());
            dbMigrator.Update();
            // The Seed method of Settings is never called, so
            // we call it here again as a workaround.

            using (var context = new EntitiesContext())
            {
                Settings.SeedDatabase(context);
            }
        }
        public AggregateStats GetAggregateStats()
        {
            return Cache.Get("aggregatestats",
                    DateTime.UtcNow.AddMinutes(5),
                    () =>
                    {
                        using (var dbContext = new EntitiesContext())
                        {
                            var database = dbContext.Database;
                            using (var command = database.Connection.CreateCommand())
                            {
                                command.CommandText = @"SELECT 
  (Select COUNT([Key]) From PackageRegistrations pr Where Exists (select 1 from Packages p where p.PackageRegistrationKey = pr.[Key] and p.Listed = 1)) AS UniquePackages,
  (Select COUNT([Key]) From Packages Where Listed = 1) AS TotalPackages,
  (Select SUM(DownloadCount) From Packages) AS DownloadCount,
  (Select COUNT([Key]) From [dbo].[Packages] Where [Status] = 'Submitted' And SubmittedStatus <> 'Waiting') AS PackagesReadyForReview,
  (Select COUNT([Key]) From [dbo].[Packages] Where [Status] = 'Submitted') AS AllPackagesUnderModeration,
  (Select AVG(DATEDIFF(HOUR, Created, ApprovedDate)) From dbo.Packages Where [Status] = 'Approved' And ReviewedById is Not Null And Created >= DATEADD(DAY, -14, GETUTCDATE())) AS AverageModerationWaitTime,
  (Select COUNT([Key]) From [dbo].[Packages] Where IsLatestStable = 1 And PackageTestResultStatus = 'Passing') AS GoodPackages,
  (Select COUNT([Key]) From [dbo].[Packages] Where IsLatest = 1 And Created >= DATEADD(MONTH, -4, GETUTCDATE())) AS UpToDatePackages,
  (Select COUNT([Key]) From [dbo].[Packages] Where IsLatest = 1 And Created < DATEADD(YEAR, -1, GETUTCDATE())) AS OlderThanOneYearPackages
";

                                database.Connection.Open();
                                using (var reader = command.ExecuteReader(CommandBehavior.CloseConnection | CommandBehavior.SingleRow))
                                {
                                    bool hasData = reader.Read();
                                    if (!hasData) return new AggregateStats();

                                    return new AggregateStats
                                    {
                                        UniquePackages = reader.IsDBNull(0) ? 0 : reader.GetInt32(0),
                                        TotalPackages = reader.IsDBNull(1) ? 0 : reader.GetInt32(1),
                                        Downloads = reader.IsDBNull(2) ? 0 : reader.GetInt32(2),
                                        PackagesReadyForReviewModeration = reader.IsDBNull(3) ? 0 : reader.GetInt32(3),
                                        TotalPackagesInModeration = reader.IsDBNull(4) ? 0 : reader.GetInt32(4),
                                        AverageModerationWaitTimeHours = reader.IsDBNull(5) ? 0 : reader.GetInt32(5),
                                        GoodPackages = reader.IsDBNull(6) ? 0 : reader.GetInt32(6),
                                        UpToDatePackages = reader.IsDBNull(7) ? 0 : reader.GetInt32(7),
                                        OlderThanOneYearPackages = reader.IsDBNull(8) ? 0 : reader.GetInt32(8),
                                    };
                                }
                            }
                        }
                    });
        }
 public void UpdateIndex()
 {
     DateTime? lastWriteTime = GetLastWriteTime();
     bool creatingIndex = lastWriteTime == null;
     using (var context = new EntitiesContext())
     {
         var packages = GetPackages(context, lastWriteTime);
         if (packages.Any())
         {
             using (var directory = new LuceneFileSystem(LuceneCommon.IndexPath))
             {
                 var analyzer = new StandardAnalyzer(LuceneCommon.LuceneVersion);
                 var indexWriter = new IndexWriter(directory, analyzer, create: creatingIndex, mfl: IndexWriter.MaxFieldLength.UNLIMITED);
                 AddPackages(indexWriter, packages);
                 indexWriter.Close();
             }
         }
     }
     UpdateLastWriteTime();
 }
        public static List<Package> GetPublishedPackagesSince(string sqlConnectionString, int highestPackageKey, TextWriter log = null, bool verbose = false, bool includeUnlisted = true)
        {
            log = log ?? DefaultTraceWriter;

            EntitiesContext context = new EntitiesContext(sqlConnectionString, readOnly: true);
            IEntityRepository<Package> packageRepository = new EntityRepository<Package>(context);

            IQueryable<Package> set = packageRepository.GetAll();

            //  the query to get the id range is cheap and provides a workaround for EF limitations on Take() 

            Tuple<int, int> range = GetNextRange(sqlConnectionString, highestPackageKey, ChunkSize);

            if (range.Item1 == 0 && range.Item2 == 0)
            {
                //  make sure Key == 0 returns no rows and so we quit
                set = set.Where(p => 1 == 2);
            }
            else
            {
                set = set.Where(p => p.Key >= range.Item1 && p.Key <= range.Item2);
                set = set.OrderBy(p => p.Key);
            }

            if (!includeUnlisted)
            {
                set = set.Where(p => p.Listed);
            }

            set = set
                .Include(p => p.PackageRegistration)
                .Include(p => p.PackageRegistration.Owners)
                .Include(p => p.SupportedFrameworks)
                .Include(p => p.Dependencies);

            var results = ExecuteQuery(set, log, verbose);
            
            return results;
        }
 public QueryHintScope(EntitiesContext entitiesContext, string queryHint)
 {
     _entitiesContext           = entitiesContext ?? throw new ArgumentNullException(nameof(entitiesContext));
     _entitiesContext.QueryHint = queryHint;
 }
Пример #11
0
        private async Task <ActionResult> CreatePackageInternal()
        {
            // Get the user
            var user = GetCurrentUser();

            using (var packageStream = ReadPackageFromRequest())
            {
                try
                {
                    using (var archive = new ZipArchive(packageStream, ZipArchiveMode.Read, leaveOpen: true))
                    {
                        var reference = DateTime.UtcNow.AddDays(1); // allow "some" clock skew

                        var entryInTheFuture = archive.Entries.FirstOrDefault(
                            e => e.LastWriteTime.UtcDateTime > reference);

                        if (entryInTheFuture != null)
                        {
                            return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, string.Format(
                                                                        CultureInfo.CurrentCulture,
                                                                        Strings.PackageEntryFromTheFuture,
                                                                        entryInTheFuture.Name)));
                        }
                    }

                    using (var packageToPush = new PackageArchiveReader(packageStream, leaveStreamOpen: false))
                    {
                        NuspecReader nuspec = null;
                        try
                        {
                            nuspec = packageToPush.GetNuspecReader();
                        }
                        catch (Exception ex)
                        {
                            return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, string.Format(
                                                                        CultureInfo.CurrentCulture,
                                                                        Strings.UploadPackage_InvalidNuspec,
                                                                        ex.Message)));
                        }

                        if (nuspec.GetMinClientVersion() > Constants.MaxSupportedMinClientVersion)
                        {
                            return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, string.Format(
                                                                        CultureInfo.CurrentCulture,
                                                                        Strings.UploadPackage_MinClientVersionOutOfRange,
                                                                        nuspec.GetMinClientVersion())));
                        }

                        // Ensure that the user can push packages for this partialId.
                        var packageRegistration = PackageService.FindPackageRegistrationById(nuspec.GetId());
                        if (packageRegistration != null)
                        {
                            if (!packageRegistration.IsOwner(user))
                            {
                                // Audit that a non-owner tried to push the package
                                await AuditingService.SaveAuditRecord(
                                    new FailedAuthenticatedOperationAuditRecord(
                                        user.Username,
                                        AuditedAuthenticatedOperationAction.PackagePushAttemptByNonOwner,
                                        attemptedPackage : new AuditedPackageIdentifier(
                                            nuspec.GetId(), nuspec.GetVersion().ToNormalizedStringSafe())));

                                // User can not push this package
                                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Forbidden,
                                                                        Strings.ApiKeyNotAuthorized));
                            }

                            // Check if a particular Id-Version combination already exists. We eventually need to remove this check.
                            string normalizedVersion = nuspec.GetVersion().ToNormalizedString();
                            bool   packageExists     =
                                packageRegistration.Packages.Any(
                                    p => String.Equals(
                                        p.NormalizedVersion,
                                        normalizedVersion,
                                        StringComparison.OrdinalIgnoreCase));

                            if (packageExists)
                            {
                                return(new HttpStatusCodeWithBodyResult(
                                           HttpStatusCode.Conflict,
                                           String.Format(CultureInfo.CurrentCulture, Strings.PackageExistsAndCannotBeModified,
                                                         nuspec.GetId(), nuspec.GetVersion().ToNormalizedStringSafe())));
                            }
                        }

                        var packageStreamMetadata = new PackageStreamMetadata
                        {
                            HashAlgorithm = Constants.Sha512HashAlgorithmId,
                            Hash          = CryptographyService.GenerateHash(packageStream.AsSeekableStream()),
                            Size          = packageStream.Length,
                        };

                        var package = await PackageService.CreatePackageAsync(
                            packageToPush,
                            packageStreamMetadata,
                            user,
                            commitChanges : false);

                        await AutoCuratePackage.ExecuteAsync(package, packageToPush, commitChanges : false);

                        await EntitiesContext.SaveChangesAsync();

                        using (Stream uploadStream = packageStream)
                        {
                            uploadStream.Position = 0;
                            await PackageFileService.SavePackageFileAsync(package, uploadStream.AsSeekableStream());

                            IndexingService.UpdatePackage(package);
                        }

                        // Write an audit record
                        await AuditingService.SaveAuditRecord(
                            new PackageAuditRecord(package, AuditedPackageAction.Create, PackageCreatedVia.Api));

                        // Notify user of push
                        MessageService.SendPackageAddedNotice(package,
                                                              Url.Action("DisplayPackage", "Packages", routeValues: new { id = package.PackageRegistration.Id, version = package.Version }, protocol: Request.Url.Scheme),
                                                              Url.Action("ReportMyPackage", "Packages", routeValues: new { id = package.PackageRegistration.Id, version = package.Version }, protocol: Request.Url.Scheme),
                                                              Url.Action("Account", "Users", routeValues: null, protocol: Request.Url.Scheme));

                        return(new HttpStatusCodeResult(HttpStatusCode.Created));
                    }
                }
                catch (InvalidPackageException ex)
                {
                    return(BadRequestForExceptionMessage(ex));
                }
                catch (InvalidDataException ex)
                {
                    return(BadRequestForExceptionMessage(ex));
                }
                catch (EntityException ex)
                {
                    return(BadRequestForExceptionMessage(ex));
                }
                catch (FrameworkException ex)
                {
                    return(BadRequestForExceptionMessage(ex));
                }
            }
        }
Пример #12
0
        /// <summary>
        ///   Loads the module into the kernel.
        /// </summary>
        public void RegisterComponents(Container container)
        {
            IConfiguration configuration = new Configuration();
            container.Register(() => configuration, Lifestyle.Singleton);

            var gallerySetting = new Lazy<GallerySetting>(
                () =>
                {
                    using (var entitiesContext = new EntitiesContext())
                    {
                        var settingsRepo = new EntityRepository<GallerySetting>(entitiesContext);
                        return settingsRepo.GetAll().FirstOrDefault();
                    }
                });

            container.Register(() => gallerySetting.Value);
            //Bind<GallerySetting>().ToMethod(c => gallerySetting.Value);

            if (configuration.UseCaching)
            {
                var cacheProvider = AppServices.Cache;
                Cache.InitializeWith(cacheProvider);
                container.Register(() => cacheProvider, Lifestyle.Singleton);
            }

            container.RegisterPerWebRequest<ISearchService, LuceneSearchService>();
            container.RegisterPerWebRequest<IEntitiesContext>(() => new EntitiesContext());
            container.RegisterPerWebRequest<IEntityRepository<User>, EntityRepository<User>>();
            container.RegisterPerWebRequest<IEntityRepository<PackageRegistration>, EntityRepository<PackageRegistration>>();
            container.RegisterPerWebRequest<IEntityRepository<Package>, EntityRepository<Package>>();
            container.RegisterPerWebRequest<IEntityRepository<PackageAuthor>, EntityRepository<PackageAuthor>>();
            container.RegisterPerWebRequest<IEntityRepository<PackageFramework>, EntityRepository<PackageFramework>>();
            container.RegisterPerWebRequest<IEntityRepository<PackageDependency>, EntityRepository<PackageDependency>>();
            container.RegisterPerWebRequest<IEntityRepository<PackageFile>, EntityRepository<PackageFile>>();
            container.RegisterPerWebRequest<IEntityRepository<PackageStatistics>, EntityRepository<PackageStatistics>>();
            container.RegisterPerWebRequest<IEntityRepository<PackageOwnerRequest>, EntityRepository<PackageOwnerRequest>>();

            container.RegisterPerWebRequest<IUserService, UserService>();
            container.RegisterPerWebRequest<IPackageService, PackageService>();
            container.RegisterPerWebRequest<ICryptographyService, CryptographyService>();

            container.Register<IIndexingService, LuceneIndexingService>(Lifestyle.Singleton);
            container.Register<IFormsAuthenticationService, FormsAuthenticationService>(Lifestyle.Singleton);

            container.RegisterPerWebRequest<IControllerFactory, NuGetControllerFactory>();
            container.RegisterPerWebRequest<INuGetExeDownloaderService, NuGetExeDownloaderService>();

            var mailSenderThunk = new Lazy<IMailSender>(
                () =>
                {
                    var settings = container.GetInstance<GallerySetting>();
                    if (settings.UseSmtp)
                    {
                        var mailSenderConfiguration = new MailSenderConfiguration
                        {
                            DeliveryMethod = SmtpDeliveryMethod.Network,
                            Host = settings.SmtpHost,
                            Port = settings.SmtpPort,
                            EnableSsl = configuration.SmtpEnableSsl,
                        };

                        if (!String.IsNullOrWhiteSpace(settings.SmtpUsername))
                        {
                            mailSenderConfiguration.UseDefaultCredentials = false;
                            mailSenderConfiguration.Credentials = new NetworkCredential(settings.SmtpUsername, settings.SmtpPassword);
                        }

                        return new MailSender(mailSenderConfiguration);
                    } else
                    {
                        var mailSenderConfiguration = new MailSenderConfiguration
                        {
                            DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory,
                            PickupDirectoryLocation = HostingEnvironment.MapPath("~/App_Data/Mail")
                        };

                        return new MailSender(mailSenderConfiguration);
                    }
                });

            container.Register(() => mailSenderThunk.Value, Lifestyle.Singleton);

            container.Register<IMessageService, MessageService>(Lifestyle.Singleton);

            container.RegisterPerWebRequest(() => HttpContext.Current.User);
            //Bind<IPrincipal>().ToMethod(context => HttpContext.Current.User);

            switch (configuration.PackageStoreType)
            {
                case PackageStoreType.FileSystem:
                case PackageStoreType.NotSpecified:
                    container.Register<IFileSystemService, FileSystemService>(Lifestyle.Singleton);
                    container.Register<IFileStorageService, FileSystemFileStorageService>(Lifestyle.Singleton);
                    break;
                case PackageStoreType.AzureStorageBlob:
                    container.Register<ICloudBlobClient>(
                        () =>
                        new CloudBlobClientWrapper(
                            new CloudBlobClient(
                                new Uri(configuration.AzureStorageBlobUrl, UriKind.Absolute), new StorageCredentialsAccountAndKey(configuration.AzureStorageAccountName, configuration.AzureStorageAccessKey))),
                        Lifestyle.Singleton);
                    container.Register<IFileStorageService, CloudBlobFileStorageService>(Lifestyle.Singleton);
                    break;
                case PackageStoreType.AmazonS3Storage:
                    container.Register<IAmazonS3Client, AmazonS3ClientWrapper>(Lifestyle.Singleton);
                    container.Register<IFileStorageService, AmazonS3FileStorageService>(Lifestyle.Singleton);
                    break;
            }

            container.Register<IPackageFileService, PackageFileService>(Lifestyle.Singleton);
            container.Register<IUploadFileService, UploadFileService>();

            // todo: bind all package curators by convention
            container.Register<IAutomaticPackageCurator, WebMatrixPackageCurator>(Lifestyle.Singleton);
            container.Register<IAutomaticPackageCurator, Windows8PackageCurator>(Lifestyle.Singleton);

            // todo: bind all commands by convention
            container.RegisterPerWebRequest<IAutomaticallyCuratePackageCommand, AutomaticallyCuratePackageCommand>();
            container.RegisterPerWebRequest<ICreateCuratedPackageCommand, CreateCuratedPackageCommand>();
            container.RegisterPerWebRequest<IDeleteCuratedPackageCommand, DeleteCuratedPackageCommand>();
            container.RegisterPerWebRequest<IModifyCuratedPackageCommand, ModifyCuratedPackageCommand>();

            // todo: bind all queries by convention
            container.RegisterPerWebRequest<ICuratedFeedByKeyQuery, CuratedFeedByKeyQuery>();
            container.RegisterPerWebRequest<ICuratedFeedByNameQuery, CuratedFeedByNameQuery>();
            container.RegisterPerWebRequest<ICuratedFeedsByManagerQuery, CuratedFeedsByManagerQuery>();
            container.RegisterPerWebRequest<IPackageRegistrationByKeyQuery, PackageRegistrationByKeyQuery>();
            container.RegisterPerWebRequest<IPackageRegistrationByIdQuery, PackageRegistrationByIdQuery>();
            container.RegisterPerWebRequest<IUserByUsernameQuery, UserByUsernameQuery>();
            container.RegisterPerWebRequest<IPackageIdsQuery, PackageIdsQuery>();
            container.RegisterPerWebRequest<IPackageVersionsQuery, PackageVersionsQuery>();

            container.RegisterPerWebRequest<IAggregateStatsService, AggregateStatsService>();

            RegisterChocolateySpecific(container);
        }
Пример #13
0
        public override void Load()
        {
            IConfiguration configuration = new Configuration();

            Bind <IConfiguration>()
            .ToMethod(context => configuration);

            Lazy <GallerySetting> gallerySetting = new Lazy <GallerySetting>(() =>
            {
                using (var entitiesContext = new EntitiesContext())
                {
                    var settingsRepo = new EntityRepository <GallerySetting>(entitiesContext);
                    return(settingsRepo.GetAll().FirstOrDefault());
                }
            });

            Bind <GallerySetting>().ToMethod(c => gallerySetting.Value);

            Bind <EntitiesContext>()
            .ToMethod(context => new EntitiesContext())
            .InRequestScope();

            Bind <IEntityRepository <User> >()
            .To <EntityRepository <User> >()
            .InRequestScope();

            Bind <IEntityRepository <PackageRegistration> >()
            .To <EntityRepository <PackageRegistration> >()
            .InRequestScope();

            Bind <IEntityRepository <Package> >()
            .To <EntityRepository <Package> >()
            .InRequestScope();

            Bind <IEntityRepository <PackageAuthor> >()
            .To <EntityRepository <PackageAuthor> >()
            .InRequestScope();

            Bind <IEntityRepository <PackageDependency> >()
            .To <EntityRepository <PackageDependency> >()
            .InRequestScope();

            Bind <IEntityRepository <PackageStatistics> >()
            .To <EntityRepository <PackageStatistics> >()
            .InRequestScope();

            Bind <IUserService>()
            .To <UserService>()
            .InRequestScope();

            Bind <IPackageService>()
            .To <PackageService>()
            .InRequestScope();

            Bind <ICryptographyService>()
            .To <CryptographyService>()
            .InRequestScope();

            Bind <IFormsAuthenticationService>()
            .To <FormsAuthenticationService>()
            .InSingletonScope();

            Bind <IControllerFactory>()
            .To <NuGetControllerFactory>()
            .InRequestScope();

            Lazy <IMailSender> mailSenderThunk = new Lazy <IMailSender>(() =>
            {
                var settings = Kernel.Get <GallerySetting>();
                if (settings.UseSmtp)
                {
                    var mailSenderConfiguration = new MailSenderConfiguration()
                    {
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        Host           = settings.SmtpHost,
                        Port           = settings.SmtpPort,
                        EnableSsl      = true
                    };

                    if (!String.IsNullOrWhiteSpace(settings.SmtpUsername))
                    {
                        mailSenderConfiguration.UseDefaultCredentials = false;
                        mailSenderConfiguration.Credentials           = new NetworkCredential(
                            settings.SmtpUsername,
                            settings.SmtpPassword);
                    }

                    return(new MailSender(mailSenderConfiguration));
                }
                else
                {
                    var mailSenderConfiguration = new MailSenderConfiguration()
                    {
                        DeliveryMethod          = SmtpDeliveryMethod.SpecifiedPickupDirectory,
                        PickupDirectoryLocation = HostingEnvironment.MapPath("~/App_Data/Mail")
                    };

                    return(new MailSender(mailSenderConfiguration));
                }
            });

            Bind <IMailSender>()
            .ToMethod(context => mailSenderThunk.Value);

            Bind <IMessageService>()
            .To <MessageService>();

            Bind <IPrincipal>().ToMethod(context => HttpContext.Current.User);

            switch (configuration.PackageStoreType)
            {
            case PackageStoreType.FileSystem:
            case PackageStoreType.NotSpecified:
                Bind <IFileSystemService>()
                .To <FileSystemService>()
                .InSingletonScope();
                Bind <IFileStorageService>()
                .To <FileSystemFileStorageService>()
                .InSingletonScope();
                break;

            case PackageStoreType.AzureStorageBlob:
                Bind <ICloudBlobClient>()
                .ToMethod(context => new CloudBlobClientWrapper(new CloudBlobClient(
                                                                    new Uri(configuration.AzureStorageBlobUrl, UriKind.Absolute),
                                                                    new StorageCredentialsAccountAndKey(configuration.AzureStorageAccountName, configuration.AzureStorageAccessKey))))
                .InSingletonScope();
                Bind <IFileStorageService>()
                .To <CloudBlobFileStorageService>()
                .InSingletonScope();
                break;
            }

            Bind <IPackageFileService>()
            .To <PackageFileService>();

            Bind <IEntityRepository <PackageOwnerRequest> >()
            .To <EntityRepository <PackageOwnerRequest> >()
            .InRequestScope();

            Bind <IUploadFileService>()
            .To <UploadFileService>();
        }
Пример #14
0
        public override void Load()
        {
            IConfiguration configuration = new Configuration();
            Bind<IConfiguration>()
                .ToMethod(context => configuration);

            var gallerySetting = new Lazy<GallerySetting>(
                () =>
                    {
                        using (var entitiesContext = new EntitiesContext(configuration.SqlConnectionString, configuration.ReadOnlyMode))
                        {
                            var settingsRepo = new EntityRepository<GallerySetting>(entitiesContext);
                            return settingsRepo.GetAll().FirstOrDefault();
                        }
                    });

            Bind<GallerySetting>().ToMethod(c => gallerySetting.Value);

            Bind<Lucene.Net.Store.Directory>()
                .ToMethod(_ => LuceneCommon.GetDirectory())
                .InSingletonScope();

            Bind<ISearchService>()
                .To<LuceneSearchService>()
                .InRequestScope();

            if (!String.IsNullOrEmpty(configuration.AzureDiagnosticsConnectionString))
            {
                Bind<ErrorLog>()
                    .ToMethod(_ => new TableErrorLog(configuration.AzureDiagnosticsConnectionString))
                    .InSingletonScope();
            }
            else
            {
                Bind<ErrorLog>()
                    .ToMethod(_ => new SqlErrorLog(configuration.SqlConnectionString))
                    .InSingletonScope();
            }
            
            if (IsDeployedToCloud)
            {
                // when running on Windows Azure, use the Azure Cache local storage
                Bind<IPackageCacheService>()
                    .To<CloudPackageCacheService>()
                    .InSingletonScope();

                // when running on Windows Azure, use the Azure Cache service if available
                if (!String.IsNullOrEmpty(configuration.AzureCacheEndpoint))
                {
                    Bind<ICacheService>()
                        .To<CloudCacheService>()
                        .InSingletonScope();
                }
                else
                {
                    Bind<ICacheService>()
                        .To<HttpContextCacheService>()
                        .InRequestScope();
                }

                // when running on Windows Azure, pull the statistics from the warehouse via storage
                Bind<IReportService>()
                    .ToMethod(context => new CloudReportService(configuration.AzureStatisticsConnectionString))
                    .InSingletonScope();

                Bind<IStatisticsService>()
                    .To<JsonStatisticsService>()
                    .InSingletonScope();
            }
            else
            {
                Bind<IPackageCacheService>()
                    .To<NullPackageCacheService>()
                    .InSingletonScope();

                // when running locally on dev box, use the built-in ASP.NET Http Cache
                Bind<ICacheService>()
                    .To<HttpContextCacheService>()
                    .InRequestScope();
            }

            Bind<IEntitiesContext>()
                .ToMethod(context => new EntitiesContext(configuration.SqlConnectionString, readOnly: configuration.ReadOnlyMode))
                .InRequestScope();

            Bind<IEntityRepository<User>>()
                .To<EntityRepository<User>>()
                .InRequestScope();

            Bind<IEntityRepository<PackageRegistration>>()
                .To<EntityRepository<PackageRegistration>>()
                .InRequestScope();

            Bind<IEntityRepository<Package>>()
                .To<EntityRepository<Package>>()
                .InRequestScope();

            Bind<IEntityRepository<PackageAuthor>>()
                .To<EntityRepository<PackageAuthor>>()
                .InRequestScope();

            Bind<IEntityRepository<PackageDependency>>()
                .To<EntityRepository<PackageDependency>>()
                .InRequestScope();

            Bind<IEntityRepository<PackageStatistics>>()
                .To<EntityRepository<PackageStatistics>>()
                .InRequestScope();

            Bind<IUserService>()
                .To<UserService>()
                .InRequestScope();

            Bind<IPackageSource>()
                .To<PackageSource>()
                .InRequestScope();

            Bind<IPackageService>()
                .To<PackageService>()
                .InRequestScope();

            Bind<ICryptographyService>()
                .To<CryptographyService>()
                .InRequestScope();

            Bind<IFormsAuthenticationService>()
                .To<FormsAuthenticationService>()
                .InSingletonScope();

            Bind<IControllerFactory>()
                .To<NuGetControllerFactory>()
                .InRequestScope();

            Bind<IIndexingService>()
                .To<LuceneIndexingService>()
                .InRequestScope();

            Bind<INuGetExeDownloaderService>()
                .To<NuGetExeDownloaderService>()
                .InRequestScope();

            var mailSenderThunk = new Lazy<IMailSender>(
                () =>
                    {
                        var settings = Kernel.Get<GallerySetting>();
                        if (settings.UseSmtp)
                        {
                            var mailSenderConfiguration = new MailSenderConfiguration
                                {
                                    DeliveryMethod = SmtpDeliveryMethod.Network,
                                    Host = settings.SmtpHost,
                                    Port = settings.SmtpPort,
                                    EnableSsl = true
                                };

                            if (!String.IsNullOrWhiteSpace(settings.SmtpUsername))
                            {
                                mailSenderConfiguration.UseDefaultCredentials = false;
                                mailSenderConfiguration.Credentials = new NetworkCredential(
                                    settings.SmtpUsername,
                                    settings.SmtpPassword);
                            }

                            return new MailSender(mailSenderConfiguration);
                        }
                        else
                        {
                            var mailSenderConfiguration = new MailSenderConfiguration
                                {
                                    DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory,
                                    PickupDirectoryLocation = HostingEnvironment.MapPath("~/App_Data/Mail")
                                };

                            return new MailSender(mailSenderConfiguration);
                        }
                    });

            Bind<IMailSender>()
                .ToMethod(context => mailSenderThunk.Value);

            Bind<IMessageService>()
                .To<MessageService>();

            Bind<IPrincipal>().ToMethod(context => HttpContext.Current.User);

            switch (configuration.PackageStoreType)
            {
                case PackageStoreType.FileSystem:
                case PackageStoreType.NotSpecified:
                    Bind<IFileStorageService>()
                        .To<FileSystemFileStorageService>()
                        .InSingletonScope();
                    break;
                case PackageStoreType.AzureStorageBlob:
                    Bind<ICloudBlobClient>()
                        .ToMethod(
                            context => new CloudBlobClientWrapper(CloudStorageAccount.Parse(configuration.AzureStorageConnectionString).CreateCloudBlobClient()))
                        .InSingletonScope();
                    Bind<IFileStorageService>()
                        .To<CloudBlobFileStorageService>()
                        .InSingletonScope();
                    break;
            }

            Bind<IFileSystemService>()
                .To<FileSystemService>()
                .InSingletonScope();

            Bind<IPackageFileService>()
                .To<PackageFileService>();

            Bind<IEntityRepository<PackageOwnerRequest>>()
                .To<EntityRepository<PackageOwnerRequest>>()
                .InRequestScope();

            Bind<IUploadFileService>()
                .To<UploadFileService>();

            // todo: bind all package curators by convention
            Bind<IAutomaticPackageCurator>()
                .To<WebMatrixPackageCurator>();
            Bind<IAutomaticPackageCurator>()
                .To<Windows8PackageCurator>();

            // todo: bind all commands by convention
            Bind<IAutomaticallyCuratePackageCommand>()
                .To<AutomaticallyCuratePackageCommand>()
                .InRequestScope();
            Bind<ICreateCuratedPackageCommand>()
                .To<CreateCuratedPackageCommand>()
                .InRequestScope();
            Bind<IDeleteCuratedPackageCommand>()
                .To<DeleteCuratedPackageCommand>()
                .InRequestScope();
            Bind<IModifyCuratedPackageCommand>()
                .To<ModifyCuratedPackageCommand>()
                .InRequestScope();

            // todo: bind all queries by convention
            Bind<ICuratedFeedByKeyQuery>()
                .To<CuratedFeedByKeyQuery>()
                .InRequestScope();
            Bind<ICuratedFeedByNameQuery>()
                .To<CuratedFeedByNameQuery>()
                .InRequestScope();
            Bind<ICuratedFeedsByManagerQuery>()
                .To<CuratedFeedsByManagerQuery>()
                .InRequestScope();
            Bind<IPackageRegistrationByKeyQuery>()
                .To<PackageRegistrationByKeyQuery>()
                .InRequestScope();
            Bind<IPackageRegistrationByIdQuery>()
                .To<PackageRegistrationByIdQuery>()
                .InRequestScope();
            Bind<IUserByUsernameQuery>()
                .To<UserByUsernameQuery>()
                .InRequestScope();

            Bind<IAggregateStatsService>()
                .To<AggregateStatsService>()
                .InRequestScope();
            Bind<IPackageIdsQuery>()
                .To<PackageIdsQuery>()
                .InRequestScope();
            Bind<IPackageVersionsQuery>()
                .To<PackageVersionsQuery>()
                .InRequestScope();
        }
Пример #15
0
        public async Task AddOwnerToReservedNamespaceAsync(string prefix, string username)
        {
            if (string.IsNullOrWhiteSpace(prefix))
            {
                throw new ArgumentException(Strings.ReservedNamespace_InvalidNamespace);
            }

            if (string.IsNullOrWhiteSpace(username))
            {
                throw new ArgumentException(Strings.ReservedNamespace_InvalidUsername);
            }

            using (var strategy = new SuspendDbExecutionStrategy())
                using (var transaction = EntitiesContext.GetDatabase().BeginTransaction())
                {
                    var namespaceToModify = FindReservedNamespaceForPrefix(prefix)
                                            ?? throw new InvalidOperationException(string.Format(
                                                                                       CultureInfo.CurrentCulture, Strings.ReservedNamespace_NamespaceNotFound, prefix));

                    var userToAdd = UserService.FindByUsername(username)
                                    ?? throw new InvalidOperationException(string.Format(
                                                                               CultureInfo.CurrentCulture, Strings.ReservedNamespace_UserNotFound, username));

                    if (namespaceToModify.Owners.Contains(userToAdd))
                    {
                        throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings.ReservedNamespace_UserAlreadyOwner, username));
                    }

                    Expression <Func <PackageRegistration, bool> > predicate;
                    if (namespaceToModify.IsPrefix)
                    {
                        predicate = registration => registration.Id.StartsWith(namespaceToModify.Value);
                    }
                    else
                    {
                        predicate = registration => registration.Id.Equals(namespaceToModify.Value);
                    }

                    // Mark all packages owned by this user that start with the given namespace as verified.
                    var allPackageRegistrationsForUser = PackageService.FindPackageRegistrationsByOwner(userToAdd);

                    // We need 'AsQueryable' here because FindPackageRegistrationsByOwner returns an IEnumerable
                    // and to evaluate the predicate server side, the casting is essential.
                    var packageRegistrationsMatchingNamespace = allPackageRegistrationsForUser
                                                                .AsQueryable()
                                                                .Where(predicate)
                                                                .ToList();

                    if (packageRegistrationsMatchingNamespace.Any())
                    {
                        packageRegistrationsMatchingNamespace
                        .ForEach(pr => namespaceToModify.PackageRegistrations.Add(pr));

                        await PackageService.UpdatePackageVerifiedStatusAsync(packageRegistrationsMatchingNamespace.AsReadOnly(), isVerified : true);
                    }

                    namespaceToModify.Owners.Add(userToAdd);
                    await ReservedNamespaceRepository.CommitChangesAsync();

                    transaction.Commit();

                    await AuditingService.SaveAuditRecordAsync(
                        new ReservedNamespaceAuditRecord(namespaceToModify, AuditedReservedNamespaceAction.AddOwner, username, packageRegistrationsMatchingNamespace));
                }
        }
        public AggregateStats GetAggregateStats()
        {
            return Cache.Get("aggregatestats",
                    DateTime.UtcNow.AddMinutes(5),
                    () =>
                    {
                        using (var dbContext = new EntitiesContext())
                        {
                            var database = dbContext.Database;
                            using (var command = database.Connection.CreateCommand())
                            {
                                command.CommandText = @"SELECT 
  (Select COUNT([Key]) From PackageRegistrations pr With (NOLOCK) Where Exists (select 1 from Packages p  with (nolock) where p.PackageRegistrationKey = pr.[Key] and p.Listed = 1)) AS UniquePackages,
  (Select COUNT([Key]) From Packages With (NOLOCK) Where Listed = 1) AS TotalPackages,
  (Select SUM(DownloadCount) From Packages With (NOLOCK)) AS DownloadCount,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [Status] = 'Submitted' And SubmittedStatus <> 'Waiting') AS PackagesReadyForReview,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [Status] = 'Submitted') AS AllPackagesUnderModeration,
  (Select AVG(DATEDIFF(HOUR, Created, ApprovedDate)) From dbo.Packages With (NOLOCK) Where [Status] = 'Approved' And ReviewedById is Not Null And Created >= DATEADD(DAY, -30, GETUTCDATE())) AS AverageModerationWaitTime,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where IsLatest = 1 And Created >= DATEADD(MONTH, -4, GETUTCDATE())) AS UpToDatePackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where IsLatest = 1 And Created < DATEADD(YEAR, -1, GETUTCDATE())) AS OlderThanOneYearPackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [Status] = 'Approved' And [IsLatestStable] = 1) AS ApprovedPackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [Status] = 'Approved') AS TotalApprovedPackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [Status] = 'Approved' And [ReviewedById] Is Not Null And [IsLatestStable] = 1) AS ManuallyApprovedPackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [Status] = 'Approved' And [ReviewedById] Is Not Null) AS TotalManuallyApprovedPackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [Status] = 'Approved' And [ReviewedById] Is Null And [IsLatestStable] = 1) AS TrustedPackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [Status] = 'Approved' And [ReviewedById] Is Null) AS TotalTrustedPackages,
  (Select Count([Key]) From [dbo].[Packages] With (NOLOCK) Where [Status] = 'Rejected') AS TotalRejectedPackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [Status] = 'Exempted' And [ReviewedById] Is Not Null And [IsLatestStable] = 1) AS ExemptedPackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [Status] = 'Exempted' And [ReviewedById] Is Not Null) AS TotalExemptedPackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where ([Status] <> 'Approved' Or [Status] Is Null) And [IsLatestStable] = 1) AS UnknownPackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where ([Status] <> 'Approved' Or [Status] Is Null)) AS TotalUnknownPackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [IsLatest] = 1 And [IsLatestStable] = 0) AS LatestPackagePrerelease,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [Listed] = 0) AS TotalUnlistedPackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [IsLatestStable] = 1 And [PackageSourceUrl] Is Not Null) AS PackagesWithPackageSource,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where IsLatestStable = 1 And PackageTestResultStatus = 'Passing') AS PackagesPassingVerification,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where IsLatestStable = 1 And PackageTestResultStatus = 'Failing') AS PackagesFailingVerification,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [IsLatestStable] = 1 And PackageValidationResultStatus = 'Passing') AS PackagesPassingValidation,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [IsLatestStable] = 1 And PackageValidationResultStatus = 'Failing') AS PackagesFailingValidation,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [IsLatestStable] = 1 And DownloadCacheDate Is Not Null) AS PackagesCached,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where DownloadCacheDate Is Not Null) AS TotalPackagesCached,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [IsLatestStable] = 1 And DownloadCacheStatus = 'Available') AS PackagesCachedAvailable,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where DownloadCacheStatus = 'Available') AS TotalPackagesCachedAvailable,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [IsLatestStable] = 1 And DownloadCacheStatus = 'Investigate') AS PackagesCachedInvestigate,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where DownloadCacheStatus = 'Investigate') AS TotalPackagesCachedInvestigate,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [IsLatestStable] = 1 And PackageScanResultDate Is Not Null) AS PackagesScanned,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where PackageScanResultDate Is Not Null) AS TotalPackagesScanned,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [IsLatestStable] = 1 And PackageScanStatus = 'NotFlagged') AS PackagesScannedNotFlagged,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where PackageScanStatus = 'NotFlagged') AS TotalPackagesScannedNotFlagged,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [IsLatestStable] = 1 And PackageScanStatus = 'Flagged') AS PackagesScannedFlagged,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where PackageScanStatus = 'Flagged') AS TotalPackagesScannedFlagged,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [IsLatestStable] = 1 And PackageScanStatus = 'Exempted') AS PackagesScannedExempted,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where PackageScanStatus = 'Exempted') AS TotalPackagesScannedExempted,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [IsLatestStable] = 1 And PackageScanStatus = 'Investigate') AS PackagesScannedInvestigate,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where PackageScanStatus = 'Investigate') AS TotalPackagesScannedInvestigate,
  (Select COUNT(ScanOverlaps) From (select count([ScanResultKey]) as ScanOverlaps from [dbo].[PackageScanResults] with (nolock) group by ScanResultKey having count(ScanResultKey) > 1) overlaps) AS TotalFileScanOverlaps,
  (Select COUNT([Key]) From [dbo].[ScanResults] With (NOLOCK)) AS TotalFileScans

";

                                database.Connection.Open();
                                using (var reader = command.ExecuteReader(CommandBehavior.CloseConnection | CommandBehavior.SingleRow))
                                {
                                    bool hasData = reader.Read();
                                    if (!hasData) return new AggregateStats();

                                    return new AggregateStats
                                    {
                                        UniquePackages = reader.IsDBNull(0) ? 0 : reader.GetInt32(0),
                                        TotalPackages = reader.IsDBNull(1) ? 0 : reader.GetInt32(1),
                                        Downloads = reader.IsDBNull(2) ? 0 : reader.GetInt32(2),
                                        PackagesReadyForReviewModeration = reader.IsDBNull(3) ? 0 : reader.GetInt32(3),
                                        TotalPackagesInModeration = reader.IsDBNull(4) ? 0 : reader.GetInt32(4),
                                        AverageModerationWaitTimeHours = reader.IsDBNull(5) ? 0 : reader.GetInt32(5),
                                        UpToDatePackages = reader.IsDBNull(6) ? 0 : reader.GetInt32(6),
                                        OlderThanOneYearPackages = reader.IsDBNull(7) ? 0 : reader.GetInt32(7),
                                        ApprovedPackages  = reader.IsDBNull(8) ? 0 : reader.GetInt32(8),
                                        TotalApprovedPackages  = reader.IsDBNull(9) ? 0 : reader.GetInt32(9),
                                        ManuallyApprovedPackages  = reader.IsDBNull(10) ? 0 : reader.GetInt32(10),
                                        TotalManuallyApprovedPackages  = reader.IsDBNull(11) ? 0 : reader.GetInt32(11),
                                        TrustedPackages  = reader.IsDBNull(12) ? 0 : reader.GetInt32(12),
                                        TotalTrustedPackages  = reader.IsDBNull(13) ? 0 : reader.GetInt32(13),
                                        TotalRejectedPackages  = reader.IsDBNull(14) ? 0 : reader.GetInt32(14),
                                        ExemptedPackages  = reader.IsDBNull(15) ? 0 : reader.GetInt32(15),
                                        TotalExemptedPackages  = reader.IsDBNull(16) ? 0 : reader.GetInt32(16),
                                        UnknownPackages  = reader.IsDBNull(17) ? 0 : reader.GetInt32(17),
                                        TotalUnknownPackages  = reader.IsDBNull(18) ? 0 : reader.GetInt32(18),
                                        LatestPackagePrerelease  = reader.IsDBNull(19) ? 0 : reader.GetInt32(19),
                                        TotalUnlistedPackages  = reader.IsDBNull(20) ? 0 : reader.GetInt32(20),
                                        PackagesWithPackageSource  = reader.IsDBNull(21) ? 0 : reader.GetInt32(21),
                                        PackagesPassingVerification  = reader.IsDBNull(22) ? 0 : reader.GetInt32(22),
                                        PackagesFailingVerification  = reader.IsDBNull(23) ? 0 : reader.GetInt32(23),
                                        PackagesPassingValidation  = reader.IsDBNull(24) ? 0 : reader.GetInt32(24),
                                        PackagesFailingValidation  = reader.IsDBNull(25) ? 0 : reader.GetInt32(25),
                                        PackagesCached  = reader.IsDBNull(26) ? 0 : reader.GetInt32(26),
                                        TotalPackagesCached  = reader.IsDBNull(27) ? 0 : reader.GetInt32(27),
                                        PackagesCachedAvailable  = reader.IsDBNull(28) ? 0 : reader.GetInt32(28),
                                        TotalPackagesCachedAvailable  = reader.IsDBNull(29) ? 0 : reader.GetInt32(29),
                                        PackagesCachedInvestigate  = reader.IsDBNull(30) ? 0 : reader.GetInt32(30),
                                        TotalPackagesCachedInvestigate  = reader.IsDBNull(31) ? 0 : reader.GetInt32(31),
                                        PackagesScanned  = reader.IsDBNull(32) ? 0 : reader.GetInt32(32),
                                        TotalPackagesScanned  = reader.IsDBNull(33) ? 0 : reader.GetInt32(33),
                                        PackagesScannedNotFlagged  = reader.IsDBNull(34) ? 0 : reader.GetInt32(34),
                                        TotalPackagesScannedNotFlagged  = reader.IsDBNull(35) ? 0 : reader.GetInt32(35),
                                        PackagesScannedFlagged  = reader.IsDBNull(36) ? 0 : reader.GetInt32(36),
                                        TotalPackagesScannedFlagged  = reader.IsDBNull(37) ? 0 : reader.GetInt32(37),
                                        PackagesScannedExempted  = reader.IsDBNull(38) ? 0 : reader.GetInt32(38),
                                        TotalPackagesScannedExempted  = reader.IsDBNull(39) ? 0 : reader.GetInt32(39),
                                        PackagesScannedInvestigate  = reader.IsDBNull(40) ? 0 : reader.GetInt32(40),
                                        TotalPackagesScannedInvestigate  = reader.IsDBNull(41) ? 0 : reader.GetInt32(41),
                                        TotalFileScanOverlaps  = reader.IsDBNull(42) ? 0 : reader.GetInt32(42),
                                        TotalFileScans  = reader.IsDBNull(43) ? 0 : reader.GetInt32(43),
                                    };
                                }
                            }
                        }
                    });
        }
Пример #17
0
        private async Task <ActionResult> CreatePackageInternal()
        {
            // Get the user
            var user = GetCurrentUser();

            using (var packageToPush = ReadPackageFromRequest())
            {
                if (packageToPush.Metadata.MinClientVersion > typeof(Manifest).Assembly.GetName().Version)
                {
                    return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, String.Format(
                                                                CultureInfo.CurrentCulture,
                                                                Strings.UploadPackage_MinClientVersionOutOfRange,
                                                                packageToPush.Metadata.MinClientVersion)));
                }

                // Ensure that the user can push packages for this partialId.
                var packageRegistration = PackageService.FindPackageRegistrationById(packageToPush.Metadata.Id);
                if (packageRegistration != null)
                {
                    if (!packageRegistration.IsOwner(user))
                    {
                        return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Forbidden, Strings.ApiKeyNotAuthorized));
                    }

                    // Check if a particular Id-Version combination already exists. We eventually need to remove this check.
                    string normalizedVersion = packageToPush.Metadata.Version.ToNormalizedString();
                    bool   packageExists     =
                        packageRegistration.Packages.Any(
                            p => String.Equals(
                                p.NormalizedVersion,
                                normalizedVersion,
                                StringComparison.OrdinalIgnoreCase));

                    if (packageExists)
                    {
                        return(new HttpStatusCodeWithBodyResult(
                                   HttpStatusCode.Conflict,
                                   String.Format(CultureInfo.CurrentCulture, Strings.PackageExistsAndCannotBeModified,
                                                 packageToPush.Metadata.Id, packageToPush.Metadata.Version.ToNormalizedStringSafe())));
                    }
                }

                var package = PackageService.CreatePackage(packageToPush, user, commitChanges: false);
                AutoCuratePackage.Execute(package, packageToPush, commitChanges: false);
                EntitiesContext.SaveChanges();

                using (Stream uploadStream = packageToPush.GetStream())
                {
                    await PackageFileService.SavePackageFileAsync(package, uploadStream);
                }

                if (
                    packageToPush.Metadata.Id.Equals(Constants.NuGetCommandLinePackageId,
                                                     StringComparison.OrdinalIgnoreCase) && package.IsLatestStable)
                {
                    // If we're pushing a new stable version of NuGet.CommandLine, update the extracted executable.
                    await NugetExeDownloaderService.UpdateExecutableAsync(packageToPush);
                }
            }

            return(new HttpStatusCodeResult(HttpStatusCode.Created));
        }
Пример #18
0
        static void GeneratePackageDataFile(string[] args)
        {
            string connectionString = @"Data Source=(LocalDB)\v11.0;Initial Catalog=SearchTesting;Integrated Security=SSPI";
            var context = new EntitiesContext(connectionString, readOnly: false);
            var packageRepo = new EntityRepository<Package>(context);

            var packages = packageRepo.GetAll()
                .Where(p => p.IsLatest || p.IsLatestStable)  // which implies that p.IsListed by the way!
                .Include(p => p.PackageRegistration)
                .Include(p => p.PackageRegistration.Owners)
                .Include(p => p.SupportedFrameworks).ToList();

            var ja = new JArray();
            foreach (Package p in packages)
            {
                var pseudoPackage = new
                {
                    Authors = p.Authors.Select(pa => pa.Name).ToList(),
                    p.Copyright,
                    p.Created,
                    Dependencies = p.Dependencies.Select(pd => new { pd.TargetFramework, pd.VersionSpec }).ToList(),
                    p.Description,
                    p.DownloadCount,
                    p.FlattenedAuthors,
                    p.FlattenedDependencies,
                    p.Hash,
                    p.HashAlgorithm,
                    p.IconUrl,
                    p.IsLatest,
                    p.IsLatestStable,
                    p.IsPrerelease,
                    p.Key,
                    p.Language,
                    p.LastUpdated,
                    p.LicenseUrl,
                    p.Listed,
                    p.MinClientVersion,
                    p.PackageFileSize,
                    PackageRegistration = new
                    {
                        DownloadCount = p.PackageRegistration.DownloadCount,
                        Id = p.PackageRegistration.Id,
                        Key = p.PackageRegistration.Key,
                        Owners = p.PackageRegistration.Owners.Select(o => o.Username).ToList(),
                    },
                    p.PackageRegistrationKey,
                    p.ProjectUrl,
                    p.Published,
                    p.ReleaseNotes,
                    p.RequiresLicenseAcceptance,
                    p.Summary,
                    SupportedFrameworks = p.SupportedFrameworks.Select(pf => pf.TargetFramework).ToList(),
                    p.Tags,
                    p.Title,
                    p.Version,
                };

                foreach (var author in p.Authors)
                {
                    author.Package = null;
                }
                var jo = JObject.FromObject(pseudoPackage);
                string json = jo.ToString();
                ja.Add(jo);
            }

            File.WriteAllText(@"samplePackageData.json", ja.ToString());
        }
        private async Task <ActionResult> CreatePackageInternal()
        {
            var policyResult = await SecurityPolicyService.EvaluateAsync(SecurityPolicyAction.PackagePush, HttpContext);

            if (!policyResult.Success)
            {
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, policyResult.ErrorMessage));
            }

            // Get the user
            var user = GetCurrentUser();

            using (var packageStream = ReadPackageFromRequest())
            {
                try
                {
                    using (var archive = new ZipArchive(packageStream, ZipArchiveMode.Read, leaveOpen: true))
                    {
                        var reference = DateTime.UtcNow.AddDays(1); // allow "some" clock skew

                        var entryInTheFuture = archive.Entries.FirstOrDefault(
                            e => e.LastWriteTime.UtcDateTime > reference);

                        if (entryInTheFuture != null)
                        {
                            return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, string.Format(
                                                                        CultureInfo.CurrentCulture,
                                                                        Strings.PackageEntryFromTheFuture,
                                                                        entryInTheFuture.Name)));
                        }
                    }

                    using (var packageToPush = new PackageArchiveReader(packageStream, leaveStreamOpen: false))
                    {
                        try
                        {
                            PackageService.EnsureValid(packageToPush);
                        }
                        catch (Exception ex)
                        {
                            ex.Log();

                            var message = Strings.FailedToReadUploadFile;
                            if (ex is InvalidPackageException || ex is InvalidDataException || ex is EntityException)
                            {
                                message = ex.Message;
                            }

                            return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, message));
                        }

                        NuspecReader nuspec;
                        var          errors = ManifestValidator.Validate(packageToPush.GetNuspec(), out nuspec).ToArray();
                        if (errors.Length > 0)
                        {
                            var errorsString = string.Join("', '", errors.Select(error => error.ErrorMessage));
                            return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, string.Format(
                                                                        CultureInfo.CurrentCulture,
                                                                        errors.Length > 1 ? Strings.UploadPackage_InvalidNuspecMultiple : Strings.UploadPackage_InvalidNuspec,
                                                                        errorsString)));
                        }

                        if (nuspec.GetMinClientVersion() > Constants.MaxSupportedMinClientVersion)
                        {
                            return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, string.Format(
                                                                        CultureInfo.CurrentCulture,
                                                                        Strings.UploadPackage_MinClientVersionOutOfRange,
                                                                        nuspec.GetMinClientVersion())));
                        }

                        // Ensure that the user can push packages for this partialId.
                        var id = nuspec.GetId();
                        var packageRegistration = PackageService.FindPackageRegistrationById(id);
                        IReadOnlyCollection <ReservedNamespace> userOwnedNamespaces = null;
                        if (packageRegistration == null)
                        {
                            // Check if API key allows pushing a new package id
                            if (!ApiKeyScopeAllows(
                                    subject: id,
                                    requestedActions: NuGetScopes.PackagePush))
                            {
                                // User cannot push a new package ID as the API key scope does not allow it
                                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Unauthorized, Strings.ApiKeyNotAuthorized));
                            }

                            // For a new package id verify that the user is allowed to push to the matching namespaces, if any.
                            var isPushAllowed = ReservedNamespaceService.IsPushAllowed(id, user, out userOwnedNamespaces);
                            if (!isPushAllowed)
                            {
                                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Conflict, Strings.UploadPackage_IdNamespaceConflict));
                            }
                        }
                        else
                        {
                            // Is the user allowed to push this Id?
                            if (!packageRegistration.IsOwner(user))
                            {
                                // Audit that a non-owner tried to push the package
                                await AuditingService.SaveAuditRecordAsync(
                                    new FailedAuthenticatedOperationAuditRecord(
                                        user.Username,
                                        AuditedAuthenticatedOperationAction.PackagePushAttemptByNonOwner,
                                        attemptedPackage : new AuditedPackageIdentifier(
                                            id, nuspec.GetVersion().ToNormalizedStringSafe())));

                                // User cannot push a package to an ID owned by another user.
                                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Conflict,
                                                                        string.Format(CultureInfo.CurrentCulture, Strings.PackageIdNotAvailable,
                                                                                      id)));
                            }

                            // Check if API key allows pushing the current package id
                            if (!ApiKeyScopeAllows(
                                    packageRegistration.Id,
                                    NuGetScopes.PackagePushVersion, NuGetScopes.PackagePush))
                            {
                                // User cannot push a package as the API key scope does not allow it
                                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Unauthorized, Strings.ApiKeyNotAuthorized));
                            }

                            // Check if a particular Id-Version combination already exists. We eventually need to remove this check.
                            string normalizedVersion = nuspec.GetVersion().ToNormalizedString();
                            bool   packageExists     =
                                packageRegistration.Packages.Any(
                                    p => string.Equals(
                                        p.NormalizedVersion,
                                        normalizedVersion,
                                        StringComparison.OrdinalIgnoreCase));

                            if (packageExists)
                            {
                                return(new HttpStatusCodeWithBodyResult(
                                           HttpStatusCode.Conflict,
                                           string.Format(CultureInfo.CurrentCulture, Strings.PackageExistsAndCannotBeModified,
                                                         id, nuspec.GetVersion().ToNormalizedStringSafe())));
                            }
                        }

                        var packageStreamMetadata = new PackageStreamMetadata
                        {
                            HashAlgorithm = Constants.Sha512HashAlgorithmId,
                            Hash          = CryptographyService.GenerateHash(packageStream.AsSeekableStream()),
                            Size          = packageStream.Length
                        };

                        var package = await PackageUploadService.GeneratePackageAsync(
                            id,
                            packageToPush,
                            packageStreamMetadata,
                            user,
                            commitChanges : false);

                        await AutoCuratePackage.ExecuteAsync(package, packageToPush, commitChanges : false);

                        using (Stream uploadStream = packageStream)
                        {
                            uploadStream.Position = 0;

                            try
                            {
                                await PackageFileService.SavePackageFileAsync(package, uploadStream.AsSeekableStream());
                            }
                            catch (InvalidOperationException ex)
                            {
                                ex.Log();

                                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Conflict, Strings.UploadPackage_IdVersionConflict));
                            }
                        }

                        try
                        {
                            await EntitiesContext.SaveChangesAsync();
                        }
                        catch
                        {
                            // If saving to the DB fails for any reason, we need to delete the package we just saved.
                            await PackageFileService.DeletePackageFileAsync(nuspec.GetId(), nuspec.GetVersion().ToNormalizedString());

                            throw;
                        }

                        IndexingService.UpdatePackage(package);

                        // Write an audit record
                        await AuditingService.SaveAuditRecordAsync(
                            new PackageAuditRecord(package, AuditedPackageAction.Create, PackageCreatedVia.Api));

                        // Notify user of push
                        MessageService.SendPackageAddedNotice(package,
                                                              Url.Package(package.PackageRegistration.Id, package.NormalizedVersion, relativeUrl: false),
                                                              Url.ReportPackage(package.PackageRegistration.Id, package.NormalizedVersion, relativeUrl: false),
                                                              Url.AccountSettings(relativeUrl: false));

                        TelemetryService.TrackPackagePushEvent(package, user, User.Identity);

                        if (package.SemVerLevelKey == SemVerLevelKey.SemVer2)
                        {
                            return(new HttpStatusCodeWithServerWarningResult(HttpStatusCode.Created, Strings.WarningSemVer2PackagePushed));
                        }

                        return(new HttpStatusCodeResult(HttpStatusCode.Created));
                    }
                }
                catch (InvalidPackageException ex)
                {
                    return(BadRequestForExceptionMessage(ex));
                }
                catch (InvalidDataException ex)
                {
                    return(BadRequestForExceptionMessage(ex));
                }
                catch (EntityException ex)
                {
                    return(BadRequestForExceptionMessage(ex));
                }
                catch (FrameworkException ex)
                {
                    return(BadRequestForExceptionMessage(ex));
                }
            }
        }
Пример #20
0
        public override void Load()
        {
            IConfiguration configuration = new Configuration();

            Bind <IConfiguration>()
            .ToMethod(context => configuration);

            Lazy <GallerySetting> gallerySetting = new Lazy <GallerySetting>(() =>
            {
                using (var entitiesContext = new EntitiesContext())
                {
                    var settingsRepo = new EntityRepository <GallerySetting>(entitiesContext);
                    return(settingsRepo.GetAll().FirstOrDefault());
                }
            });

            Bind <GallerySetting>().ToMethod(c => gallerySetting.Value);

            Bind <ISearchService>()
            .To <LuceneSearchService>()
            .InRequestScope();

            Bind <IEntitiesContext>()
            .ToMethod(context => new EntitiesContext())
            .InRequestScope();

            Bind <IEntityRepository <User> >()
            .To <EntityRepository <User> >()
            .InRequestScope();

            Bind <IEntityRepository <PackageRegistration> >()
            .To <EntityRepository <PackageRegistration> >()
            .InRequestScope();

            Bind <IEntityRepository <Package> >()
            .To <EntityRepository <Package> >()
            .InRequestScope();

            Bind <IEntityRepository <PackageAuthor> >()
            .To <EntityRepository <PackageAuthor> >()
            .InRequestScope();

            Bind <IEntityRepository <PackageDependency> >()
            .To <EntityRepository <PackageDependency> >()
            .InRequestScope();

            Bind <IEntityRepository <PackageStatistics> >()
            .To <EntityRepository <PackageStatistics> >()
            .InRequestScope();

            Bind <IUserService>()
            .To <UserService>()
            .InRequestScope();

            Bind <IPackageService>()
            .To <PackageService>()
            .InRequestScope();

            Bind <ICryptographyService>()
            .To <CryptographyService>()
            .InRequestScope();

            Bind <IFormsAuthenticationService>()
            .To <FormsAuthenticationService>()
            .InSingletonScope();

            Bind <IControllerFactory>()
            .To <NuGetControllerFactory>()
            .InRequestScope();

            Bind <IIndexingService>()
            .To <LuceneIndexingService>()
            .InRequestScope();

            Bind <INuGetExeDownloaderService>()
            .To <NuGetExeDownloaderService>()
            .InRequestScope();

            Lazy <IMailSender> mailSenderThunk = new Lazy <IMailSender>(() =>
            {
                var settings = Kernel.Get <GallerySetting>();
                if (settings.UseSmtp)
                {
                    var mailSenderConfiguration = new MailSenderConfiguration()
                    {
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        Host           = settings.SmtpHost,
                        Port           = settings.SmtpPort,
                        EnableSsl      = true
                    };

                    if (!String.IsNullOrWhiteSpace(settings.SmtpUsername))
                    {
                        mailSenderConfiguration.UseDefaultCredentials = false;
                        mailSenderConfiguration.Credentials           = new NetworkCredential(
                            settings.SmtpUsername,
                            settings.SmtpPassword);
                    }

                    return(new MailSender(mailSenderConfiguration));
                }
                else
                {
                    var mailSenderConfiguration = new MailSenderConfiguration()
                    {
                        DeliveryMethod          = SmtpDeliveryMethod.SpecifiedPickupDirectory,
                        PickupDirectoryLocation = HostingEnvironment.MapPath("~/App_Data/Mail")
                    };

                    return(new MailSender(mailSenderConfiguration));
                }
            });

            Bind <IMailSender>()
            .ToMethod(context => mailSenderThunk.Value);

            Bind <IMessageService>()
            .To <MessageService>();

            Bind <IPrincipal>().ToMethod(context => HttpContext.Current.User);

            switch (configuration.PackageStoreType)
            {
            case PackageStoreType.FileSystem:
            case PackageStoreType.NotSpecified:
                Bind <IFileStorageService>()
                .To <FileSystemFileStorageService>()
                .InSingletonScope();
                break;

            case PackageStoreType.AzureStorageBlob:
                Bind <ICloudBlobClient>()
                .ToMethod(context => new CloudBlobClientWrapper(new CloudBlobClient(
                                                                    new Uri(configuration.AzureStorageBlobUrl, UriKind.Absolute),
                                                                    configuration.UseEmulator ?
                                                                    CloudStorageAccount.DevelopmentStorageAccount.Credentials :
                                                                    new StorageCredentialsAccountAndKey(configuration.AzureStorageAccountName, configuration.AzureStorageAccessKey))))
                .InSingletonScope();
                Bind <IFileStorageService>()
                .To <CloudBlobFileStorageService>()
                .InSingletonScope();
                break;
            }

            Bind <IFileSystemService>()
            .To <FileSystemService>()
            .InSingletonScope();

            Bind <IPackageFileService>()
            .To <PackageFileService>();

            Bind <IEntityRepository <PackageOwnerRequest> >()
            .To <EntityRepository <PackageOwnerRequest> >()
            .InRequestScope();

            Bind <IUploadFileService>()
            .To <UploadFileService>();

            // todo: bind all package curators by convention
            Bind <IAutomaticPackageCurator>()
            .To <WebMatrixPackageCurator>();
            Bind <IAutomaticPackageCurator>()
            .To <Windows8PackageCurator>();

            // todo: bind all commands by convention
            Bind <IAutomaticallyCuratePackageCommand>()
            .To <AutomaticallyCuratePackageCommand>()
            .InRequestScope();
            Bind <ICreateCuratedPackageCommand>()
            .To <CreateCuratedPackageCommand>()
            .InRequestScope();
            Bind <IDeleteCuratedPackageCommand>()
            .To <DeleteCuratedPackageCommand>()
            .InRequestScope();
            Bind <IModifyCuratedPackageCommand>()
            .To <ModifyCuratedPackageCommand>()
            .InRequestScope();

            // todo: bind all queries by convention
            Bind <ICuratedFeedByKeyQuery>()
            .To <CuratedFeedByKeyQuery>()
            .InRequestScope();
            Bind <ICuratedFeedByNameQuery>()
            .To <CuratedFeedByNameQuery>()
            .InRequestScope();
            Bind <ICuratedFeedsByManagerQuery>()
            .To <CuratedFeedsByManagerQuery>()
            .InRequestScope();
            Bind <IPackageRegistrationByKeyQuery>()
            .To <PackageRegistrationByKeyQuery>()
            .InRequestScope();
            Bind <IPackageRegistrationByIdQuery>()
            .To <PackageRegistrationByIdQuery>()
            .InRequestScope();
            Bind <IUserByUsernameQuery>()
            .To <UserByUsernameQuery>()
            .InRequestScope();

            Bind <IAggregateStatsService>()
            .To <AggregateStatsService>()
            .InRequestScope();
            Bind <IPackageIdsQuery>()
            .To <PackageIdsQuery>()
            .InRequestScope();
            Bind <IPackageVersionsQuery>()
            .To <PackageVersionsQuery>()
            .InRequestScope();
        }
Пример #21
0
 public PackageSource(EntitiesContext entitiesContext)
 {
     _packageSet = new EntityRepository <Package>(entitiesContext);
     _curatedPackageRepository = new EntityRepository <CuratedPackage>(entitiesContext);
 }
        public static IDictionary<int, IEnumerable<string>>  GetFeedsByPackageRegistration(string sqlConnectionString, TextWriter log, bool verbose)
        {
            log = log ?? DefaultTraceWriter;

            EntitiesContext context = new EntitiesContext(sqlConnectionString, readOnly: true);
            IEntityRepository<CuratedPackage> curatedPackageRepository = new EntityRepository<CuratedPackage>(context);

            var curatedFeedsPerPackageRegistrationGrouping = curatedPackageRepository.GetAll()
                .Include(c => c.CuratedFeed)
                .Select(cp => new { PackageRegistrationKey = cp.PackageRegistrationKey, FeedName = cp.CuratedFeed.Name })
                .GroupBy(x => x.PackageRegistrationKey);

            if (verbose)
            {
                log.WriteLine(curatedFeedsPerPackageRegistrationGrouping.ToString());
            }

            //  database call

            DateTime before = DateTime.Now;

            IDictionary<int, IEnumerable<string>> feeds = curatedFeedsPerPackageRegistrationGrouping
                .ToDictionary(group => group.Key, element => element.Select(x => x.FeedName));

            DateTime after = DateTime.Now;

            log.WriteLine("Feeds: {0} rows returned, duration {1} seconds", feeds.Count, (after - before).TotalSeconds);

            return feeds;
        }
Пример #23
0
        public async Task <Membership> AddMemberAsync(Organization organization, string memberName, string confirmationToken)
        {
            organization = organization ?? throw new ArgumentNullException(nameof(organization));

            var request = FindMembershipRequestByUsername(organization, memberName);

            if (request == null || request.ConfirmationToken != confirmationToken)
            {
                throw new EntityException(string.Format(CultureInfo.CurrentCulture,
                                                        Strings.AddMember_MissingRequest, memberName));
            }

            var member = request.NewMember;

            organization.MemberRequests.Remove(request);

            if (!member.Confirmed)
            {
                throw new EntityException(string.Format(CultureInfo.CurrentCulture,
                                                        Strings.AddMember_UserNotConfirmed, memberName));
            }

            if (member is Organization)
            {
                throw new EntityException(string.Format(CultureInfo.CurrentCulture,
                                                        Strings.AddMember_UserIsOrganization, memberName));
            }

            var membership = FindMembershipByUsername(organization, memberName);

            if (membership == null)
            {
                // Ensure that the new member meets the AAD tenant policy for this organization.
                var policyResult = await SecurityPolicyService.EvaluateOrganizationPoliciesAsync(
                    SecurityPolicyAction.JoinOrganization, organization, member);

                if (policyResult != SecurityPolicyResult.SuccessResult)
                {
                    throw new EntityException(string.Format(CultureInfo.CurrentCulture,
                                                            Strings.AddMember_PolicyFailure, policyResult.ErrorMessage));
                }

                membership = new Membership()
                {
                    Member  = member,
                    IsAdmin = request.IsAdmin
                };
                organization.Members.Add(membership);

                await Auditing.SaveAuditRecordAsync(new UserAuditRecord(organization, AuditedUserAction.AddOrganizationMember, membership));
            }
            else
            {
                // If the user is already a member, update the existing membership.
                // If the request grants admin but this member is not an admin, grant admin to the member.
                membership.IsAdmin = membership.IsAdmin || request.IsAdmin;

                await Auditing.SaveAuditRecordAsync(new UserAuditRecord(organization, AuditedUserAction.UpdateOrganizationMember, membership));
            }

            await EntitiesContext.SaveChangesAsync();

            return(membership);
        }
        public static List<Package> GetPackages(string sqlConnectionString, List<int> packageKeys, TextWriter log = null, bool verbose = false)
        {
            log = log ?? DefaultTraceWriter;

            EntitiesContext context = new EntitiesContext(sqlConnectionString, readOnly: true);
            IEntityRepository<Package> packageRepository = new EntityRepository<Package>(context);

            IQueryable<Package> set = packageRepository.GetAll();

            set = set.Where(p => packageKeys.Contains(p.Key));

            set = set.OrderBy(p => p.Key);

            set = set
                .Include(p => p.PackageRegistration)
                .Include(p => p.PackageRegistration.Owners)
                .Include(p => p.SupportedFrameworks)
                .Include(p => p.Dependencies);

            return ExecuteQuery(set, log, verbose);
        }
Пример #25
0
        public async Task <MembershipRequest> AddMembershipRequestAsync(Organization organization, string memberName, bool isAdmin)
        {
            organization = organization ?? throw new ArgumentNullException(nameof(organization));

            var membership = FindMembershipByUsername(organization, memberName);

            if (membership != null)
            {
                throw new EntityException(string.Format(CultureInfo.CurrentCulture,
                                                        Strings.AddMember_AlreadyAMember, memberName));
            }

            var request = FindMembershipRequestByUsername(organization, memberName);

            if (request != null)
            {
                // If there is already an existing request, return it.
                // If the existing request grants collaborator but we are trying to create a request that grants admin, update the request to grant admin.
                request.IsAdmin = isAdmin || request.IsAdmin;
                await EntitiesContext.SaveChangesAsync();

                return(request);
            }

            var member = FindByUsername(memberName);

            if (member == null)
            {
                throw new EntityException(string.Format(CultureInfo.CurrentCulture,
                                                        Strings.AddMember_UserNotFound, memberName));
            }

            if (!member.Confirmed)
            {
                throw new EntityException(string.Format(CultureInfo.CurrentCulture,
                                                        Strings.AddMember_UserNotConfirmed, memberName));
            }

            if (member is Organization)
            {
                throw new EntityException(string.Format(CultureInfo.CurrentCulture,
                                                        Strings.AddMember_UserIsOrganization, memberName));
            }

            // Ensure that the new member meets the AAD tenant policy for this organization.
            var policyResult = await SecurityPolicyService.EvaluateOrganizationPoliciesAsync(
                SecurityPolicyAction.JoinOrganization, organization, member);

            if (policyResult != SecurityPolicyResult.SuccessResult)
            {
                throw new EntityException(policyResult.ErrorMessage);
            }

            request = new MembershipRequest()
            {
                Organization      = organization,
                NewMember         = member,
                IsAdmin           = isAdmin,
                ConfirmationToken = Crypto.GenerateToken(),
                RequestDate       = DateTime.UtcNow,
            };
            organization.MemberRequests.Add(request);

            await EntitiesContext.SaveChangesAsync();

            return(request);
        }
Пример #26
0
        /// <summary>
        ///   Loads the module into the kernel.
        /// </summary>
        public void RegisterComponents(SimpleInjector.Container container)
        {
            IConfiguration configuration = new Configuration();

            container.Register <IConfiguration>(() => configuration, Lifestyle.Singleton);

            Lazy <GallerySetting> gallerySetting = new Lazy <GallerySetting>(() =>
            {
                using (var entitiesContext = new EntitiesContext())
                {
                    var settingsRepo = new EntityRepository <GallerySetting>(entitiesContext);
                    return(settingsRepo.GetAll().FirstOrDefault());
                }
            });

            container.Register <GallerySetting>(() => gallerySetting.Value);
            //Bind<GallerySetting>().ToMethod(c => gallerySetting.Value);

            container.RegisterPerWebRequest <ISearchService, LuceneSearchService>();

            container.RegisterPerWebRequest <IEntitiesContext>(() => new EntitiesContext());
            container.RegisterPerWebRequest <IEntityRepository <User>, EntityRepository <User> >();
            container.RegisterPerWebRequest <IEntityRepository <PackageRegistration>, EntityRepository <PackageRegistration> >();
            container.RegisterPerWebRequest <IEntityRepository <Package>, EntityRepository <Package> >();
            container.RegisterPerWebRequest <IEntityRepository <PackageAuthor>, EntityRepository <PackageAuthor> >();
            container.RegisterPerWebRequest <IEntityRepository <PackageFramework>, EntityRepository <PackageFramework> >();
            container.RegisterPerWebRequest <IEntityRepository <PackageDependency>, EntityRepository <PackageDependency> >();
            container.RegisterPerWebRequest <IEntityRepository <PackageFile>, EntityRepository <PackageFile> >();
            container.RegisterPerWebRequest <IEntityRepository <PackageStatistics>, EntityRepository <PackageStatistics> >();
            container.RegisterPerWebRequest <IEntityRepository <PackageOwnerRequest>, EntityRepository <PackageOwnerRequest> >();

            container.RegisterPerWebRequest <IUserService, UserService>();
            container.RegisterPerWebRequest <IPackageService, PackageService>();
            container.RegisterPerWebRequest <ICryptographyService, CryptographyService>();

            container.Register <IFormsAuthenticationService, FormsAuthenticationService>(Lifestyle.Singleton);

            container.RegisterPerWebRequest <IControllerFactory, NuGetControllerFactory>();
            container.RegisterPerWebRequest <IIndexingService, LuceneIndexingService>();
            container.RegisterPerWebRequest <INuGetExeDownloaderService, NuGetExeDownloaderService>();

            Lazy <IMailSender> mailSenderThunk = new Lazy <IMailSender>(() =>
            {
                var settings = container.GetInstance <GallerySetting>();
                if (settings.UseSmtp)
                {
                    var mailSenderConfiguration = new MailSenderConfiguration()
                    {
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        Host           = settings.SmtpHost,
                        Port           = settings.SmtpPort,
                        EnableSsl      = configuration.SmtpEnableSsl,
                    };

                    if (!String.IsNullOrWhiteSpace(settings.SmtpUsername))
                    {
                        mailSenderConfiguration.UseDefaultCredentials = false;
                        mailSenderConfiguration.Credentials           = new NetworkCredential(
                            settings.SmtpUsername,
                            settings.SmtpPassword);
                    }

                    return(new NuGetGallery.MailSender(mailSenderConfiguration));
                }
                else
                {
                    var mailSenderConfiguration = new MailSenderConfiguration()
                    {
                        DeliveryMethod          = SmtpDeliveryMethod.SpecifiedPickupDirectory,
                        PickupDirectoryLocation = HostingEnvironment.MapPath("~/App_Data/Mail")
                    };

                    return(new NuGetGallery.MailSender(mailSenderConfiguration));
                }
            });

            container.Register <IMailSender>(() => mailSenderThunk.Value, Lifestyle.Singleton);

            container.Register <IMessageService, MessageService>(Lifestyle.Singleton);

            container.RegisterPerWebRequest <IPrincipal>(() => HttpContext.Current.User);
            //Bind<IPrincipal>().ToMethod(context => HttpContext.Current.User);

            switch (configuration.PackageStoreType)
            {
            case PackageStoreType.FileSystem:
            case PackageStoreType.NotSpecified:
                container.Register <IFileSystemService, FileSystemService>(Lifestyle.Singleton);
                container.Register <IFileStorageService, FileSystemFileStorageService>(Lifestyle.Singleton);
                break;

            case PackageStoreType.AzureStorageBlob:
                container.Register <ICloudBlobClient>(() => new CloudBlobClientWrapper(new CloudBlobClient(
                                                                                           new Uri(configuration.AzureStorageBlobUrl, UriKind.Absolute),
                                                                                           new StorageCredentialsAccountAndKey(configuration.AzureStorageAccountName, configuration.AzureStorageAccessKey)
                                                                                           ))
                                                      , Lifestyle.Singleton);
                container.Register <IFileStorageService, CloudBlobFileStorageService>(Lifestyle.Singleton);
                break;

            case PackageStoreType.AmazonS3Storage:
                container.Register <IAmazonS3Client, AmazonS3ClientWrapper>(Lifestyle.Singleton);
                container.Register <IFileStorageService, AmazonS3FileStorageService>(Lifestyle.Singleton);
                break;
            }

            container.Register <IPackageFileService, PackageFileService>(Lifestyle.Singleton);
            container.Register <IUploadFileService, UploadFileService>();

            // todo: bind all package curators by convention
            container.Register <IAutomaticPackageCurator, WebMatrixPackageCurator>(Lifestyle.Singleton);
            container.Register <IAutomaticPackageCurator, Windows8PackageCurator>(Lifestyle.Singleton);

            // todo: bind all commands by convention
            container.RegisterPerWebRequest <IAutomaticallyCuratePackageCommand, AutomaticallyCuratePackageCommand>();
            container.RegisterPerWebRequest <ICreateCuratedPackageCommand, CreateCuratedPackageCommand>();
            container.RegisterPerWebRequest <IDeleteCuratedPackageCommand, DeleteCuratedPackageCommand>();
            container.RegisterPerWebRequest <IModifyCuratedPackageCommand, ModifyCuratedPackageCommand>();

            // todo: bind all queries by convention
            container.RegisterPerWebRequest <ICuratedFeedByKeyQuery, CuratedFeedByKeyQuery>();
            container.RegisterPerWebRequest <ICuratedFeedByNameQuery, CuratedFeedByNameQuery>();
            container.RegisterPerWebRequest <ICuratedFeedsByManagerQuery, CuratedFeedsByManagerQuery>();
            container.RegisterPerWebRequest <IPackageRegistrationByKeyQuery, PackageRegistrationByKeyQuery>();
            container.RegisterPerWebRequest <IPackageRegistrationByIdQuery, PackageRegistrationByIdQuery>();
            container.RegisterPerWebRequest <IUserByUsernameQuery, UserByUsernameQuery>();
            container.RegisterPerWebRequest <IPackageIdsQuery, PackageIdsQuery>();
            container.RegisterPerWebRequest <IPackageVersionsQuery, PackageVersionsQuery>();

            container.RegisterPerWebRequest <IAggregateStatsService, AggregateStatsService>();

            RegisterChocolateySpecific(container);
        }
 public EntityRepository(EntitiesContext entities)
 {
     this.entities = entities;
 }
Пример #28
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 (!String.IsNullOrEmpty(version))
            {
                SemanticVersion dummy;
                if (!SemanticVersion.TryParse(version, out dummy))
                {
                    return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, "The package version is not a valid semantic version"));
                }
            }

            // Normalize the version
            version = SemanticVersionExtensions.Normalize(version);

            // if the version is null, the user is asking for the latest version. Presumably they don't want includePrerelease release versions.
            // The allow prerelease flag is ignored if both partialId and version are specified.
            // In general we want to try to add download statistics for any package regardless of whether a version was specified.

            // Only allow database requests to take up to 5 seconds.  Any longer and we just lose the data; oh well.
            EntitiesContext.SetCommandTimeout(5);

            Package package = null;

            try
            {
                package = PackageService.FindPackageByIdAndVersion(id, version, allowPrerelease: false);
                if (package == null)
                {
                    return(new HttpStatusCodeWithBodyResult(
                               HttpStatusCode.NotFound, String.Format(CultureInfo.CurrentCulture, Strings.PackageWithIdAndVersionNotFound, id, version)));
                }

                try
                {
                    var stats = new PackageStatistics
                    {
                        IPAddress        = Request.UserHostAddress,
                        UserAgent        = Request.UserAgent,
                        Package          = package,
                        Operation        = Request.Headers["NuGet-Operation"],
                        DependentPackage = Request.Headers["NuGet-DependentPackage"],
                        ProjectGuids     = Request.Headers["NuGet-ProjectGuids"],
                    };

                    if (_config == null || _config.MetricsServiceUri == null)
                    {
                        PackageService.AddDownloadStatistics(stats);
                    }
                    else
                    {
                        // Disable warning about not awaiting async calls because we are _intentionally_ not awaiting this.
#pragma warning disable 4014
                        Task.Run(() => PostDownloadStatistics(id, package.NormalizedVersion, stats.IPAddress, stats.UserAgent, stats.Operation, stats.DependentPackage, stats.ProjectGuids));
#pragma warning restore 4014
                    }
                }
                catch (ReadOnlyModeException)
                {
                    // *gulp* Swallowed. It's OK not to add statistics and ok to not log errors in read only mode.
                }
                catch (SqlException e)
                {
                    // Log the error and continue
                    QuietLog.LogHandledException(e);
                }
                catch (DataException e)
                {
                    // Log the error and continue
                    QuietLog.LogHandledException(e);
                }
            }
            catch (SqlException e)
            {
                QuietLog.LogHandledException(e);
            }
            catch (DataException e)
            {
                QuietLog.LogHandledException(e);
            }

            // Fall back to constructing the URL based on the package version and ID.
            if (String.IsNullOrEmpty(version) && package == null)
            {
                // Database was unavailable and we don't have a version, return a 503
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.ServiceUnavailable, Strings.DatabaseUnavailable_TrySpecificVersion));
            }
            return(await PackageFileService.CreateDownloadPackageActionResultAsync(
                       HttpContext.Request.Url,
                       id,
                       String.IsNullOrEmpty(version)?package.NormalizedVersion : version));
        }
Пример #29
0
        public AggregateStats GetAggregateStats()
        {
            return(Cache.Get("aggregatestats",
                             DateTime.UtcNow.AddMinutes(5),
                             () =>
            {
                using (var dbContext = new EntitiesContext())
                {
                    var database = dbContext.Database;
                    using (var command = database.Connection.CreateCommand())
                    {
                        command.CommandText = @"SELECT 
  (Select COUNT([Key]) From PackageRegistrations pr With (NOLOCK) Where Exists (select 1 from Packages p  with (nolock) where p.PackageRegistrationKey = pr.[Key] and p.Listed = 1)) AS UniquePackages,
  (Select COUNT([Key]) From Packages With (NOLOCK) Where Listed = 1) AS TotalPackages,
  (Select SUM(DownloadCount) From Packages With (NOLOCK)) AS DownloadCount,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [Status] = 'Submitted' And SubmittedStatus <> 'Waiting') AS PackagesReadyForReview,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [Status] = 'Submitted') AS AllPackagesUnderModeration,
  (Select AVG(DATEDIFF(HOUR, Created, ApprovedDate)) From dbo.Packages With (NOLOCK) Where [Status] = 'Approved' And ReviewedById is Not Null And Created >= DATEADD(DAY, -30, GETUTCDATE())) AS AverageModerationWaitTime,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where IsLatest = 1 And Created >= DATEADD(MONTH, -4, GETUTCDATE())) AS UpToDatePackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where IsLatest = 1 And Created < DATEADD(YEAR, -1, GETUTCDATE())) AS OlderThanOneYearPackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [Status] = 'Approved' And [IsLatestStable] = 1) AS ApprovedPackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [Status] = 'Approved') AS TotalApprovedPackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [Status] = 'Approved' And [ReviewedById] Is Not Null And [IsLatestStable] = 1) AS ManuallyApprovedPackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [Status] = 'Approved' And [ReviewedById] Is Not Null) AS TotalManuallyApprovedPackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [Status] = 'Approved' And [ReviewedById] Is Null And [IsLatestStable] = 1) AS TrustedPackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [Status] = 'Approved' And [ReviewedById] Is Null) AS TotalTrustedPackages,
  (Select Count([Key]) From [dbo].[Packages] With (NOLOCK) Where [Status] = 'Rejected') AS TotalRejectedPackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [Status] = 'Exempted' And [ReviewedById] Is Not Null And [IsLatestStable] = 1) AS ExemptedPackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [Status] = 'Exempted' And [ReviewedById] Is Not Null) AS TotalExemptedPackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where ([Status] <> 'Approved' Or [Status] Is Null) And [IsLatestStable] = 1) AS UnknownPackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where ([Status] <> 'Approved' Or [Status] Is Null)) AS TotalUnknownPackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [IsLatest] = 1 And [IsLatestStable] = 0) AS LatestPackagePrerelease,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [Listed] = 0) AS TotalUnlistedPackages,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [IsLatestStable] = 1 And [PackageSourceUrl] Is Not Null) AS PackagesWithPackageSource,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where IsLatestStable = 1 And PackageTestResultStatus = 'Passing') AS PackagesPassingVerification,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where IsLatestStable = 1 And PackageTestResultStatus = 'Failing') AS PackagesFailingVerification,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [IsLatestStable] = 1 And PackageValidationResultStatus = 'Passing') AS PackagesPassingValidation,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [IsLatestStable] = 1 And PackageValidationResultStatus = 'Failing') AS PackagesFailingValidation,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [IsLatestStable] = 1 And DownloadCacheDate Is Not Null) AS PackagesCached,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where DownloadCacheDate Is Not Null) AS TotalPackagesCached,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [IsLatestStable] = 1 And DownloadCacheStatus = 'Available') AS PackagesCachedAvailable,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where DownloadCacheStatus = 'Available') AS TotalPackagesCachedAvailable,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [IsLatestStable] = 1 And DownloadCacheStatus = 'Investigate') AS PackagesCachedInvestigate,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where DownloadCacheStatus = 'Investigate') AS TotalPackagesCachedInvestigate,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [IsLatestStable] = 1 And PackageScanResultDate Is Not Null) AS PackagesScanned,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where PackageScanResultDate Is Not Null) AS TotalPackagesScanned,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [IsLatestStable] = 1 And PackageScanStatus = 'NotFlagged') AS PackagesScannedNotFlagged,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where PackageScanStatus = 'NotFlagged') AS TotalPackagesScannedNotFlagged,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [IsLatestStable] = 1 And PackageScanStatus = 'Flagged') AS PackagesScannedFlagged,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where PackageScanStatus = 'Flagged') AS TotalPackagesScannedFlagged,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [IsLatestStable] = 1 And PackageScanStatus = 'Exempted') AS PackagesScannedExempted,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where PackageScanStatus = 'Exempted') AS TotalPackagesScannedExempted,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where [IsLatestStable] = 1 And PackageScanStatus = 'Investigate') AS PackagesScannedInvestigate,
  (Select COUNT([Key]) From [dbo].[Packages] With (NOLOCK) Where PackageScanStatus = 'Investigate') AS TotalPackagesScannedInvestigate,
  (Select COUNT(ScanOverlaps) From (select count([ScanResultKey]) as ScanOverlaps from [dbo].[PackageScanResults] with (nolock) group by ScanResultKey having count(ScanResultKey) > 1) overlaps) AS TotalFileScanOverlaps,
  (Select COUNT([Key]) From [dbo].[ScanResults] With (NOLOCK)) AS TotalFileScans

";

                        database.Connection.Open();
                        using (var reader = command.ExecuteReader(CommandBehavior.CloseConnection | CommandBehavior.SingleRow))
                        {
                            bool hasData = reader.Read();
                            if (!hasData)
                            {
                                return new AggregateStats();
                            }

                            return new AggregateStats
                            {
                                UniquePackages = reader.IsDBNull(0) ? 0 : reader.GetInt32(0),
                                TotalPackages = reader.IsDBNull(1) ? 0 : reader.GetInt32(1),
                                Downloads = reader.IsDBNull(2) ? 0 : reader.GetInt32(2),
                                PackagesReadyForReviewModeration = reader.IsDBNull(3) ? 0 : reader.GetInt32(3),
                                TotalPackagesInModeration = reader.IsDBNull(4) ? 0 : reader.GetInt32(4),
                                AverageModerationWaitTimeHours = reader.IsDBNull(5) ? 0 : reader.GetInt32(5),
                                UpToDatePackages = reader.IsDBNull(6) ? 0 : reader.GetInt32(6),
                                OlderThanOneYearPackages = reader.IsDBNull(7) ? 0 : reader.GetInt32(7),
                                ApprovedPackages = reader.IsDBNull(8) ? 0 : reader.GetInt32(8),
                                TotalApprovedPackages = reader.IsDBNull(9) ? 0 : reader.GetInt32(9),
                                ManuallyApprovedPackages = reader.IsDBNull(10) ? 0 : reader.GetInt32(10),
                                TotalManuallyApprovedPackages = reader.IsDBNull(11) ? 0 : reader.GetInt32(11),
                                TrustedPackages = reader.IsDBNull(12) ? 0 : reader.GetInt32(12),
                                TotalTrustedPackages = reader.IsDBNull(13) ? 0 : reader.GetInt32(13),
                                TotalRejectedPackages = reader.IsDBNull(14) ? 0 : reader.GetInt32(14),
                                ExemptedPackages = reader.IsDBNull(15) ? 0 : reader.GetInt32(15),
                                TotalExemptedPackages = reader.IsDBNull(16) ? 0 : reader.GetInt32(16),
                                UnknownPackages = reader.IsDBNull(17) ? 0 : reader.GetInt32(17),
                                TotalUnknownPackages = reader.IsDBNull(18) ? 0 : reader.GetInt32(18),
                                LatestPackagePrerelease = reader.IsDBNull(19) ? 0 : reader.GetInt32(19),
                                TotalUnlistedPackages = reader.IsDBNull(20) ? 0 : reader.GetInt32(20),
                                PackagesWithPackageSource = reader.IsDBNull(21) ? 0 : reader.GetInt32(21),
                                PackagesPassingVerification = reader.IsDBNull(22) ? 0 : reader.GetInt32(22),
                                PackagesFailingVerification = reader.IsDBNull(23) ? 0 : reader.GetInt32(23),
                                PackagesPassingValidation = reader.IsDBNull(24) ? 0 : reader.GetInt32(24),
                                PackagesFailingValidation = reader.IsDBNull(25) ? 0 : reader.GetInt32(25),
                                PackagesCached = reader.IsDBNull(26) ? 0 : reader.GetInt32(26),
                                TotalPackagesCached = reader.IsDBNull(27) ? 0 : reader.GetInt32(27),
                                PackagesCachedAvailable = reader.IsDBNull(28) ? 0 : reader.GetInt32(28),
                                TotalPackagesCachedAvailable = reader.IsDBNull(29) ? 0 : reader.GetInt32(29),
                                PackagesCachedInvestigate = reader.IsDBNull(30) ? 0 : reader.GetInt32(30),
                                TotalPackagesCachedInvestigate = reader.IsDBNull(31) ? 0 : reader.GetInt32(31),
                                PackagesScanned = reader.IsDBNull(32) ? 0 : reader.GetInt32(32),
                                TotalPackagesScanned = reader.IsDBNull(33) ? 0 : reader.GetInt32(33),
                                PackagesScannedNotFlagged = reader.IsDBNull(34) ? 0 : reader.GetInt32(34),
                                TotalPackagesScannedNotFlagged = reader.IsDBNull(35) ? 0 : reader.GetInt32(35),
                                PackagesScannedFlagged = reader.IsDBNull(36) ? 0 : reader.GetInt32(36),
                                TotalPackagesScannedFlagged = reader.IsDBNull(37) ? 0 : reader.GetInt32(37),
                                PackagesScannedExempted = reader.IsDBNull(38) ? 0 : reader.GetInt32(38),
                                TotalPackagesScannedExempted = reader.IsDBNull(39) ? 0 : reader.GetInt32(39),
                                PackagesScannedInvestigate = reader.IsDBNull(40) ? 0 : reader.GetInt32(40),
                                TotalPackagesScannedInvestigate = reader.IsDBNull(41) ? 0 : reader.GetInt32(41),
                                TotalFileScanOverlaps = reader.IsDBNull(42) ? 0 : reader.GetInt32(42),
                                TotalFileScans = reader.IsDBNull(43) ? 0 : reader.GetInt32(43),
                            };
                        }
                    }
                }
            }));
        }
Пример #30
0
 public PackageSource(EntitiesContext entitiesContext)
 {
     _packageSet = new EntityRepository<Package>(entitiesContext);
 }
 public ReadOnlyEntitiesContext(DbConnection connection)
 {
     _entitiesContext = new EntitiesContext(connection, readOnly: true);
 }
Пример #32
0
        public override void Load()
        {
            IConfiguration configuration = new Configuration();
            Bind<IConfiguration>()
                .ToMethod(context => configuration);

            Lazy<GallerySetting> gallerySetting = new Lazy<GallerySetting>(() =>
            {
                using (var entitiesContext = new EntitiesContext())
                {
                    var settingsRepo = new EntityRepository<GallerySetting>(entitiesContext);
                    return settingsRepo.GetAll().FirstOrDefault();
                }
            });

            Bind<GallerySetting>().ToMethod(c => gallerySetting.Value);

            Bind<ISearchService>()
                .To<LuceneSearchService>()
                .InRequestScope();

            Bind<IEntitiesContext>()
                .ToMethod(context => new EntitiesContext())
                .InRequestScope();

            Bind<IEntityRepository<User>>()
                .To<EntityRepository<User>>()
                .InRequestScope();

            Bind<IEntityRepository<PackageRegistration>>()
                .To<EntityRepository<PackageRegistration>>()
                .InRequestScope();

            Bind<IEntityRepository<Package>>()
                .To<EntityRepository<Package>>()
                .InRequestScope();

            Bind<IEntityRepository<PackageAuthor>>()
                .To<EntityRepository<PackageAuthor>>()
                .InRequestScope();

            Bind<IEntityRepository<PackageDependency>>()
                .To<EntityRepository<PackageDependency>>()
                .InRequestScope();

            Bind<IEntityRepository<PackageStatistics>>()
                .To<EntityRepository<PackageStatistics>>()
                .InRequestScope();

            Bind<IUserService>()
                .To<UserService>()
                .InRequestScope();

            Bind<IPackageService>()
                .To<PackageService>()
                .InRequestScope();

            Bind<ICryptographyService>()
                .To<CryptographyService>()
                .InRequestScope();

            Bind<IFormsAuthenticationService>()
                .To<FormsAuthenticationService>()
                .InSingletonScope();

            Bind<IControllerFactory>()
                .To<NuGetControllerFactory>()
                .InRequestScope();

            Bind<IIndexingService>()
                .To<LuceneIndexingService>()
                .InRequestScope();

            Bind<INuGetExeDownloaderService>()
                .To<NuGetExeDownloaderService>()
                .InRequestScope();

            Lazy<IMailSender> mailSenderThunk = new Lazy<IMailSender>(() =>
            {
                var settings = Kernel.Get<GallerySetting>();
                if (settings.UseSmtp)
                {
                    var mailSenderConfiguration = new MailSenderConfiguration()
                    {
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        Host = settings.SmtpHost,
                        Port = settings.SmtpPort,
                        EnableSsl = configuration.SmtpEnableSsl,
                    };

                    if (!String.IsNullOrWhiteSpace(settings.SmtpUsername))
                    {
                        mailSenderConfiguration.UseDefaultCredentials = false;
                        mailSenderConfiguration.Credentials = new NetworkCredential(
                            settings.SmtpUsername,
                            settings.SmtpPassword);
                    }

                    return new MailSender(mailSenderConfiguration);
                }
                else
                {
                    var mailSenderConfiguration = new MailSenderConfiguration()
                    {
                        DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory,
                        PickupDirectoryLocation = HostingEnvironment.MapPath("~/App_Data/Mail")
                    };

                    return new MailSender(mailSenderConfiguration);
                }
            });

            Bind<IMailSender>()
                .ToMethod(context => mailSenderThunk.Value);

            Bind<IMessageService>()
                .To<MessageService>();

            Bind<IPrincipal>().ToMethod(context => HttpContext.Current.User);

            switch (configuration.PackageStoreType)
            {
                case PackageStoreType.FileSystem:
                case PackageStoreType.NotSpecified:
                    Bind<IFileSystemService>()
                        .To<FileSystemService>()
                        .InSingletonScope();
                    Bind<IFileStorageService>()
                        .To<FileSystemFileStorageService>()
                        .InSingletonScope();
                    break;
                case PackageStoreType.AzureStorageBlob:
                    Bind<ICloudBlobClient>()
                        .ToMethod(context => new CloudBlobClientWrapper(new CloudBlobClient(
                            new Uri(configuration.AzureStorageBlobUrl, UriKind.Absolute),
                            new StorageCredentialsAccountAndKey(configuration.AzureStorageAccountName, configuration.AzureStorageAccessKey))))
                        .InSingletonScope();
                    Bind<IFileStorageService>()
                        .To<CloudBlobFileStorageService>()
                        .InSingletonScope();
                    break;
                case PackageStoreType.AmazonS3Storage:
                    Bind<IAmazonS3Client>()
                        .To<AmazonS3ClientWrapper>()
                        .InSingletonScope();
                    Bind<IFileStorageService>()
                        .To<AmazonS3FileStorageService>()
                        .InSingletonScope();
                    break;
            }

            Bind<IPackageFileService>()
                .To<PackageFileService>();

            Bind<IEntityRepository<PackageOwnerRequest>>()
                .To<EntityRepository<PackageOwnerRequest>>()
                .InRequestScope();

            Bind<IUploadFileService>()
                .To<UploadFileService>();

            // todo: bind all package curators by convention
            Bind<IAutomaticPackageCurator>()
                .To<WebMatrixPackageCurator>();
            Bind<IAutomaticPackageCurator>()
                .To<Windows8PackageCurator>();

            // todo: bind all commands by convention
            Bind<IAutomaticallyCuratePackageCommand>()
                .To<AutomaticallyCuratePackageCommand>()
                .InRequestScope();
            Bind<ICreateCuratedPackageCommand>()
                .To<CreateCuratedPackageCommand>()
                .InRequestScope();
            Bind<IDeleteCuratedPackageCommand>()
                .To<DeleteCuratedPackageCommand>()
                .InRequestScope();
            Bind<IModifyCuratedPackageCommand>()
                .To<ModifyCuratedPackageCommand>()
                .InRequestScope();

            // todo: bind all queries by convention
            Bind<ICuratedFeedByKeyQuery>()
                .To<CuratedFeedByKeyQuery>()
                .InRequestScope();
            Bind<ICuratedFeedByNameQuery>()
                .To<CuratedFeedByNameQuery>()
                .InRequestScope();
            Bind<ICuratedFeedsByManagerQuery>()
                .To<CuratedFeedsByManagerQuery>()
                .InRequestScope();
            Bind<IPackageRegistrationByKeyQuery>()
                .To<PackageRegistrationByKeyQuery>()
                .InRequestScope();
            Bind<IPackageRegistrationByIdQuery>()
                .To<PackageRegistrationByIdQuery>()
                .InRequestScope();
            Bind<IUserByUsernameQuery>()
                .To<UserByUsernameQuery>()
                .InRequestScope();

            Bind<IAggregateStatsService>()
                .To<AggregateStatsService>()
                .InRequestScope();
            Bind<IPackageIdsQuery>()
                .To<PackageIdsQuery>()
                .InRequestScope();
            Bind<IPackageVersionsQuery>()
                .To<PackageVersionsQuery>()
                .InRequestScope();


            BindChocolateySpecific();
        }
Пример #33
0
        private async Task <ActionResult> CreatePackageInternal()
        {
            // Get the user
            var user = GetCurrentUser();

            using (var packageStream = ReadPackageFromRequest())
                using (var packageToPush = new PackageReader(packageStream, leaveStreamOpen: false))
                {
                    NuspecReader nuspec = null;
                    try
                    {
                        nuspec = packageToPush.GetNuspecReader();
                    }
                    catch (Exception ex)
                    {
                        return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, string.Format(
                                                                    CultureInfo.CurrentCulture,
                                                                    Strings.UploadPackage_InvalidNuspec,
                                                                    ex.Message)));
                    }

                    if (nuspec.GetMinClientVersion() > Constants.MaxSupportedMinClientVersion)
                    {
                        return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, string.Format(
                                                                    CultureInfo.CurrentCulture,
                                                                    Strings.UploadPackage_MinClientVersionOutOfRange,
                                                                    nuspec.GetMinClientVersion())));
                    }

                    // Ensure that the user can push packages for this partialId.
                    var packageRegistration = PackageService.FindPackageRegistrationById(nuspec.GetId());
                    if (packageRegistration != null)
                    {
                        if (!packageRegistration.IsOwner(user))
                        {
                            return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Forbidden, Strings.ApiKeyNotAuthorized));
                        }

                        // Check if a particular Id-Version combination already exists. We eventually need to remove this check.
                        string normalizedVersion = nuspec.GetVersion().ToNormalizedString();
                        bool   packageExists     =
                            packageRegistration.Packages.Any(
                                p => String.Equals(
                                    p.NormalizedVersion,
                                    normalizedVersion,
                                    StringComparison.OrdinalIgnoreCase));

                        if (packageExists)
                        {
                            return(new HttpStatusCodeWithBodyResult(
                                       HttpStatusCode.Conflict,
                                       String.Format(CultureInfo.CurrentCulture, Strings.PackageExistsAndCannotBeModified,
                                                     nuspec.GetId(), nuspec.GetVersion().ToNormalizedStringSafe())));
                        }
                    }

                    var packageStreamMetadata = new PackageStreamMetadata
                    {
                        HashAlgorithm = Constants.Sha512HashAlgorithmId,
                        Hash          = CryptographyService.GenerateHash(packageStream.AsSeekableStream()),
                        Size          = packageStream.Length,
                    };

                    var package = PackageService.CreatePackage(packageToPush, packageStreamMetadata, user, commitChanges: false);
                    AutoCuratePackage.Execute(package, packageToPush, commitChanges: false);
                    EntitiesContext.SaveChanges();

                    using (Stream uploadStream = packageStream)
                    {
                        uploadStream.Position = 0;
                        await PackageFileService.SavePackageFileAsync(package, uploadStream.AsSeekableStream());

                        IndexingService.UpdatePackage(package);
                    }
                }

            return(new HttpStatusCodeResult(HttpStatusCode.Created));
        }
Пример #34
0
        public override void Load()
        {
            IConfiguration configuration = new Configuration();
            Bind<IConfiguration>()
                .ToMethod(context => configuration);

            Lazy<GallerySetting> gallerySetting = new Lazy<GallerySetting>(() =>
            {
                using (var entitiesContext = new EntitiesContext())
                {
                    var settingsRepo = new EntityRepository<GallerySetting>(entitiesContext);
                    return settingsRepo.GetAll().FirstOrDefault();
                }
            });

            Bind<GallerySetting>().ToMethod(c => gallerySetting.Value);

            Bind<EntitiesContext>()
                .ToMethod(context => new EntitiesContext())
                .InRequestScope();

            Bind<IEntityRepository<User>>()
                .To<EntityRepository<User>>()
                .InRequestScope();

            Bind<IEntityRepository<PackageRegistration>>()
                .To<EntityRepository<PackageRegistration>>()
                .InRequestScope();

            Bind<IEntityRepository<Package>>()
                .To<EntityRepository<Package>>()
                .InRequestScope();

            Bind<IEntityRepository<PackageAuthor>>()
                .To<EntityRepository<PackageAuthor>>()
                .InRequestScope();

            Bind<IEntityRepository<PackageDependency>>()
                .To<EntityRepository<PackageDependency>>()
                .InRequestScope();

            Bind<IEntityRepository<PackageStatistics>>()
                .To<EntityRepository<PackageStatistics>>()
                .InRequestScope();

            Bind<IUserService>()
                .To<UserService>()
                .InRequestScope();

            Bind<IPackageService>()
                .To<PackageService>()
                .InRequestScope();

            Bind<ICryptographyService>()
                .To<CryptographyService>()
                .InRequestScope();

            Bind<IFormsAuthenticationService>()
                .To<FormsAuthenticationService>()
                .InSingletonScope();

            Bind<IControllerFactory>()
                .To<NuGetControllerFactory>()
                .InRequestScope();

            Lazy<IMailSender> mailSenderThunk = new Lazy<IMailSender>(() =>
            {
                var settings = Kernel.Get<GallerySetting>();
                if (settings.UseSmtp)
                {
                    var mailSenderConfiguration = new MailSenderConfiguration()
                    {
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        Host = settings.SmtpHost,
                        Port = settings.SmtpPort,
                        EnableSsl = true,
                        UseDefaultCredentials = false,
                        Credentials = new NetworkCredential(
                            settings.SmtpUsername,
                            settings.SmtpPassword)
                    };

                    return new MailSender(mailSenderConfiguration);
                }
                else
                {
                    var mailSenderConfiguration = new MailSenderConfiguration()
                    {
                        DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory,
                        PickupDirectoryLocation = HostingEnvironment.MapPath("~/App_Data/Mail")
                    };

                    return new MailSender(mailSenderConfiguration);
                }
            });

            Bind<IMailSender>()
                .ToMethod(context => mailSenderThunk.Value);

            Bind<IMessageService>()
                .To<MessageService>();

            Bind<IPrincipal>().ToMethod(context => HttpContext.Current.User);

            switch (configuration.PackageStoreType)
            {
                case PackageStoreType.FileSystem:
                case PackageStoreType.NotSpecified:
                    Bind<IFileSystemService>()
                        .To<FileSystemService>()
                        .InSingletonScope();
                    Bind<IFileStorageService>()
                        .To<FileSystemFileStorageService>()
                        .InSingletonScope();
                    break;
                case PackageStoreType.AzureStorageBlob:
                    Bind<ICloudBlobClient>()
                        .ToMethod(context => new CloudBlobClientWrapper(new CloudBlobClient(
                            new Uri(configuration.AzureStorageBlobUrl, UriKind.Absolute),
                            new StorageCredentialsAccountAndKey(configuration.AzureStorageAccountName, configuration.AzureStorageAccessKey))))
                        .InSingletonScope();
                    Bind<IFileStorageService>()
                        .To<CloudBlobFileStorageService>()
                        .InSingletonScope();
                    break;
            }

            Bind<IPackageFileService>()
                .To<PackageFileService>();

            Bind<IEntityRepository<PackageOwnerRequest>>()
                .To<EntityRepository<PackageOwnerRequest>>()
                .InRequestScope();

            Bind<IUploadFileService>()
                .To<UploadFileService>();
        }
 private static List<PackageIndexEntity> GetPackages(EntitiesContext context, DateTime? dateTime)
 {
     if (dateTime == null)
     {
         // If we're creating the index for the first time, fetch the new packages.
         string sql = @"Select p.[Key], pr.Id, p.Title, p.Description, p.Tags, p.FlattenedAuthors as Authors, p.[Key] as LatestKey
                  from Packages p join PackageRegistrations pr on p.PackageRegistrationKey = pr.[Key]
                  where p.IsLatestStable = 1 or (p.IsLatest = 1 and Not exists (Select 1 from Packages iP where iP.PackageRegistrationKey = p.PackageRegistrationKey and p.IsLatestStable = 1))";
         return context.Database.SqlQuery<PackageIndexEntity>(sql).ToList();
     }
     else
     {
         string sql = @"Select p.[Key], pr.Id, p.Title, p.Description, p.Tags, p.FlattenedAuthors as Authors,
                            LatestKey = CASE When p.IsLatest = 1 then p.[Key] Else (Select pLatest.[Key] from Packages pLatest where pLatest.PackageRegistrationKey = pr.[Key] and pLatest.IsLatest = 1) End
                            from Packages p join PackageRegistrations pr on p.PackageRegistrationKey = pr.[Key]
                            where p.LastUpdated > @UpdatedDate";
         return context.Database.SqlQuery<PackageIndexEntity>(sql, new SqlParameter("UpdatedDate", dateTime.Value)).ToList();
     }
 }