private static UserService GetService()
 {
     IDataContextFactory<SampleDataContext> dataContextFactory = new DataContextFactory();
     IUserRepository userRepository = new UserRepository(dataContextFactory);
     IUnitOfWork uow = new UnitOfWork<SampleDataContext>(dataContextFactory);
     return new UserService(uow, userRepository);
 }
예제 #2
0
        public TEntity Insert <TEntity>(TEntity entity) where TEntity : class
        {
            using (var context = DataContextFactory.NewInstance())
            {
                context.Insert(entity);
                context.SaveChanges();

                return(entity);
            }
        }
예제 #3
0
        public TEntity GetByKey <TKey, TEntity>(string keyPropertyName, TKey key, params Expression <Func <TEntity, object> >[] paths) where TEntity : class
        {
            using (var context = DataContextFactory.NewInstance())
            {
                var query = context.Query <TEntity>();
                query = IncludePaths(paths, query);

                return(query.Single(GetSelectByKeyCriteria <TKey, TEntity>(keyPropertyName, key)));
            }
        }
예제 #4
0
        public PaytopiaProcessor(CancellationToken cancelToken) : base(cancelToken)
        {
#if DEBUG
            _pollPeriod = 1;
#endif
            _cancelToken               = cancelToken;
            DataContextFactory         = new DataContextFactory();
            PoolDataContextFactory     = new PoolDataContextFactory();
            ExchangeDataContextFactory = new ExchangeDataContextFactory();
        }
예제 #5
0
 /// <summary>
 /// Gets category for a given a product.
 /// </summary>
 /// <param name="productId">The product identifier.</param>
 /// <returns>The category.</returns>
 public Category GetCategoryByProduct(int productId)
 {
     using (ActionDataContext db = DataContextFactory.CreateContext())
     {
         return(Mapper.ToBusinessObject(db.CategoryEntities.SelectMany(c => db.ProductEntities
                                                                       .Where(p => c.CategoryId == p.CategoryId)
                                                                       .Where(p => p.ProductId == productId),
                                                                       (c, p) => c).SingleOrDefault(c => true)));
     }
 }
예제 #6
0
 internal FakeAuthenticationManager(DataContextFactory factory, UserManager <ApplicationUser> userManager, User[] users) : base(factory, userManager)
 {
     foreach (User user in users)
     {
         ApplicationUser applicationUser = new ApplicationUser();
         applicationUser.UserName = user.Username;
         applicationUser.Email    = user.Email;
         userManager.CreateAsync(applicationUser, user.Password);
     }
 }
예제 #7
0
        public TEntity Update <TEntity>(TEntity entity) where TEntity : class
        {
            using (var context = DataContextFactory.NewInstance())
            {
                context.AttachModified(entity);
                context.SaveChanges();

                return(entity);
            }
        }
예제 #8
0
        /// <summary>
        /// Changes the parent ou of a given ou.
        /// </summary>
        /// <param name="ouID"></param>
        /// <param name="ouIDParent"></param>
        /// <returns></returns>
        public bool ChangeParent(int ouID, int?ouIDParent, DateTime updateTime)
        {
            try
            {
                using (var dataContext = DataContextFactory.CreateDataContext())
                {
                    var ou = (from q in dataContext.OrganizationalUnit
                              where q.ID == ouID
                              select q).FirstOrDefault();

                    if (ou != null && (ou.LastUpdate == null || ou.LastUpdate < updateTime.Ticks))
                    {
                        ou.LastUpdate = updateTime.Ticks;

                        if (ou != null && ouIDParent != null)
                        {
                            var parentOU = (from p in dataContext.OrganizationalUnit
                                            where p.ID == ouIDParent
                                            select p.ID).ToList();

                            if (parentOU.Count == 1)
                            {
                                ou.Parent = ouIDParent;
                                dataContext.SubmitChanges();
                            }
                            else
                            {
                                throw new ArgumentException("Parent OU deosn't exists");
                            }
                        }
                        else
                        {
                            ou.Parent = null;
                            dataContext.SubmitChanges();
                        }
                    }
                    else if (ou == null)
                    {
                        Logger.Instance.WriteEntry("OUManager_ChangeParent: Can't find the OU to be changed.", LogType.Warning);
                        return(false);
                    }
                    else
                    {
                        Logger.Instance.WriteEntry("OUManager_ChangeParent: Can't change parent OU. The UpdateTime is to late.", LogType.Warning);
                        return(false);
                    }
                }
                return(true);
            }
            catch (Exception e)
            {
                Logger.Instance.WriteEntry("OUManager_ChangeParent: Can't change parent OU. " + e.StackTrace + " " + e.Message + " " + e, LogType.Exception);
                return(false);
            }
        }
