public void SetUp()
        {
            theRepository = EntityRepository.InMemory();
            theHash = new PasswordHash();

            theMembership = new MembershipRepository<User>(theRepository, theHash);
        }
 public void ShouldBeAbleToSaveAEntity()
 {
     var entityRepository = new EntityRepository(_session);
     var entity = new BusinessEntity { Name = "test" };
     entityRepository.Save(entity);
     entity.Id.Should().NotBeEmpty();
 }
        public void all_Licence_numbers_are_7_digit_integers()
        {
            var entities = new EntitiesContext();

            var siteRepository = new EntityRepository<Site>(entities);
            var licenceRepository = new EntityRepository<Licence>(entities);
            var antennaRepository = new EntityRepository<Antenna>(entities);

            ISiteService siteService = new SiteService(siteRepository, licenceRepository, antennaRepository);

            var licences = siteService.GetLicences();
            foreach (var licence in licences)
            {
                int n;
                int.TryParse(licence.SpectrumLicence, out n);

                var s = n.ToString();
                var target = s.Length;
                //if (digitCount != 7)
                //{
                    //this.TestContext.WriteLine("\tInvalid Licence Number: " + s);
                    //throw new ApplicationException("\tInvalid Licence Number: " + s);
                //}
                Assert.AreEqual(7, target);
            }
        }
            public TestableCuratedPackagesController()
            {
                Fakes = new Fakes();

                StubCuratedFeed = new CuratedFeed
                    { Key = 0, Name = "aFeedName", Managers = new HashSet<User>(new[] { Fakes.User }) };
                StubPackageRegistration = new PackageRegistration { Key = 0, Id = "anId" };

                OwinContext = Fakes.CreateOwinContext();

                EntitiesContext = new FakeEntitiesContext();
                EntitiesContext.CuratedFeeds.Add(StubCuratedFeed);
                EntitiesContext.PackageRegistrations.Add(StubPackageRegistration);

                var curatedFeedRepository = new EntityRepository<CuratedFeed>(
                    EntitiesContext);

                var curatedPackageRepository = new EntityRepository<CuratedPackage>(
                    EntitiesContext);

                base.CuratedFeedService = new CuratedFeedService(
                    curatedFeedRepository,
                    curatedPackageRepository);

                var httpContext = new Mock<HttpContextBase>();
                TestUtility.SetupHttpContextMockForUrlGeneration(httpContext, this);
            }
        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 void GetCountries_Should_Get_Expected_Result() { 
            
            // Arrange

            var countries = new List<Country>() { 
                new Country { Id = 1, Name = "Turkey", ISOCode = "TR", CreatedOn = DateTimeOffset.Now },
                new Country { Id = 2, Name = "United Kingdom", ISOCode = "EN", CreatedOn = DateTimeOffset.Now },
                new Country { Id = 3, Name = "United States", ISOCode = "US", CreatedOn = DateTimeOffset.Now },
                new Country { Id = 4, Name = "Argentina", ISOCode = "AR", CreatedOn = DateTimeOffset.Now },
                new Country { Id = 4, Name = "Bahamas", ISOCode = "BS", CreatedOn = DateTimeOffset.Now },
                new Country { Id = 4, Name = "Uruguay", ISOCode = "UY", CreatedOn = DateTimeOffset.Now }
            };
            var dbSet = new FakeDbSet<Country>();
            foreach (var country in countries) {
                dbSet.Add(country);
            }

            var entitiesContext = new Mock<IEntitiesContext>();
            entitiesContext.Setup(ec => ec.Set<Country>()).Returns(dbSet);
            var countriesRepo = new EntityRepository<Country>(entitiesContext.Object);
            var countriesController = new CountriesController(countriesRepo, Mapper.Engine);
            var pageIndex = 1;
            var pageSize = 3;

            // Act
            var paginatedDto = countriesController.GetCountries(pageIndex, pageSize);

            // Assert
            Assert.NotNull(paginatedDto);
            Assert.Equal(countries.Count, paginatedDto.TotalCount);
            Assert.Equal(pageSize, paginatedDto.PageSize);
            Assert.Equal(pageIndex, paginatedDto.PageIndex);
        }
        public void Can_Validate_Station_Data()
        {
            var entities = new EntitiesContext();

            var siteRepository = new EntityRepository<Site>(entities);
            var licenceRepository = new EntityRepository<Licence>(entities);
            var antennaRepository = new EntityRepository<Antenna>(entities);

            ISiteService siteService = new SiteService(siteRepository, licenceRepository, antennaRepository);

            XNamespace ns = "http://sd.ic.gc.ca/SLDR_Schema_Definition_en";

            IEnumerable<XElement> spectrum_licences = siteService
                .GetLicences()
                .ToList()
                .Where(x => x.Antennas.Any())
                .OrderBy(x => x.SpectrumLicence)
                //.Take(3)
                .Select(x => new XElement("spectrum_licence",
                    new XElement("licence_number", x.SpectrumLicence),
                    new XElement("office_number", 7),
                    new XElement("company_code", x.CompanyCode),
                    new XElement("reference_number", x.ReferenceNumber),
                    new XElement("contact_name", x.ContactName),
                    new XElement("business_telephone", x.Phone),
                    new XElement("extension", x.PhoneExt),
                    new XElement("email_address", x.Email),
                    getStations(x)
                ));

            XDocument doc = new XDocument(new XElement("spectrum_licence_data_registry", spectrum_licences));

            foreach (XElement e in doc.Root.DescendantsAndSelf())
            {
                if (e.Name.Namespace == "")
                    e.Name = ns + e.Name.LocalName;
            }

            XmlReaderSettings sldrSettings = new XmlReaderSettings();
            sldrSettings.Schemas.Add(ns.NamespaceName, @"c:\temp\SLDR_Schema_Definition_en.xsd");
            sldrSettings.ValidationType = ValidationType.Schema;
            sldrSettings.ValidationEventHandler += new ValidationEventHandler(validationCallBack);

            //using (MemoryStream stream = new MemoryStream())
            using (FileStream stream = new FileStream(@"c:\temp\Silo_Station_Data.xml", FileMode.Create, FileAccess.ReadWrite))
            {
                StreamWriter writer = new StreamWriter(stream, Encoding.Default);
                doc.Save(writer);

                stream.Flush();
                stream.Seek(0, SeekOrigin.Begin);

                XmlReader data = XmlReader.Create(stream, sldrSettings);

                while (data.Read()) { }
            }

            Assert.IsNotNull(doc);
        }
 public void SetUp()
 {
     _fixture = new Fixture().Customize(new AutoMoqCustomization());
     _dataContext = new Mock<IDataContext>();
     _dbSet = new Mock<DbSet<FakeAnswer>>();
     _dataContext.Setup(m => m.Set<FakeAnswer>()).Returns(_dbSet.Object);
     _sut = new EntityRepository<FakeAnswer>(_dataContext.Object);
 }