예제 #9
0
        public bool AddMailObserver(int userID, List <string> mac)
        {
            if (mac == null)
            {
                return(false);
            }
            try
            {
                using (var dataContext = DataContextFactory.CreateDataContext())
                {
                    foreach (string i in mac)
                    {
                        var msID = (from q in dataContext.MonitoredSystem
                                    where q.MacAddress == i
                                    select q.ID).FirstOrDefault();

                        EmailObserver observer = new EmailObserver()
                        {
                            EmailID           = userID,
                            MonitoredSystemID = msID
                        };
                        dataContext.EmailObserver.InsertOnSubmit(observer);
                        dataContext.SubmitChanges();

                        // local caching.
                        #region caching
                        if (warningMails.ContainsKey(msID))
                        {
                            List <MailAddress> list;
                            if (warningMails.TryGetValue(msID, out list))
                            {
                                warningMails.Remove(msID);
                            }
                            else
                            {
                                list = new List <MailAddress>();
                            }
                            list.Add(new MailAddress(observer.Email.Address, observer.Email.ReceiverName));
                            warningMails.Add(msID, list);
                        }
                        #endregion
                    }
                    return(true);
                }
            }
            catch (Exception e)
            {
                //logging exception
                var messageEx1 = new StringBuilder();
                messageEx1.Append("Mailer_AddMailObserver: ");
                messageEx1.Append("Adding of MailObserver failed. " + e.ToString());
                MISD.Core.Logger.Instance.WriteEntry(messageEx1.ToString(), LogType.Exception);
                return(false);
            }
        }
예제 #10
0
 public AuthService(
     SignInManager <UserEntity> signInManager,
     DataContextFactory contextFactory,
     AppConfiguration configuration,
     IDateTimeService dateTimeService)
 {
     _signInManager   = signInManager ?? throw new ArgumentNullException(nameof(signInManager));
     _contextFactory  = contextFactory ?? throw new ArgumentNullException(nameof(contextFactory));
     _configuration   = configuration ?? throw new ArgumentNullException(nameof(configuration));
     _dateTimeService = dateTimeService ?? throw new ArgumentNullException(nameof(dateTimeService));
 }
예제 #11
0
        /// <summary>
        /// Deletes a customer record from the database.
        /// </summary>
        /// <param name="customer">The customer to be deleted.</param>
        /// <returns>Number of rows affected.</returns>
        public void DeleteCustomer(Customer customer)
        {
            var entity = Mapper.Map(customer);

            using (var context = DataContextFactory.CreateContext())
            {
                context.CustomerEntities.Attach(entity, false);
                context.CustomerEntities.DeleteOnSubmit(entity);
                context.SubmitChanges();
            }
        }
        private void btnFiltrar_Click(object sender, EventArgs e)
        {
            using (ClienteDataContext clienteDataContext = DataContextFactory.Create())
            {
                var clientes = string.IsNullOrEmpty(txtNomeCliente.Text) ?
                               clienteDataContext.Clientes :
                               clienteDataContext.Clientes.Where(t => t.Nome.StartsWith(txtNomeCliente.Text));

                dtgClientes.DataSource = clientes.ToList();
            }
        }
        public async Task <UserProfileModel> GetProfile(string userId)
        {
            try
            {
                using (var context = DataContextFactory.CreateReadOnlyContext())
                {
                    var user = await context.Users
                               .AsNoTracking()
                               .Include(x => x.Profile)
                               .Include(x => x.Settings)
                               .Where(x => x.Id == userId)
                               .FirstOrDefaultNoLockAsync().ConfigureAwait(false);

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

                    return(new UserProfileModel
                    {
                        IsPublic = user.Profile.IsPublic,
                        AboutMe = user.Profile.AboutMe,
                        AccountEmail = user.Email,
                        Birthday = user.Profile.Birthday,
                        ChatHandle = user.ChatHandle,
                        ContactEmail = user.Profile.ContactEmail,
                        Education = user.Profile.Education,
                        Facebook = user.Profile.Facebook,
                        Gender = user.Profile.Gender,
                        Hobbies = user.Profile.Hobbies,
                        LinkedIn = user.Profile.LinkedIn,
                        MiningHandle = user.MiningHandle,
                        Occupation = user.Profile.Occupation,
                        TrustRating = user.TrustRating,
                        Twitter = user.Profile.Twitter,
                        Website = user.Profile.Website,
                        FirstName = user.Profile.FirstName,
                        LastName = user.Profile.LastName,
                        VerificationLevel = user.VerificationLevel,
                        Address = user.Profile.Address,
                        City = user.Profile.City,
                        Country = user.Profile.Country,
                        Postcode = user.Profile.Postcode,
                        State = user.Profile.State,

                        ReferralDetails = await ReferralReader.GetActiveReferral(user.Id).ConfigureAwait(false)
                    });
                }
            }
            catch (Exception)
            {
                return(new UserProfileModel());
            }
        }
예제 #14
0
 public CategoryService(
     QueryOptions queryOptions, DropdownList dropdownList,
     ModelValidator modelValidator, IUriHelper uriHelper, JSInterop js,
     DataContextFactory contextFactory) :
     base(queryOptions, modelValidator)
 {
     DropdownList    = dropdownList;
     _uriHelper      = uriHelper;
     _js             = js;
     _contextFactory = contextFactory;
 }
        /// <summary>
        /// Creates the initial dbcontext, services and repositories
        /// </summary>
        /// <param name="dbName">Database name for the in memory database</param>
        /// <returns>DbContext, Userservice, UserRepository, DatasetRepository, DatasetService</returns>
        private static (DataContext, UserService, UserRepository, DatasetRepository, DatasetService) InitDb(string dbName)
        {
            DataContext    dbContext   = new DataContext(DataContextFactory.GetInMemoryDb(dbName));
            UserRepository userRep     = new UserRepository(dbContext);
            UserService    userService = new UserService(userRep);

            DatasetRepository datasetRepository = new DatasetRepository(dbContext);
            DatasetService    datasetService    = new DatasetService(datasetRepository);

            return(dbContext, userService, userRep, datasetRepository, datasetService);
        }
예제 #16
0
        private void btnFiltrar_Click(object sender, EventArgs e)
        {
            using (ClienteDataContext clienteDataContext = DataContextFactory.Create())
            {
                var clientes = string.IsNullOrEmpty(txtNomeCliente.Text) ?
                               Program.unityOfWork.clienteRepository.Clientes() :
                               Program.unityOfWork.clienteRepository.BuscarClientesPorNome(txtNomeCliente.Text);

                dtgClientes.DataSource = clientes;
            }
        }