Esempio n. 9
0
 /// <summary>
 /// Initialize.
 /// </summary>
 /// <param name="repo"></param>
 public LogEntryService(string logname, int bufferLevel)
 {
     LogEntryMapper mapper = new LogEntryMapper();
     mapper.Init();
     _repo = new EntityRepositoryXml<LogEntry>(mapper);
     _repo.SetFileName(logname);
     _items = new List<LogEntry>();
     _bufferLevel = bufferLevel;
 }
        public void SavingAnExistingEntityShouldNotChangeId()
        {
            var entity = new BusinessEntity { Name = "test" };
            _session.Store(entity);
            _session.SaveChanges();

            var entityRepository = new EntityRepository(_session);
            var entityGet = entityRepository.GetSingle<BusinessEntity>(x => x.Name == Entityname);
            entityRepository.Save(entityGet);
            entityGet.Id.Should().Be(entity.Id);
        }
        public void Init(HttpApplication context) {

            MasterEntities entitiesCtx = new MasterEntities();
            IEntityRepository<Tenant, Guid> tenantRepository = new EntityRepository<Tenant, Guid>(entitiesCtx);
            try {
                ValidateRequest(new HttpContextWrapper(context.Context), tenantRepository);
            }
            catch (HttpException) // will throw at the app start-up
            { 
            }
        }
        public void ShouldBeAbleToGetAllEntitys()
        {
            var entity1 = new BusinessEntity { Name = "test" };
            var entity2 = new BusinessEntity { Name = "test" };
            _session.Store(entity1);
            _session.Store(entity2);
            _session.SaveChanges();

            var entityRepository = new EntityRepository(_session);
            var entitys = entityRepository.GetAll<BusinessEntity>();
            entitys.Count.Should().Be(2);
        }
            public TestableCuratedPackagesController()
            {
                StubCuratedFeed = new CuratedFeed
                    { Key = 0, Name = "aFeedName", Managers = new HashSet<User>(new[] { Fakes.User }) };
                StubPackageRegistration = new PackageRegistration { Key = 0, Id = "anId" };
                StubPackage = new Package
                {
                    Key = 34,
                    PackageRegistration = StubPackageRegistration,
                    PackageRegistrationKey = StubPackageRegistration.Key,
                    Version = "1.0.0"
                };
                StubLatestPackage = new Package
                {
                    Key = 42,
                    PackageRegistration = StubPackageRegistration,
                    PackageRegistrationKey = StubPackageRegistration.Key,
                    Version = "2.0.1-alpha",
                    IsLatest = true,
                    IsPrerelease = true
                };
                StubLatestStablePackage = new Package
                {
                    Key = 41,
                    PackageRegistration = StubPackageRegistration,
                    PackageRegistrationKey = StubPackageRegistration.Key,
                    Version = "2.0.0",
                    IsLatestStable = true
                };

                OwinContext = Fakes.CreateOwinContext();

                EntitiesContext = new FakeEntitiesContext();
                EntitiesContext.CuratedFeeds.Add(StubCuratedFeed);
                EntitiesContext.PackageRegistrations.Add(StubPackageRegistration);

                StubPackageRegistration.Packages.Add(StubPackage);
                StubPackageRegistration.Packages.Add(StubLatestPackage);
                StubPackageRegistration.Packages.Add(StubLatestStablePackage);

                var curatedFeedRepository = new EntityRepository<CuratedFeed>(
                    EntitiesContext);

                var curatedPackageRepository = new EntityRepository<CuratedPackage>(
                    EntitiesContext);

                base.CuratedFeedService = new CuratedFeedService(
                    curatedFeedRepository,
                    curatedPackageRepository);

                var httpContext = new Mock<HttpContextBase>();
                TestUtility.SetupHttpContextMockForUrlGeneration(httpContext, this);
            }
 private void AddEvent(ObjectId id, int statusCode)
 {
     var repository = new EntityRepository();
     var entity = repository.Get(id);
     entity.StatusCode = statusCode;
     entity.Events.Add(new EntityEvent
     {
         CreatedAt = DateTime.Now,
         Description = Guid.NewGuid().ToString(),
         StatusCode = statusCode
     });
     repository.Save(entity);
 }
        public void ShouldBeAbleToRetrieveAEntity()
        {
            var entity = new BusinessEntity { Name = "test" };
            _session.Store(entity);
            _session.SaveChanges();

            var entityRepository = new EntityRepository(_session);
            var getEntity = entityRepository.GetSingle<BusinessEntity>(x => x.Name == Entityname);
            
            AssertAll.Succeed(
                () => Assert.IsNotNullOrEmpty(getEntity.Id, "Id should be retrieved"),
                () => Assert.IsNotNullOrEmpty(getEntity.Name, "Password should be retrieved")
            );
        }
        public void GetAll_Should_Call_Set_Once_And_Get_Expected_Amount_Of_Entities()
        {
            // Arrange
            var people = GetDummyPeople(2);
            var personDbSet = GetPersonDbSet(people);
            var peopleContextMock = new Mock<IPeopleContext>();
            peopleContextMock.Setup(pc => pc.Set<Person>()).Returns(personDbSet);
            var entityRepository = new EntityRepository<Person>(peopleContextMock.Object);

            // Act
            IEnumerable<Person> peopleResult = entityRepository.GetAll().ToList();

            // Assert
            Assert.Equal(personDbSet.Count(), peopleResult.Count());
        }