예제 #17
0
        public IActionResult Get(Int32?id)
        {
            try
            {
                LoggerBundle.Trace("Registered GET request on FilesController.Get");

                if (!IsAuthorized(out IActionResult result))
                {
                    LoggerBundle.Trace("Request not authorized");
                    return(result);
                }

                // validate
                if (id == null)
                {
                    LoggerBundle.Trace("Validation failed: id is null");
                    return(StatusCode(StatusCodes.Status400BadRequest));
                }

                // get track
                Track track;
                using (DataContext dataContext = DataContextFactory.GetInstance())
                {
                    track = dataContext.SetTracks.FirstOrDefault(x => x.UniqueId.Equals(id));
                }

                // validate
                if (null == track || !System.IO.File.Exists(track.Path))
                {
                    LoggerBundle.Trace($"Track not found for given id '{id}'");
                    return(StatusCode(StatusCodes.Status404NotFound));
                }

                FileSystemInfo file = new FileInfo(track.Path);
                if (!file.Exists)
                {
                    LoggerBundle.Warn($"File '{track.Path}' not found for given track. Cleanup your database.");
                    return(StatusCode(StatusCodes.Status404NotFound));
                }

                // get mime type
                if (!new FileExtensionContentTypeProvider().TryGetContentType(file.Name, out String contentType))
                {
                    // default fallback
                    contentType = $"audio/{file.Extension.Substring(1)}";
                }

                return(PhysicalFile(file.FullName, contentType));
            }
            catch (Exception ex)
            {
                return(HandleException(ex));
            }
        }
예제 #18
0
        public void Given()
        {
            _container = RestApiApplication.CreateContainer();

            _dataContextFactory = _container.Resolve <DataContextFactory>();

            _dataContextFactory.DeleteAllData();

            TimeService.ResetToRealTime();
            _excelWriter = new ExcelWriter();
        }
예제 #19
0
        private void HandleStdOutput(DataReceivedEventArgs arguments, Track track)
        {
            LoggerBundle.Trace($"Processing response of track '{track}'...");
            try
            {
                String output = arguments?.Data?.Trim();
                if (String.IsNullOrEmpty(output))
                {
                    return;
                }

                LoggerBundle.Debug(Logger.DefaultLogFlags & ~LogFlags.SuffixNewLine
                                   , $"Trying to serialize computation output of file '{track}'...");
                JsonFingerprint jfp = JsonConvert.DeserializeObject <JsonFingerprint>(output);
                LoggerBundle.Debug(Logger.DefaultLogFlags & ~LogFlags.PrefixLoggerType & ~LogFlags.PrefixTimeStamp, "Ok.");

                track.LastFingerprintCalculation = DateTime.Now;
                track.FingerprintHash            = _hasher.Compute(jfp.Fingerprint);
                track.FingerprintError           = null;

                LoggerBundle.Trace($"Fingerprint hash: {track.FingerprintHash} for fingerprint {jfp.Fingerprint}");

                using (DataContext dataContext = DataContextFactory.GetInstance())
                {
                    LoggerBundle.Trace($"Checking for duplicates for file '{track}'...");
                    if (dataContext.SetTracks.AsNoTracking().Any(x => x.FingerprintHash.Equals(track.FingerprintHash)))
                    {
                        LoggerBundle.Debug($"File with same fingerprint already in database. Path '{track}' will be skipped");
                        track.FingerprintError = "duplicate";
                    }
                    else
                    {
                        LoggerBundle.Trace($"No duplicate found for file '{track}'");
                        track.Duration    = jfp.Duration;
                        track.Fingerprint = jfp.Fingerprint;
                        LoggerBundle.Trace($"New meta data duration '{track.Duration}' and fingerprint '{jfp.Fingerprint}'");
                    }

                    LoggerBundle.Trace($"Saving file '{track.Path}'...");
                    dataContext.SetTracks.Attach(track);
                    dataContext.Entry(track).State = EntityState.Modified;
                    dataContext.SaveChanges();
                    LoggerBundle.Debug($"Successfully saved file '{track}'...");
                }
            }
            catch (Exception ex)
            {
                LoggerBundle.Error(ex);
            }
            finally
            {
                _buffer.Remove(track);
            }
        }
        /// <inheritdoc />
        public override IRepository <T, TKey> GetInstance <T, TKey>()
        {
            var(items, storagePath) = Getrep <T>();


            return
                (string.IsNullOrEmpty(DataContextFactory.GetContext())
                ? throw new ConfigurationErrorsException(
                     "The directory attribute is required in order to use the XmlRepository via the configuration file.")
                : new XmlRepository <T, TKey>(items, storagePath));
        }
예제 #21
0
        public override void OnCreate(Bundle savedInstanceState)
        {
            Log.Debug(TAG, nameof(OnCreate));

            base.OnCreate(savedInstanceState);

            // Create your fragment here
            string pathToDatabase = DeviceInfo.GetFileFinallPath(Resources.GetString(Resource.String.DBfilename));

            db = DataContextFactory.GetDataContext(pathToDatabase);
        }
예제 #22
0
 public bool UploadIndicatorValue(string monitoredSystemMAC, string pluginName, string indicatorValueName, object value, DataType valueDataType, DateTime aquiredTimestamp)
 {
     using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
     {
         int monitoredSystemID = PrecompiledQueries.GetMonitoredSystemIDByMAC(dataContext, monitoredSystemMAC);
         //Manager.Logger.Instance.WriteEntry("Reveiving Data from " + monitoredSystemMAC + " via single UploadIndicatorValue", LogType.Info);
         List <Tuple <string, object, DataType, DateTime> > list = new List <Tuple <string, object, DataType, DateTime> >();
         list.Add(new Tuple <string, object, DataType, DateTime>(indicatorValueName, value, valueDataType, aquiredTimestamp));
         return(MISD.Server.Manager.WorkstationManager.Instance.UploadIndicatorValues(monitoredSystemID, pluginName, list));
     }
 }
 public M20210304_1026_02_AddDefaultUsers(
     ILogger logger,
     AppConfiguration configuration,
     UserManager <UserEntity> userManager,
     DataContextFactory contextFactory)
 {
     _logger         = logger ?? throw new ArgumentNullException(nameof(logger));
     _configuration  = configuration ?? throw new ArgumentNullException(nameof(configuration));
     _userManager    = userManager ?? throw new ArgumentNullException(nameof(userManager));
     _contextFactory = contextFactory ?? throw new ArgumentNullException(nameof(contextFactory));
 }
예제 #24
0
        public void CheckAmbigousAssembly()
        {
            var exception =
                Assert.Throws <InvalidOperationException>(
                    () => DataContextFactory.CreateCOM(globalContext.ComObject(), Assembly.GetExecutingAssembly()));
            const string expectedMessageFormat =
                "can't map [{0}] to [Simple1C.Tests] because it's already mapped to [Metadata1C]";

            Assert.That(exception.Message,
                        Is.EqualTo(string.Format(expectedMessageFormat, globalContext.GetConnectionString())));
        }
예제 #25
0
        public async Task CreateUserTest()
        {
            var context = DataContextFactory.CreateSocialNetworkContext();
            var service = new UserService(context);
            var result  = await service.CreateUser(new CreateUserRequest(), CancellationToken.None);

            Assert.True(result != Guid.Empty);

            var user = context.Users.Single();

            Assert.Equal(user.Id, result);
        }
 public void CanAddUserUsingMegaMediaManagerContext()
 {
     using (new EFUnitOfWorkFactory().Create())
     {
         var context = DataContextFactory.GetDataContext();
         var user    = new User {
             UserName = "******", Email = "*****@*****.**", PasswordHash = "123456"
         };
         context.Users.Add(user);
         context.Users.Remove(user);
     }
 }
예제 #27
0
        public Device Register(Device device)
        {
            var application = DataContextFactory.GetDataContext().Application.Where(app => app.AppId == device.AppId && app.IsRemoved == false).FirstOrDefault();

            if (application == null)
            {
                //app不存在
            }
            DataContextFactory.GetDataContext().Device.Add(device);
            _uow.Commit();
            return(device);
        }