Esempio n. 17
0
        public void RollbackTest()
        {
            // Add a new thing, but rollback xn.
            using (RepositoryTransaction rt = EntityRepository.BeginTransaction())
            {
                ThingRepo.Save(new Thing()
                {
                    Name = "TestThing", Corners = 1
                });
                rt.Rollback();
            }

            // Check thing wasn't saved
            Assert.AreEqual(0, ThingRepo.GetAll().Count, "Thing should not be saved");
        }
Esempio n. 18
0
 /// <summary>
 /// دلیل استفاده از این سرویس این است که واسط کاربر باید درختی از پیشکارتها را نمایش دهد
 /// و بدلیل محدودیتها جاوا اسکریپت مجبوریم شمای درخت را در سرویس دریافت و آنرا تحلیل کنیم
 /// </summary>
 /// <param name="name">نام گروه دسترسی</param>
 /// <param name="description">توضیح</param>
 /// <param name="accessGroupList">لیست پیکارتها که از درخت استخراج شده است</param>
 public decimal InsertByProxy(string name, string description, IList <AccessGroupProxy> accessGroupList)
 {
     try
     {
         EntityRepository <PrecardGroups> groupRep = new EntityRepository <PrecardGroups>(false);
         IList <Precard>    removeList             = new List <Precard>();
         PrecardAccessGroup accessGroup            = new PrecardAccessGroup();
         accessGroup.Name        = name;
         accessGroup.Description = description;
         accessGroup.PrecardList = new List <Precard>();
         foreach (AccessGroupProxy proxy in accessGroupList)
         {
             if (proxy.IsParent)
             {
                 PrecardGroups group = groupRep.GetById(proxy.ID, false);
                 foreach (Precard p in group.PrecardList)
                 {
                     accessGroup.PrecardList.Add(p);
                 }
             }
             else if (proxy.Checked)
             {
                 accessGroup.PrecardList.Add(new Precard()
                 {
                     ID = proxy.ID
                 });
             }
             else
             {
                 removeList.Add(new Precard()
                 {
                     ID = proxy.ID
                 });
             }
         }
         foreach (Precard p in removeList)
         {
             accessGroup.PrecardList.Remove(p);
         }
         SaveChanges(accessGroup, UIActionType.ADD);
         return(accessGroup.ID);
     }
     catch (Exception ex)
     {
         LogException(ex, "BPrecardAccessGroup", "InsertByProxy");
         throw ex;
     }
 }
        public static void Test()
        {
            // ---------------------------------------------------------------------------------------------------
            // If you want to build a DB Context from an existing database:
            // Install-Package Microsoft.EntityFrameworkCore.Tools
            // Sqlite: Scaffold-DbContext "DataSource=test.db" Microsoft.EntityFrameworkCore.Sqlite -OutputDir "NewFolder"
            // Postgre: Scaffold-DbContext "User ID=postgres;Password=secret;Server=localhost;Port=5432;Database=test;Integrated Security = true;Pooling = true" Npgsql.EntityFrameworkCore.PostgreSQL -OutputDir "NewFolder"
            // ---------------------------------------------------------------------------------------------------

            /* Option 1 - Pass options using builder
             * var optBuilder = new DbContextOptionsBuilder<testContext>();
             * optBuilder.UseSqlite("DataSource=test.db");
             * var dbCtxFactory = new DbContextFactory<testContext>(optBuilder.Options);*/

            // Option 2 - Pass connection string
            //var dbCtxFactory = new DbContextFactory<testContext>(DatabaseEnums.POSTGRESQL, "User ID=postgres;Password=secret;Server=localhost;Port=5432;Database=test;Integrated Security = true;Pooling = true");
            var dbCtxFactory = new DbContextFactory <testContext>(DatabaseEnums.SQLITE, "DataSource=test.db");
            //IEntityStore<Person> personStore = new AuditableRepository<Person>(dbCtxFactory, httpContextAccessor: null);

            // Entity repository does physical delete and also does not have audit fields (updatedby, deletedon, ..)
            IEntityStore <Person> personStore = new EntityRepository <Person>(dbCtxFactory);
            // This factory and store can be moved to dependency injectors

            var me = new Person {
                Age = 30
            };

            personStore.SaveOrUpdate(me);

            var notClone = personStore.Get(me.Id);

            notClone.Age = 18;
            personStore.SaveOrUpdate(notClone);

            try
            {
                me.Age = 17;
                personStore.SaveOrUpdate(me);
            }
            catch (StaleDataException e)
            {
                // Message explains a more recent item exists (bigger Version number) so updating might lose data
                Console.WriteLine(e.Message);
            }

            personStore.Delete(notClone);
            personStore.DeleteAll();
        }
Esempio n. 20
0
        public void DirectMigrationTest()
        {
            ConsoleLogger.LogLevel = 5;

            var orgService = ConnectionHelper.GetOrganizationSprintAutoTest();
            var repo       = new EntityRepository(orgService, new ServiceRetryExecutor());

            List <string> fetchXMLQueries = new List <string>
            {
                "<fetch><entity name=\"contact\" ><attribute name=\"ownerid\" /><filter>" +
                $"<condition attribute=\"ownerid\" operator=\"eq\" value=\"{sourceUserId}\" />" +
                "</filter></entity></fetch>"
            };

            var readerConfig = new CrmStoreReaderConfig(fetchXMLQueries)
            {
                BatchSize = 200,
                PageSize  = 200,
                TopCount  = 200
            };

            var writerConfig = new CrmStoreWriterConfig
            {
                SaveBatchSize = 200
            };

            Dictionary <Guid, Guid> contactMappings =
                new Dictionary <Guid, Guid>()
            {
                { sourceUserId, targetGuidId }
            };

            MappingConfiguration mappingConfig = new MappingConfiguration();

            mappingConfig.Mappings.Add("systemuser", contactMappings);

            var reader = new DataCrmStoreReader(logger, repo, readerConfig);
            var writer = new DataCrmStoreWriter(logger, repo, writerConfig);

            var migrator         = new GenericDataMigrator <Entity, EntityWrapper>(logger, reader, writer);
            var mappingProcessor = new MapEntityProcessor(mappingConfig, logger, repo);

            migrator.AddProcessor(mappingProcessor);

            FluentActions.Invoking(() => migrator.MigrateData())
            .Should()
            .NotThrow();
        }
Esempio n. 21
0
        /// <inheritdoc cref="IUserService.RegisterAsync(RegisterRequest)"/>
        public async Task <RegisterResponse> RegisterAsync(RegisterRequest registerRequest)
        {
            if (string.IsNullOrEmpty(registerRequest.Password))
            {
                return(new RegisterResponse(registerRequest.Id, message: "Credentials are null or empty."));
            }

            if (await EntityRepository.ExistsAsync(anyUser => anyUser.Username == registerRequest.Username))
            {
                return(new RegisterResponse(registerRequest.Id, message: "Username already exists."));
            }

            if (!await _credentialTypeRepository.ExistsAsync(ct => ct.Code == registerRequest.CredentialTypeCode))
            {
                return(new RegisterResponse(registerRequest.Id, message: "CredentialType not found."));
            }

            User user = new User
            {
                Username         = registerRequest.Username,
                TimestampCreated = DateTime.UtcNow
            };

            (bool createdSuccess, _) = await EntityRepository.CreateAsync(user);

            if (!createdSuccess)
            {
                return(new RegisterResponse(registerRequest.Id, "Failed to persist data."));
            }

            CredentialType credentialType = await _credentialTypeRepository.FindSingleOrDefaultAsync(ct => ct.Code == registerRequest.CredentialTypeCode);

            byte[]     salt       = _saltGenerator.GenerateSalt();
            Credential credential = new Credential
            {
                UserId           = user.Id,
                CredentialTypeId = credentialType.Id,
                Identifier       = registerRequest.Username,
                Secret           = _hasher.Hash(registerRequest.Password, salt),
                Extra            = Convert.ToBase64String(salt)
            };

            (bool success, _) = await _credentialRepository.CreateAsync(credential);

            return(!success
                ? new RegisterResponse(registerRequest.Id, "Failed to persist data.")
                : new RegisterResponse(registerRequest.Id, "Registration successful!", true));
        }
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {

            HttpContextBase httpContext = request.Properties["MS_HttpContext"] as HttpContextBase;
            MasterEntities entitiesCtx = new MasterEntities();
            IEntityRepository<Tenant, Guid> tenantRepository = new EntityRepository<Tenant, Guid>(entitiesCtx);

            ValidateRequest(httpContext, tenantRepository);

            var tenant = httpContext.Items["App:Tenant"] as string;
            if (tenant == null) {

                return Task.FromResult(request.CreateResponse(HttpStatusCode.NotFound));
            }

            return base.SendAsync(request, cancellationToken);
        }
Esempio n. 23
0
 public SyncService(
     ResolverFactory resolverFactory,
     EntityRepository entityRepository,
     AttributeRepository attributeRepository,
     IWorkflowHost host,
     IEnumerable <IBaseWorkflow> workflows)
 {
     _logger                  = resolverFactory.Resolve <ILogger>("SyncService");
     _errorLogger             = resolverFactory.Resolve <ILogger>("Error");
     this.resolverFactory     = resolverFactory;
     this.entityRepository    = entityRepository;
     this.attributeRepository = attributeRepository;
     _host          = host;
     this.workflows = workflows;
     //RegisterWorkflows();
 }
Esempio n. 24
0
        public virtual void Purge(int id)
        {
            try
            {
                EntityRepository <T> .Purge(id);
            }
            catch (System.Exception ex)
            {
                bool reThrow = ExceptionHandler.HandleBusinessLogicLayerException(ex);

                if (reThrow)
                {
                    throw;
                }
            }
        }
Esempio n. 25
0
        public virtual IActionResult Delete(int id)
        {
            var entity = EntityRepository.Db.Find <T>(id);

            if (entity == null)
            {
                return(NotFound());
            }

            EntityRepository.Db.Remove(entity);
            EntityRepository.SaveChanges();

            EntityRepository.Db.RecordedActivities.Add(new RecordedActivity(ActivityOperation.Delete.ToString(), "Deletes an entity", GetUser(HttpContext.User), "", $"Deleted entity with id of {id}", DateTimeOffset.UtcNow, entity.Id, GetUnderlyingEntityType <T>()));
            EntityRepository.SaveChanges();
            return(new NoContentResult());
        }
Esempio n. 26
0
        public void GetCommentsList_Valid(int postId)
        {
            // Arrange
            var repo = new EntityRepository(new TestStoreDbContext());
            CommentsController commentsController = new CommentsController(repo);

            // Act
            IHttpActionResult actionResult = commentsController.GetCommentsList(postId);
            var contentResult = actionResult as OkNegotiatedContentResult <List <Comment> >;

            // Assert
            Assert.IsType <OkNegotiatedContentResult <List <Comment> > >(actionResult);
            Assert.NotNull(contentResult.Content[0].Content);
            Assert.NotNull(contentResult.Content[0].Date);
            Assert.NotNull(contentResult.Content[0].PostId);
        }
Esempio n. 27
0
        /// <summary>
        /// توسط پرسنل استفاده نشده باشد
        /// </summary>
        /// <param name="dateRangeGroup"></param>
        protected override void DeleteValidate(CalculationRangeGroup dateRangeGroup)
        {
            UIValidationExceptions exception = new UIValidationExceptions();

            EntityRepository <PersonRangeAssignment> assgnRep = new EntityRepository <PersonRangeAssignment>();

            if (assgnRep.GetCountByCriteria(new CriteriaStruct(Utility.GetPropertyName(() => new PersonRangeAssignment().CalcDateRangeGroup), dateRangeGroup)) > 0)
            {
                exception.Add(new ValidationException(ExceptionResourceKeys.DateRangesUsedByPerson, "این دوره محاسبات توسط اشخاص استفاده شده است", ExceptionSrc));
            }

            if (exception.Count > 0)
            {
                throw exception;
            }
        }