예제 #28
0
        public void SetsContextFactory()
        {
            DataContextFactory contextFactory = (connectionString, source) => null;

            ActiveRecordConfiguration.Configure(x => {
                x.ConnectionStringIs("foo");
//				x.MapTypes(typeof(Customer));
                x.DataContextFactory(contextFactory);
            });

            ActiveRecordConfiguration.Current.DataContextFactory.ShouldBeTheSameAs(contextFactory);
        }
예제 #29
0
 public AdminController(GameStateService gameStateService, OverridableSettings appSettings, TilgangsKontroll tilgangsKontroll, PosisjonsService posisjonsService, ExcelImport excelImport, KmlToExcelPoster kmlToExcelPoster, ExcelWriter excelWriter, ExcelExport excelExport, DataContextFactory dataContextFactory)
 {
     _gameStateService   = gameStateService;
     _appSettings        = appSettings;
     _tilgangsKontroll   = tilgangsKontroll;
     _posisjonsService   = posisjonsService;
     _excelImport        = excelImport;
     _kmlToExcelPoster   = kmlToExcelPoster;
     _excelWriter        = excelWriter;
     _excelExport        = excelExport;
     _dataContextFactory = dataContextFactory;
 }
 protected Task ExecuteSqlCommand(string cmd)
 {
     return(Task.Run(
                () =>
     {
         this.dbContext.Database.ExecuteSqlCommand(cmd);
         DataContextFactory.Clear();
         var context = DataContextFactory.GetDataContext();
         this.dbContext = context ?? throw new ArgumentNullException(nameof(context));
         this.dbSet = this.dbContext.Set <TEntity>();
     }));
 }
        public async Task <IWriterResult> RejectUser(string currentAdminId, int verificationId, string reason)
        {
            string            userName;
            EmailMessageModel emailModel;

            using (var context = DataContextFactory.CreateContext())
            {
                var userVerification = await context.UserVerification
                                       .Include(uv => uv.User)
                                       .Where(uv => uv.Id == verificationId)
                                       .FirstOrDefaultNoLockAsync();

                if (userVerification == null)
                {
                    return(new WriterResult(false, "User Verification Entity not found"));
                }

                var user = userVerification.User;

                if (userVerification.User.VerificationLevel != VerificationLevel.Level2Pending)
                {
                    return(new WriterResult(false, "User Verification level not at Level 2 Pending"));
                }


                var rejectedUserEntity = UserVerificationReject.CreateFrom(userVerification);
                rejectedUserEntity.RejectReason = reason;
                context.UserVerificationReject.Add(rejectedUserEntity);

                user.VerificationLevel = VerificationLevel.Level1;

                context.UserVerification.Remove(userVerification);
                context.LogActivity(currentAdminId, $"Rejected User Verification for {userVerification.FirstName} {userVerification.LastName}. Reason: {reason}");

                await context.SaveChangesAsync();

                var emailParameters = new List <object> {
                    user.UserName, reason
                };
                emailModel = new EmailMessageModel
                {
                    BodyParameters = emailParameters.ToArray(),
                    Destination    = user.Email,
                    EmailType      = EmailTemplateType.UserAccountRejected
                };

                userName = user.UserName;
            }

            await EmailService.SendEmail(emailModel);

            return(new WriterResult(true, $"User {userName} Rejected - Email sent"));
        }
        public NHibernateInMemoryRepository(IFrameworkContext fakeFrameworkContext, ISessionFactory sessionFactory = null, ISession sessionForTest = null)
        {
            using (DisposableTimer.TraceDuration<NHibernateInMemoryRepository>("Start setup", "End setup"))
            {
                if (sessionFactory == null && sessionForTest == null)
                {
                    var builder = new NHibernateConfigBuilder("data source=:memory:", "unit-tester",
                                                              SupportedNHDrivers.SqlLite, "thread_static", false);
                    var config = builder.BuildConfiguration();
                    _sessionFactory = config.BuildSessionFactory();
                    SessionForTest = _sessionFactory.OpenSession();

                    // See http://stackoverflow.com/questions/4325800/testing-nhibernate-with-sqlite-no-such-table-schema-is-generated
                    // and also http://nhforge.org/doc/nh/en/index.html#architecture-current-session
                    // regarding contextual sessions and GetCurrentSession()

                    // We pass in our own TextWriter because a bug in VS's testing framework means directly passing in Console.Out causes an ObjectDisposedException
                    new SchemaExport(config).Execute(false, true, false, SessionForTest.Connection, _schemaWriter);
                }
                else
                {
                    _sessionFactory = sessionFactory;
                    SessionForTest = sessionForTest;
                }

                _dataContextFactory = new DataContextFactory(fakeFrameworkContext, SessionForTest, true);

                // Create reader
                ReadOnlyUnitOfWorkFactory = new ReadOnlyUnitOfWorkFactory();
                _hiveReadProvider = new HiveReadProvider(new HiveProviderSetup(fakeFrameworkContext, "r-unit-tester", new FakeHiveProviderBootstrapper(), ReadOnlyUnitOfWorkFactory, null, _dataContextFactory));

                // Create writer
                ReadWriteUnitOfWorkFactory = new ReadWriteUnitOfWorkFactory();
                _writeProvider = new HiveReadWriteProvider(new HiveProviderSetup(fakeFrameworkContext, "rw-unit-tester", new FakeHiveProviderBootstrapper(), ReadOnlyUnitOfWorkFactory, ReadWriteUnitOfWorkFactory, _dataContextFactory));

                //setup nhibernate mappers
                var manualMapper = new ManualMapper(new NhLookupHelper(_dataContextFactory), _writeProvider);
                fakeFrameworkContext.TypeMappers.Add(new Lazy<AbstractTypeMapper, TypeMapperMetadata>(() => manualMapper, new TypeMapperMetadata(true)));


                // Create hive wrappers for the readers and writers
                var governorRUowFactory = new ReadOnlyUnitOfWorkFactoryWrapper(new[] { _hiveReadProvider });

                var governorRWUowFactory = new ReadWriteUnitOfWorkFactoryWrapper(new[] { _writeProvider });

                _hiveReadProviderViaGovernor = new Framework.Hive.PersistenceGovernor.HiveReadProvider(new HiveProviderSetup(fakeFrameworkContext, "r-unit-wrapper", new FakeHiveProviderBootstrapper(), governorRUowFactory, null, null), new[] { _hiveReadProvider });
                _hiveReadWriteProviderViaGovernor = new Framework.Hive.PersistenceGovernor.HiveReadWriteProvider(new HiveProviderSetup(fakeFrameworkContext, "rw-unit-wrapper", new FakeHiveProviderBootstrapper(), governorRUowFactory, governorRWUowFactory, null), new[] { _writeProvider });
            }
        }
        private static HiveReadWriteProvider CreateReadWritter()
        {
            var builder = new NHibernateConfigBuilder("data source=:memory:", "unit-tester",
                                                      SupportedNHDrivers.SqlLite, "thread_static", false);
            var config = builder.BuildConfiguration();
            var sessionFactory = config.BuildSessionFactory();
            _sessionForTest = sessionFactory.OpenSession();
            var schemaWriter = new StringWriter(new StringBuilder());
            new SchemaExport(config).Execute(false, true, false, _sessionForTest.Connection, schemaWriter);

            var fakeFrameworkContext = new FakeFrameworkContext();
            var dataContextFactory = new DataContextFactory(fakeFrameworkContext, _sessionForTest, true);

            var readWriteRepositoryUnitOfWorkFactory = new ReadWriteUnitOfWorkFactory();
            var writer = new HiveReadWriteProvider(new HiveProviderSetup(fakeFrameworkContext, "r-unit-tester", new FakeHiveProviderBootstrapper(), null, readWriteRepositoryUnitOfWorkFactory, dataContextFactory));

            fakeFrameworkContext.TypeMappers.Add(
                new Lazy<AbstractTypeMapper, TypeMapperMetadata>(
                    () => new ManualMapper(new NhLookupHelper(dataContextFactory), writer), new TypeMapperMetadata(true)));
            
            return writer;
        }