Esempio n. 28
0
        /// <summary>
        ///     Verify that the current user is in the specified role.
        /// </summary>
        /// <param name="role">The security role.</param>
        /// <exception cref="PlatformSecurityException">Thrown if permission is denied.</exception>
        public void CheckUserInRole(IEntityRef role)
        {
            // Check user is in import/export role
            var userRoles = UserRoleRepository.GetUserRoles(RequestContext.UserId);


            if (!userRoles.Contains(role.Id))
            {
                string roleName;
                using (new SecurityBypassContext( ))
                {
                    roleName = EntityRepository.Get <Role>(role)?.Name ?? "specified";
                }
                throw new PlatformSecurityException($"Must be a member of the '{roleName}' role.");
            }
        }
Esempio n. 29
0
        public void TestAdd()
        {
            using (var repo = new EntityRepository(new DatabaseContext(_options)))
            {
                repo.Insert(new Entity()
                {
                    Name = "Naam"
                });
            }


            using (var repo = new EntityRepository(new DatabaseContext(_options)))
            {
                Assert.AreEqual(1, repo.Count());
            }
        }
Esempio n. 30
0
        private void CleanRepositories()
        {
            AuthorAlarmRepository authorAlarmRepository = new AuthorAlarmRepository();
            PhraseRepository      phraseRepository      = new PhraseRepository();
            EntityRepository      entityRepository      = new EntityRepository();
            SentimentRepository   sentimentRepository   = new SentimentRepository();
            AuthorRepository      authorRepository      = new AuthorRepository();
            AlarmRepository       alarmRepository       = new AlarmRepository();

            authorAlarmRepository.Clear();
            phraseRepository.Clear();
            entityRepository.Clear();
            sentimentRepository.Clear();
            authorRepository.Clear();
            alarmRepository.Clear();
        }
Esempio n. 31
0
        public override async Task <TDto?> InsertAsync(TInputDto dto)
        {
            if (!(await UserIsInGame()))
            {
                throw new UserPermissionException("Update permission denied");
            }
            TGameEntity entity = Mapper.Map <TInputDto, TGameEntity>(dto);
            int         gameId = _sessionService.GetCurrentGameId();

            entity.Game = await _gameService.GetById(gameId) ?? throw new ArgumentNullException(nameof(gameId));

            entity.GameId = gameId;
            await EntityRepository.InsertAsync(entity);

            return(Mapper.Map <TGameEntity, TDto>(entity));
        }
        public async Task ShouldAddIdToKeeperAtSaveChanges()
        {
            var work = new UnitOfWorkFactory <UnitOfWork>(_dbContext, _idsKeeper);
            var repo = new EntityRepository(_dbContext, _idsKeeper);

            var newCustomer = Bogus.CustomerFaker.Generate(1).Single();
            var unitOfWork  = work.Transact();

            {
                await repo.AddAsync(newCustomer);

                await unitOfWork.SaveAsync();
            }

            Assert.That(_idsKeeper.Get <Customer>().Contains(newCustomer.Id), Is.True);
        }
        public IActionResult DissassociateCustomEntity(int customEntityId, int investmentId)
        {
            var entityInvestmentLink = EntityRepository.Db.Find <CustomEntity_Investment>(investmentId, customEntityId);

            EntityRepository.Db.Remove(entityInvestmentLink);
            EntityRepository.SaveChanges();

            EntityRepository.Db.RecordedActivities.Add(new RecordedActivity(ActivityOperation.Update.ToString(),
                                                                            "Updates an existing entity", GetUser(HttpContext.User), "Dissassociated custom entity"
                                                                            , $"Dissassociated custom entity '{EntityRepository.GetEntityByType<CustomEntity>().Single(r => r.Id == customEntityId).Name}' with investment.",
                                                                            DateTimeOffset.UtcNow,
                                                                            investmentId, EntityType.Investment));
            EntityRepository.Db.SaveChanges();

            return(new NoContentResult());
        }
 public IActionResult AssociateRisks(int id, [FromBody] int[] riskIds)
 {
     foreach (var riskId in riskIds)
     {
         var riskInvestmentLink = new InvestmentRisk_Investment
         {
             InvestmentID     = id,
             InvestmentRiskID = riskId
         };
         EntityRepository.Db.Add(riskInvestmentLink);
         EntityRepository.Db.RecordedActivities.Add(new RecordedActivity(ActivityOperation.Update.ToString(), "Updates an entity", GetUser(HttpContext.User), "Associated risk", $"Associated risk '{EntityRepository.GetEntityByType<InvestmentRisk>().Single(r => r.Id == riskId).Name}' with investment.", DateTimeOffset.UtcNow,
                                                                         id, EntityType.Investment));
     }
     EntityRepository.SaveChanges();
     return(new NoContentResult());
 }
Esempio n. 35
0
        private static void ClearAllTreeIndex(EntityRepository repository)
        {
            var dp = repository.DataProvider as RdbDataProvider;

            if (dp == null)
            {
                throw new InvalidProgramException("TreeIndexHelper.ResetTreeIndex 方法只支持在关系数据库上使用。");
            }
            var table  = dp.DbTable;
            var column = table.Columns.First(c => c.Info.Property == Entity.TreeIndexProperty);

            using (var dba = dp.CreateDbAccesser())
            {
                dba.ExecuteText(string.Format("UPDATE {0} SET {1} = NULL", table.Name, column.Name));
            }
        }
 public IActionResult AssociateFactors(int id, [FromBody] int[] factorIds)
 {
     foreach (var factorId in factorIds)
     {
         var factorInvestmentLink = new InvestmentInfluenceFactor_Investment
         {
             InvestmentID = id,
             InvestmentInfluenceFactorID = factorId
         };
         EntityRepository.Db.Add(factorInvestmentLink);
         EntityRepository.Db.RecordedActivities.Add(new RecordedActivity(ActivityOperation.Update.ToString(), "Updates an entity", GetUser(HttpContext.User), "Associated factor", $"Associated factor '{EntityRepository.GetEntityByType<InvestmentInfluenceFactor>().Single(f => f.Id == factorId).Name}' with investment.", DateTimeOffset.UtcNow,
                                                                         id, EntityType.Investment));
     }
     EntityRepository.SaveChanges();
     return(new NoContentResult());
 }