예제 #34
0
        public CachingProviderTests()
        {
            _fakeFrameworkContext = new FakeFrameworkContext();

            var inMemory = new NHibernateInMemoryRepository(_fakeFrameworkContext);

            var dataContextFactory = new DataContextFactory();
            var readWriteUnitOfWorkFactory = new ReadWriteUnitOfWorkFactory();
            var directReaderProvider = new HiveReadWriteProvider(new HiveProviderSetup(_fakeFrameworkContext, "r-unit-tester",
                                                                  new FakeHiveProviderBootstrapper(),
                                                                  readWriteUnitOfWorkFactory, readWriteUnitOfWorkFactory,
                                                                  dataContextFactory));
            var directReadWriteProvider = directReaderProvider;

            // Create hive wrappers for the readers and writers
            var governorRUowFactory = new ReadOnlyUnitOfWorkFactoryWrapper(new[] { directReaderProvider, inMemory.HiveReadProvider });
            var governorRWUowFactory = new ReadWriteUnitOfWorkFactoryWrapper(new[] { directReadWriteProvider, inMemory.ReadWriteProvider });

            _readerProviderViaHiveGovernor = _directReaderProvider =
                new Framework.Hive.PersistenceGovernor.HiveReadProvider(new HiveProviderSetup(_fakeFrameworkContext, "r-unit-wrapper", new FakeHiveProviderBootstrapper(), governorRUowFactory, null, null), new[] { _directReaderProvider });
            _readWriteProviderViaHiveGovernor = _directReadWriteProvider =
                new Framework.Hive.PersistenceGovernor.HiveReadWriteProvider(new HiveProviderSetup(_fakeFrameworkContext, "rw-unit-wrapper", new FakeHiveProviderBootstrapper(), governorRUowFactory, governorRWUowFactory, null), new[] { _directReadWriteProvider });
        }
        public static void MyClassInitialize(TestContext testContext)
        {
            var frameworkContext =
                new FrameworkContext(
                    ConfigurationManager.GetSection("umbraco.foundation") as IFoundationConfigurationSection);

            var persistenceConfig = ConfigurationManager.GetSection("hive.persistence") as HiveConfigurationSection;

            var localConfig = persistenceConfig.AvailableProviders.ReadWriters["rw-nhibernate-01"].GetLocalProviderConfig() as ProviderConfigurationSection;

            var nhSetup = new NHibernateConfigBuilder("rw-nhibernate-01", localConfig);
            var config = nhSetup.BuildConfiguration();

            // Setup the local provider
            var dataContextFactory = new DataContextFactory(config.BuildSessionFactory());
            var unitOfWorkFactory = new ReadWriteRepositoryUnitOfWorkFactory(dataContextFactory);
            var reader = new Reader(unitOfWorkFactory);
            var readWriter = new ReadWriter(unitOfWorkFactory);

            var uriMatch = new DefaultUriMatch() {MatchType = UriMatchElement.MatchTypes.Wildcard, Uri = "content://*/"};

            // Setup hive's provider governor. Normally it takes two uow factories (read and read-write) but we can use the same for both here
            _mappingGroup = new DefaultPersistenceMappingGroup("rw-nhibernate-01", new[] { unitOfWorkFactory }, new[] { unitOfWorkFactory }, new[] { reader }, new[] { readWriter }, new[]{uriMatch});
        }