Esempio n. 37
0
        /// <summary>
        /// - نباید مدیر در جریان کار استفاده شده باشد
        /// </summary>
        /// <param name="manager"></param>
        protected override void DeleteValidate(Manager manager)
        {
            UIValidationExceptions         exception = new UIValidationExceptions();
            EntityRepository <ManagerFlow> rep       = new EntityRepository <ManagerFlow>(false);
            int count = rep.GetCountByCriteria(new CriteriaStruct(Utility.GetPropertyName(() => new ManagerFlow().Manager), manager));

            if (count > 0)
            {
                exception.Add(new ValidationException(ExceptionResourceKeys.ManagerUsedByFlow, "مدیر در سلسله مراتب جریان کار استفاده شده است و امکان حذف آن نیست", ExceptionSrc));
            }

            if (exception.Count > 0)
            {
                throw exception;
            }
        }
        public void update_an_existing_case_should_replace_it()
        {
            var repository = EntityRepository.InMemory();
            var case1      = new FakeEntity();
            var case2      = new FakeEntity();

            repository.Update(case1);
            repository.All <FakeEntity>().Single().ShouldBeTheSameAs(case1);
            repository.Find <FakeEntity>(case1.Id).ShouldBeTheSameAs(case1);

            case2.Id = case1.Id;
            repository.Update(case2);

            repository.All <FakeEntity>().Single().ShouldBeTheSameAs(case2);
            repository.Find <FakeEntity>(case1.Id).ShouldBeTheSameAs(case2);
        }
Esempio n. 39
0
 public UpdateIndexChangesStep(
     ResolverFactory resolver,
     EntityRepository entityRepository,
     AttributeRepository attributeRepository,
     ConnectionRepository connectionRepository,
     IEnumerable <IPuller> pullers,
     IEnumerable <IIndexer> indexers,
     IndexerManager indexerManager) : base(resolver)
 {
     this.entityRepository     = entityRepository;
     this.attributeRepository  = attributeRepository;
     this.connectionRepository = connectionRepository;
     this.pullers        = pullers;
     this.indexers       = indexers;
     this.indexerManager = indexerManager;
 }
        public void CreateNewProblemWithoutTag()
        {
            IRepository <Problem> repository = new EntityRepository <Problem>(GetDbContext());
            var problem = new Problem
            {
                Title       = "Test",
                Description = "This is a test Problem",
                IsResolved  = false
            };

            Assert.True(repository.Insert(problem));

            var result = repository.GetAll(p => p.Title == "Test");

            Assert.True(result.Count() > 0);
        }
Esempio n. 41
0
        void entityRepository()
        {
            // Total components is kindly generated for you by the code generator
            var repo   = new EntityRepository(ComponentIds.TotalComponents);
            var entity = repo.CreateEntity();

            entity.isMovable = true;

            // Returns all entities having MoveComponent and PositionComponent. Matchers are also generated for you.
            var entities = repo.GetEntities(Matcher.AllOf(Matcher.Movable, Matcher.Position));

            foreach (var e in entities)
            {
                // do something
            }
        }
Esempio n. 42
0
        public async Task Add_Success(ToDoItem item)
        {
            //arrange
            CancellationToken    token       = new CancellationToken();
            Mock <ToDoDbContext> mockContext = new Mock <ToDoDbContext>();

            mockContext.Setup(x => x.Add(It.IsAny <ToDoItem>())).Verifiable();
            mockContext.Setup(x => x.SaveChangesAsync(token)).Returns(() => Task.Run(() => { return(1); })).Verifiable();
            EntityRepository <ToDoItem> repo = new EntityRepository <ToDoItem>(mockContext.Object);

            //act
            await repo.Add(item);

            //assert
            mockContext.VerifyAll();
        }
Esempio n. 43
0
        public override TResultDto Update <TDto, TResultDto>(TDto dto)
        {
            TEntity primaryEntity = null;

            if (dto is IPrimary <TKey> )
            {
                var id = (dto as IPrimary <TKey>).Id;
                primaryEntity = EntityRepository.GetById(id);
            }

            var entity = Mapper.Map(dto, primaryEntity);

            var updatedEntity = EntityRepository.Update(entity);

            return(Mapper.Map <TResultDto>(updatedEntity));
        }
Esempio n. 44
0
        public sealed override async Task <TResultDto> UpdateAsync <TDto, TResultDto>(TDto dto)
        {
            TEntity primaryEntity = null;

            if (dto is IPrimary <TKey> )
            {
                var id = (dto as IPrimary <TKey>).Id;
                primaryEntity = await EntityRepository.GetByIdAsync(id);
            }

            var entity = MapUpdatedEntity(dto, primaryEntity);

            var updatedEntity = await EntityRepository.UpdateAsync(entity);

            return(Mapper.Map <TResultDto>(updatedEntity));
        }
Esempio n. 45
0
        public void GetAll_Should_Call_Set_Once_And_Get_Expected_Amount_Of_Entities()
        {
            // Arrange
            var people            = GetDummyPeople(2);
            var personDbSet       = GetPersonDbSet(people);
            var peopleContextMock = new Mock <IPeopleContext>();

            peopleContextMock.Setup(pc => pc.Set <Person>()).Returns(personDbSet);
            var entityRepository = new EntityRepository <Person>(peopleContextMock.Object);

            // Act
            IEnumerable <Person> peopleResult = entityRepository.GetAll().ToList();

            // Assert
            Assert.Equal(personDbSet.Count(), peopleResult.Count());
        }
        public override async Task Update(ScheduledScan scan, Action onSuccess = null, Action <Exception> onException = null)
        {
            await Task.Factory.StartNew(() =>
            {
                using (var scansRepo = new EntityRepository <ScheduledScan>(_connection))
                {
                    var existingScan = scansRepo.GetAll().Where(s => s.Id == scan.Id).Include(s => s.Periods).Single();

                    var periodsToDelete = existingScan.Periods.Where(ep => !scan.Periods.Select(p => p.Id).Contains(ep.Id)).ToList();
                    var periodsToAdd    = scan.Periods.Where(p => p.Scan == null).ToList();

                    if (periodsToDelete.Any())
                    {
                        using (var periodsRepo = new EntityRepository <ScanPeriod>(_connection))
                        {
                            periodsToDelete.ForEach(s =>
                            {
                                periodsRepo.Delete(s.Id);
                            });
                        }
                    }

                    periodsToAdd.ForEach(s =>
                    {
                        s.ScanId = existingScan.Id;
                        s.Scan   = existingScan;
                        existingScan.Periods.Add(s);
                    });

                    existingScan.DateModified = DateTime.Now;
                    existingScan.Title        = scan.Title;
                    existingScan.IsActive     = scan.IsActive;
                    scansRepo.Update(existingScan);
                }
            }, TaskCreationOptions.LongRunning)
            .ContinueWith(result =>
            {
                if (result.Exception != null)
                {
                    onException?.Invoke(result.Exception.InnerException);
                }
                else
                {
                    onSuccess?.Invoke();
                }
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
 /// <summary>
 /// تنظیمات را برمیگرداند
 /// اگر موجود نباشد ایجاد میکند
 /// </summary>
 /// <returns></returns>
 public MonthlyOperationGridClientSettings GetMonthlyOperationGridClientSettings()
 {
     using (NHibernateSessionManager.Instance.BeginTransactionOn())
     {
         MonthlyOperationGridClientSettings Result = null;
         try
         {
             if (ValidateUser())
             {
                 EntityRepository <MonthlyOperationGridClientSettings> rep  = new EntityRepository <MonthlyOperationGridClientSettings>(false);
                 IList <MonthlyOperationGridClientSettings>            list = rep.GetByCriteria(new CriteriaStruct(Utility.GetPropertyName(() => new MonthlyOperationGridClientSettings().UserSetting), new UserSettings()
                 {
                     ID = workingUserSettingsId
                 }));
                 if (list != null && list.Count > 0)
                 {
                     Result = list[0];
                 }
                 else//insert record
                 {
                     MonthlyOperationGridClientSettings settings = new MonthlyOperationGridClientSettings()
                     {
                         AllowableOverTime = true, DailyAbsence = true, DailyMeritoriouslyLeave = true, DailyMission = true, DailyPureOperation = true, DailySickLeave = true, DailyWithoutPayLeave = true, DailyWithPayLeave = true, TheDate = true, DayName = true, FifthEntrance = false, FifthExit = false, FirstEntrance = true, FirstExit = true, FourthEntrance = false, FourthExit = false, HostelryMission = true, HourlyAllowableAbsence = true, HourlyMeritoriouslyLeave = true, HourlyMission = true, HourlyPureOperation = true, HourlySickLeave = true, HourlyUnallowableAbsence = true, HourlyWithoutPayLeave = true, HourlyWithPayLeave = true, ImpureOperation = true, LastExit = true, NecessaryOperation = true, PresenceDuration = true, ReserveField1 = false, ReserveField10 = false, ReserveField2 = false, ReserveField3 = false, ReserveField4 = false, ReserveField5 = false, ReserveField6 = false, ReserveField7 = false, ReserveField8 = false, ReserveField9 = false, SecondEntrance = true, SecondExit = true, Shift = true, ThirdEntrance = false, ThirdExit = false, UnallowableOverTime = true
                     };
                     settings.UserSetting = new UserSettings()
                     {
                         ID = workingUserSettingsId
                     };
                     base.Insert(settings);
                     Result = settings;
                 }
             }
             else
             {
                 throw new IllegalServiceAccess("کاربر یا تنظیمات کاربر در دیتابیس موجود نیست", ExceptionSrc);
             }
             NHibernateSessionManager.Instance.CommitTransactionOn();
             return(Result);
         }
         catch (Exception ex)
         {
             NHibernateSessionManager.Instance.RollbackTransactionOn();
             LogException(ex, "BGridMonthlyOperationClientSettings", "GetMonthlyOperationGridClientSettings");
             throw ex;
         }
     }
 }
        // NOTE: Windows Azure changes a lot with each release.
        // This code was written against version 1.7 (June 2012).
        public void ShouldAlterEntity()
        {
            // NOTE: expect the context and the repository to be managed by your IoC container.
            var context = new TableStorageContext();
            var entityRepository = new EntityRepository(context);

            var partitionKey = new ByPartitionKeySpecification("partitionKey");
            var rowKey = new ByRowKeySpecification("rowKey");

            var entity = entityRepository.GetEntity(partitionKey, rowKey);

            //// make some change to entity ...

            entityRepository.Save(entity);

            context.Commit();
        }
        public void GetSingle_Should_Call_Set_Once_And_Return_Null()
        {
            // Arrange
            var targetPersonId = 4;
            var people = GetDummyPeople(3).ToList();
            var personDbSet = GetPersonDbSet(people);
            var peopleContextMock = new Mock<IPeopleContext>();
            peopleContextMock.Setup(pc => pc.Set<Person>()).Returns(personDbSet);
            var entityRepository = new EntityRepository<Person>(peopleContextMock.Object);

            // Act
            Person person = entityRepository.GetSingle(targetPersonId);

            // Assert
            peopleContextMock.Verify(pc => pc.Set<Person>(), Times.Once());
            Assert.Null(person);
        }
        public void GetSingle_Should_Call_Set_Once_And_Get_Expected_Entity()
        {
            // Arrange
            var targetPersonId = 2;
            var people = GetDummyPeople(3).ToList();
            var personDbSet = GetPersonDbSet(people);
            var peopleContextMock = new Mock<IPeopleContext>();
            peopleContextMock.Setup(pc => pc.Set<Person>()).Returns(personDbSet);
            var entityRepository = new EntityRepository<Person>(peopleContextMock.Object);
            var expectedPeson = people.FirstOrDefault(x => x.Id == targetPersonId);

            // Act
            Person person = entityRepository.GetSingle(targetPersonId);

            // Assert
            peopleContextMock.Verify(pc => pc.Set<Person>(), Times.Once());
            Assert.Same(expectedPeson, person);
        }
Esempio n. 51
0
        public void WhenInsertingEmployeeShouldSaveIt()
        {
            // Arrange
            const string ExpectedFirstName = "FirstName";
            const string ExpectedLastName = "LastName";

            var employeeRepository = new EntityRepository<Employee>(this.Context);
            var employee = CreateEmployee(ExpectedFirstName, ExpectedLastName);

            // Act
            var insertedEmployee = employeeRepository.Insert(employee);
            this.Context.SaveChanges();
            var query = new EmployeeIdQuery(insertedEmployee.Id);
            var actual = employeeRepository.Single(query);

            // Assert
            Assert.IsNotNull(actual);
            Assert.AreEqual(ExpectedFirstName, actual.FirstName);
            Assert.AreEqual(ExpectedLastName, actual.LastName);
        }
Esempio n. 52
0
        public void GetEmployeeById()
        {
            // Arrange
            var repository = new EntityRepository<Employee>(this.Context);
            var employeeService = new EmployeeService(repository);
            var expectedFirstName = "TestName";
            var expectedLastName = "TestLastName";
            var expectedEmail = "*****@*****.**";
            var employee = this.CreateEmployee(expectedFirstName, expectedLastName, expectedEmail);
            var savedEmployee = employeeService.Save(employee);

            // Act
            var actual = employeeService.SingleById(savedEmployee.Id);

            // Assert
            Assert.IsNotNull(actual);
            Assert.AreEqual(expectedFirstName, actual.FirstName);
            Assert.AreEqual(expectedLastName, actual.LastName);
            Assert.IsNotNull(actual.Profile);
            Assert.IsNotNull(actual.Profile.Bio);
        }
        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 void GiveAIdWhichUserHasNoPermission_ShouldThrowException()
            {
                const int aValidId = 1;
                var genres = new List<Genre>
                                 {
                                     new Genre
                                         {
                                             Id = aValidId
                                         }
                                 };

                var dbSet = new FakeDbSet<Genre>();

                foreach (Genre genre in genres)
                {
                    dbSet.Add(genre);
                }

                var entitiesContext = A.Fake<IEntitiesContext>();
                A.CallTo(() => entitiesContext.Set<Genre>()).Returns(dbSet);

                var fakeValidator = A.Fake<IValidator<Genre>>();
                var validationFailure = new List<ValidationFailure> { new ValidationFailure("Id", "fake error") };
                var validationResult = new ValidationResult(validationFailure);

                A.CallTo(() => fakeValidator.Validate(A<Genre>.Ignored)).Returns(validationResult);

                var repo = new EntityRepository<Genre>(entitiesContext);
                IValidatorFactory factory = A.Fake<IValidatorFactory>();
                var fakeMapping = A.Fake<IMappingEngine>();
                var genreService = new GenreService(repo, factory, fakeMapping);

                //Genre result = genreService.GetGenre(aValidId);

                Action act = () => genreService.GetGenre(aValidId);

                act.ShouldThrow<ValidationException>();
            }
            public TestableCuratedPackagesController()
            {
                StubCuratedFeed = new CuratedFeed
                    { Key = 0, Name = "aFeedName", Managers = new HashSet<User>(new[] { new User { Username = "******" } }) };
                StubIdentity = new Mock<IIdentity>();
                StubPackageRegistration = new PackageRegistration { Key = 0, Id = "anId" };

                StubIdentity.Setup(stub => stub.IsAuthenticated).Returns(true);
                StubIdentity.Setup(stub => stub.Name).Returns("aUsername");

                EntitiesContext = new FakeEntitiesContext();
                EntitiesContext.CuratedFeeds.Add(StubCuratedFeed);
                EntitiesContext.PackageRegistrations.Add(StubPackageRegistration);

                var curatedFeedRepository = new EntityRepository<CuratedFeed>(
                    EntitiesContext);

                var curatedPackageRepository = new EntityRepository<CuratedPackage>(
                    EntitiesContext);

                base.CuratedFeedService = new CuratedFeedService(
                    curatedFeedRepository,
                    curatedPackageRepository);
            }
Esempio n. 56
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>();
        }
Esempio n. 57
0
        public static void UpdateCache()
        {
            EntityRepository<Config> configsRepo = new EntityRepository<Config>(new mbEntities(Settings.EntityConnectionString));
            List<Config> configurations = configsRepo.Get().ToList();

            HttpRuntime.Cache[CacheKeys.SiteConfigurations] = configurations;
        }
            public void GivenAValidId_ReturnsGenre()
            {
                const int aValidId = 1;
                var genres = new List<Genre>
                                 {
                                     new Genre
                                         {
                                             Id = aValidId
                                         }
                                 };
                var dbSet = new FakeDbSet<Genre>();
                genres.ForEach(genre => dbSet.Add(genre));

                var entitiesContext = A.Fake<IEntitiesContext>();
                A.CallTo(() => entitiesContext.Set<Genre>()).Returns(dbSet);

                var fakeValidator = A.Fake<IValidator>();
                var failure = new ValidationFailure("Id", "error");
                var failures = new List<ValidationFailure> { failure };
                A.CallTo(() => fakeValidator.Validate(A<Genre>.Ignored)).Returns(new ValidationResult(failures));

                IValidatorFactory factory = A.Fake<IValidatorFactory>();
                //var hasPermissionToGet = new HasPermissionToGet(fakeRepo);

                //A.CallTo(() => factory.GetValidator<HasPermissionToGet>()).Returns<HasPermissionToGet>(hasPermissionToGet as IValidator<HasPermissionToGet>);

                var fakeMapping = A.Fake<IMappingEngine>();

                var repo = new EntityRepository<Genre>(entitiesContext);
                var genreService = new GenreService(repo, factory, fakeMapping);

                Genre result = genreService.GetGenre(aValidId);

                result.Should().NotBeNull();
            }
 public TestableUserServiceWithDBFaking()
 {
     Config = (MockConfig = new Mock<IAppConfiguration>()).Object;
     UserRepository = new EntityRepository<User>(FakeEntitiesContext = new FakeEntitiesContext());
     Auditing = new TestAuditingService();
 }
        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();
        }