예제 #1
0
        private static ISessionFactory CreateSessionFactory()
        {
            try
            {
                var cfg = OracleManagedDataClientConfiguration.Oracle10
                          .ConnectionString(c =>
                                            c.Is("DATA SOURCE=gislab-oracle.elfak.ni.ac.rs:1521/SBP_PDB;PERSIST SECURITY INFO=True;USER ID=S16381;Password=Mudri1234"));

                return(Fluently.Configure()
                       .Database(cfg)
                       .Mappings(m => m.FluentMappings.AddFromAssemblyOf <PredajeMapiranje>())
                       //.ExposeConfiguration(BuildSchema)
                       .BuildSessionFactory());
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
                return(null);
            }
        }
예제 #2
0
        private static FluentConfiguration RecuperaFluent(Configuration cfg)
        {
            var config = Fluently.Configure(cfg);

            try
            {
                var map = Assembly.Load("Thomas.Greg.Data");

                if (map != null)
                {
                    config.Mappings(m => m.FluentMappings.AddFromAssembly(map));
                }

                return(config);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static void Exec(Action <ISession> action)
        {
            lock (LOCK) {
                if (FACTORY == null)
                {
                    var sqlHelper = new SqlServerTestDbHelper("NH");
                    sqlHelper.ResetDatabase();

                    FACTORY = Fluently.Configure()
                              .Database(MsSqlConfiguration.MsSql2012.ConnectionString(sqlHelper.ConnectionString))
                              .Mappings(m => m.FluentMappings.AddFromAssembly(typeof(SessionFactoryHelper).Assembly))
                              .ExposeConfiguration(config => new SchemaExport(config).Create(false, true))
                              .BuildSessionFactory();
                }

                using (var session = FACTORY.OpenSession()) {
                    action(session);
                }
            }
        }
예제 #4
0
        public void WritesBothOut()
        {
            Fluently.Configure()
            .Database(SQLiteConfiguration.Standard.InMemory())
            .Mappings(m =>
            {
                m.FluentMappings
                .AddFromAssemblyOf <Record>()
                .ExportTo(ExportPath);

                m.AutoMappings.Add(AutoMap.AssemblyOf <Person>(type => type.Namespace == "FluentNHibernate.Testing.Fixtures.Basic"))
                .ExportTo(ExportPath);
            })
            .BuildSessionFactory();

            var files = Directory.GetFiles(ExportPath);

            files.ShouldContain(HbmFor <Record>);
            files.ShouldContain(HbmFor <Person>);
        }
        private ISessionFactory CreateFactory()
        {
            IPersistenceConfigurer dbConfig;
            var bancoNoAppConfig = _databaseEngine;

            if (bancoNoAppConfig.Equals(DATABASE_MYSQL, StringComparison.InvariantCultureIgnoreCase))
            {
                dbConfig = MySQLConfiguration.Standard.ConnectionString(_connectionString);
            }
            else
            {
                dbConfig = OracleManagedDataClientConfiguration.Oracle10.ConnectionString(c => c.Is(_connectionString));
            }

            return(Fluently.Configure()
                   .Database(dbConfig)
                   .Mappings(m => m.FluentMappings.AddFromAssembly(typeof(T).Assembly))
                   .ExposeConfiguration(BuildSchema)
                   .BuildSessionFactory());
        }
예제 #6
0
        public Configuration BuildConfiguration(SessionFactoryParameters parameters)
        {
            var database         = GetPersistenceConfigurer(parameters.CreateDatabase);
            var persistenceModel = CreatePersistenceModel(parameters.RecordDescriptors.ToList());

            var config = Fluently.Configure();

            parameters.Configurers.Invoke(c => c.Created(config, persistenceModel), Logger);

            config = config.Database(database)
                     .Mappings(m => m.AutoMappings.Add(persistenceModel))
                     .ExposeConfiguration(cfg => {
                cfg.EventListeners.LoadEventListeners = new ILoadEventListener[] { new OrchardLoadEventListener() };
                parameters.Configurers.Invoke(c => c.Building(cfg), Logger);
            });

            parameters.Configurers.Invoke(c => c.Prepared(config), Logger);

            return(config.BuildConfiguration());
        }
예제 #7
0
        public static IServiceCollection AddNHibernate(this IServiceCollection services, string connectionString, string createDataBase)
        {
            string dataBaseName = GetDatabaseNameFromConnectionString(connectionString);

            CreateDatabase(dataBaseName, createDataBase);

            var sessionFactory = Fluently.Configure()
                                 .Database(MySQLConfiguration.Standard
                                           .ConnectionString(connectionString))
                                 .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
                                 .Mappings(m => m.FluentMappings.AddFromAssemblyOf <Mappings>())
                                 .CurrentSessionContext("call")
                                 .ExposeConfiguration(cfg => BuildSchema(cfg, true, true)).BuildSessionFactory();

            services.AddSingleton(sessionFactory);
            services.AddScoped(factory => sessionFactory.OpenSession());
            services.AddScoped <IMapperSession, NHibernateMapperSession>();

            return(services);
        }
 private static Configuration AddFluentMappings(Configuration nhConfiguration, string stringConnection)
 {
     return(Fluently
            .Configure(nhConfiguration)
            .Database(MySQLConfiguration.Standard.ConnectionString(stringConnection))
            .Mappings(cfg =>
     {
         cfg.FluentMappings.AddFromAssembly(typeof(BankAccountMap).Assembly);
         cfg.FluentMappings.Conventions.Add(
             ForeignKey.EndsWith("_id"),
             ConventionBuilder.Property.When(criteria => criteria.Expect(x => x.Nullable, Is.Not.Set), x => x.Not.Nullable()));
         cfg.FluentMappings.Conventions.Add <OtherConversions>();
         cfg.FluentMappings.Conventions.Add <TableNameConvention>();
     })
            .Mappings(cfg =>
     {
         cfg.FluentMappings.AddFromAssemblyOf <TransferSagaData>();
     })
            .BuildConfiguration());
 }
예제 #9
0
 private static ISessionFactory CreateSessionFactory()
 {
     try
     {
         var cfg = OracleManagedDataClientConfiguration.Oracle10
                   .ConnectionString(c =>
                                     c.Is(
                                         "DATA SOURCE=gislab-oracle.elfak.ni.ac.rs:1521/SBP_PDB;PERSIST SECURITY INFO=True; USER ID=S16630;PASSWORD=igor98"));
         return(Fluently.Configure()
                .Database(cfg.ShowSql())
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf <PolicijskaStanicaMapiranja>())
                //.ExposeConfiguration(BuildSchema) // kako ovo treba da radi?
                .BuildSessionFactory());
     }
     catch (Exception ec)
     {
         System.Windows.Forms.MessageBox.Show(ec.Message);
         return(null);
     }
 }
예제 #10
0
        public static void ConfigureDatabase(IUnityContainer container)
        {
            var needToCreate = CheckDbExistsFirst();

            ISessionFactory sessionFactory      = default(ISessionFactory);
            var             fluentConfiguration = Fluently
                                                  .Configure()
                                                  .Database(MsSqlConfiguration.MsSql2012
                                                            .ConnectionString(c => c.FromConnectionStringWithKey(ConnectionStringName)).ShowSql())
                                                  .Mappings(m => m.FluentMappings.Add <TreeItemMap>());

            if (needToCreate)
            {
                fluentConfiguration = fluentConfiguration.ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true));
            }

            sessionFactory = fluentConfiguration.BuildSessionFactory();

            container.RegisterInstance(typeof(ISessionFactory), sessionFactory);
        }
예제 #11
0
 public static ISessionFactory FluentConfigure()
 {
     return(Fluently.Configure()
            //which database
            .Database(
                MsSqlConfiguration.MsSql2012
                .ConnectionString(
                    cs => cs.FromConnectionStringWithKey("DBConnection"))  //connection string from app.config
                                                                           //.ShowSql()
                )
            //2nd level cache
            .Cache(
                c => c.UseQueryCache()
                .UseSecondLevelCache()
                .ProviderClass <NHibernate.Cache.HashtableCacheProvider>())
            //find/set the mappings
            //.Mappings(m => m.FluentMappings.AddFromAssemblyOf<CustomerMapping>())
            .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
            .BuildSessionFactory());
 }
예제 #12
0
파일: Program.cs 프로젝트: ora11g/Test
        static Program()
        {
            //            var configuration = new Configuration()
            //    .Cache(x => x.UseQueryCache = true)
            //configuration.SessionFactory()
            //    .Caching.Through<SysCacheProvider>().WithDefaultExpiration(60)

            Configuration config = new Configuration().Configure();
            //var connStr = System.Configuration.ConfigurationManager.ConnectionStrings["HisPlus"].ConnectionString;
            var connStr = "Data Source=localhost;Initial Catalog=HIS;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False";

            sessionFactory = Fluently.Configure(config)
                             //.Database(MsSqlConfiguration.MsSql2012.ConnectionString(connStr).ShowSql())
                             //.Cache(c => c.ProviderClass<SysCacheProvider>().UseQueryCache())
                             .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetAssembly(typeof(BsGfxeMap))))
                             .Cache(c =>
            {
                c.ProviderClass <SysCacheProvider>().UseQueryCache().UseSecondLevelCache();
            }).BuildSessionFactory();
        }
        public static ISession CreateSession()
        {
            var storeConfiguration = new StoreConfiguration();
            var configuration      = Fluently.Configure()
                                     .Database(
                MsSqlCeConfiguration.Standard.ShowSql()
                .ConnectionString("Data Source=CustomerImport.sdf"))
                                     .Mappings(m => m.AutoMappings.Add(AutoMap
                                                                       .AssemblyOf <Customer>(storeConfiguration)
                                                                       .Override <Customer>(
                                                                           map =>
                                                                           map.HasMany(x => x.Addresses).Cascade.All())));

            var sessionFactory = configuration.BuildSessionFactory();

            new SchemaExport(configuration.BuildConfiguration()).Execute(true, true, false);
            var session = sessionFactory.OpenSession();

            return(session);
        }
예제 #14
0
        //konfiguracija i kreiranje session factory
        private static ISessionFactory CreateSessionFactory()
        {
            try
            {
                var cfg = OracleManagedDataClientConfiguration.Oracle10
                          .ShowSql()
                          .ConnectionString(c =>
                                            c.Is("Data Source=gislab-oracle.elfak.ni.ac.rs:1521/SBP_PDB;User Id=S16317;Password=Bubamara8#"));

                return(Fluently.Configure()
                       .Database(cfg)
                       .Mappings(m => m.FluentMappings.AddFromAssemblyOf <FederacijaMapiranja>())
                       .BuildSessionFactory());
            }
            catch (Exception ec)
            {
                System.Windows.Forms.MessageBox.Show(ec.Message);
                return(null);
            }
        }
예제 #15
0
 public static ISessionFactory CreateSessionFactory <T>()
 {
     try
     {
         return(Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2005.ConnectionString(c => c.FromAppSetting(ConnString))
                          .ShowSql())
                .ExposeConfiguration(cfg => cfg.Properties.Add("current_session_context_class", "web"))
                .Mappings(m => m
                          .FluentMappings.AddFromAssemblyOf <T>()
                          //.Conventions.AddFromAssemblyOf<EnumConvention>()
                          )
                .BuildSessionFactory());
     }
     catch (Exception ex)
     {
         Log.Error("unable to connect to DB", ex);
         throw;
     }
 }
예제 #16
0
파일: Program.cs 프로젝트: xgame92/Stove
        public static void Main(string[] args)
        {
            NHibernateProfiler.Initialize();

            IRootResolver rootResolver = IocBuilder
                                         .New
                                         .UseAutofacContainerBuilder()
                                         .UseStove <StoveDemoBootstrapper>()
                                         .UseStoveNullLogger()
                                         .UseStoveNHibernate(nhCfg =>
            {
                nhCfg.AddFluentConfigurationFor <PrimarySessionContext>(() =>
                {
                    return(Fluently.Configure()
                           .Database(MsSqlConfiguration.MsSql2012.ConnectionString(nhCfg.Configuration.DefaultNameOrConnectionString))
                           .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly())));
                });

                nhCfg.AddFluentConfigurationFor <SecondarySessionContext>(() =>
                {
                    return(Fluently.Configure()
                           .Database(MsSqlConfiguration.MsSql2012.ConnectionString(nhCfg.Configuration.TypedConnectionStrings[typeof(SecondarySessionContext)]))
                           .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly())));
                });

                return(nhCfg);
            })
                                         .UseStoveDapper()
                                         .UseStoveEventBus()
                                         .RegisterServices(r => r.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly()))
                                         .CreateResolver();

            using (rootResolver)
            {
                rootResolver.Resolve <ProductDomainService>().DoSomeCoolStuff();
            }

            NHibernateProfiler.Shutdown();

            Console.ReadLine();
        }
예제 #17
0
        public NHibernate.Cfg.Configuration GetConfiguration()
        {
            var assemblies = GetAssemblies();

            if (_databaseProvider == null)
            {
                throw new Exception("Please set the database provider in mrcms.config");
            }

            var iPersistenceConfigurer = _databaseProvider.GetPersistenceConfigurer();
            var autoPersistenceModel   = GetAutoPersistenceModel(assemblies);

            ApplyCoreFilters(autoPersistenceModel);

            var config = Fluently.Configure()
                         .Database(iPersistenceConfigurer)
                         .Mappings(m => m.AutoMappings.Add(autoPersistenceModel))
                         .Cache(SetupCache)
                         .ExposeConfiguration(AppendListeners)
                         .ExposeConfiguration(AppSpecificConfiguration)
                         .ExposeConfiguration(c =>
            {
#if DEBUG
                c.SetProperty(Environment.GenerateStatistics, "true");
#else
                c.SetProperty(Environment.GenerateStatistics, "false");
#endif
                c.SetProperty(Environment.Hbm2ddlKeyWords, "auto-quote");
                c.SetProperty(Environment.BatchSize, "25");
            })
                         .BuildConfiguration();


            _databaseProvider.AddProviderSpecificConfiguration(config);

            ValidateSchema(config);

            config.BuildMappings();

            return(config);
        }
예제 #18
0
        public static void BootStrap()
        {
            const string ConnectionString = SqlHelper.ConnectionString;

            MsSqlConfiguration msSqlConfiguration = MsSqlConfiguration.MsSql2008.ConnectionString(ConnectionString);

            try
            {
                ObjectFactory.Initialize(
                    x =>
                {
                    x.For <IInterceptor>().Use <DependencyInjectionEntityInterceptor>();
                    x.For(typeof(IRepository <>)).Use(typeof(Repository <>));

                    x.ForSingletonOf <ISessionFactory>()
                    .Use(
                        y =>
                        Fluently.Configure()
                        .Database(msSqlConfiguration)
                        .ExposeConfiguration(
                            configuration =>
                            configuration.SetProperty(TimeoutProperty, DefaultTimeout.ToString()))
                        .ExposeConfiguration(
                            configuration =>
                            configuration.SetInterceptor(y.GetInstance <IInterceptor>()))
                        .Mappings(
                            m =>
                            m.FluentMappings.AddFromAssemblyOf <BookMapping>()
                            .Conventions.AddFromAssemblyOf <BookMapping>())
                        .BuildSessionFactory());

                    x.For <ISession>()
                    .HybridHttpOrThreadLocalScoped()
                    .Use(y => y.GetInstance <ISessionFactory>().OpenSession());
                });
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
        public static void Run()
        {
            Configuration   cfg     = null;
            ISessionFactory factory = null;

            try
            {
                #region NHibernate initialize

                factory = Fluently.Configure()
                          .Database(MsSqlConfiguration.MsSql2008
                                    .ConnectionString(c => c
                                                      .FromConnectionStringWithKey("Connection"))
                                    .ShowSql())
                          .Mappings(m => m
                                    .FluentMappings.AddFromAssemblyOf <Customer>())
                          .BuildSessionFactory();
                #endregion

                Random randomGenerator = new Random();
                int    random          = randomGenerator.Next((int)(DateTime.Now.Ticks % (long)int.MaxValue));

                using (var session = factory.OpenSession())
                    using (var transaction = session.BeginTransaction())
                    {
                        Customer customer = new Customer();
                        customer.Name      = "Barış_" + random.ToString();
                        customer.SurName   = "Akan_" + random.ToString();
                        customer.EMail     = "bakan" + random.ToString() + "@innova.com.tr";
                        customer.BirthDate = DateTime.Today;

                        session.Save(customer);
                        transaction.Commit();
                        session.Close();
                    }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #20
0
        static void Main(string[] args)
        {
            ISessionFactory sessionFactory = Fluently.Configure()
                                             .Database(MsSqlConfiguration.MsSql2012.ConnectionString("Data Source=localhost;Initial Catalog=Northwind;User ID=sa;Password=Northwind0123")
                                                       .ShowSql().FormatSql())
                                             .Mappings(m =>
                                                       m.FluentMappings
                                                       .AddFromAssemblyOf <EmployeesMap>())
                                             .BuildSessionFactory();

            ISession session = sessionFactory.OpenSession();

            IEnumerable <Orders> ordersCustomer = session.Query <Orders>()
                                                  .Where(e => e.Customer.CustomerID.Equals("TORTU") && e.Employee.EmployeeID == 1).ToList();

            IEnumerable <Orders> ordersCity = session.Query <Orders>()
                                              .Where(e => e.ShipCity.Equals("Rio de Janeiro") && e.Employee.EmployeeID == 1).ToList();

            IEnumerable <Orders> ordersCountry = session.Query <Orders>()
                                                 .Where(e => e.ShipCountry.Equals("Brazil") && e.Employee.EmployeeID == 1).ToList();

            //ISession session = sessionFactory.WithOptions().Interceptor(new SessionInterceptor()).OpenSession();

            //ISession session = sessionFactory.OpenSession();
            //session.EnableFilter("OrdersConditionFilter").SetParameter("idEmployee", 1);

            //IEnumerable<Orders> ordersCustomer = session.Query<Orders>()
            //    .Where(e => e.Customer.CustomerID.Equals("TORTU")).ToList();

            //IEnumerable<Orders> ordersCity = session.Query<Orders>()
            //    .Where(e => e.ShipCity.Equals("Rio de Janeiro")).ToList();

            //IEnumerable<Orders> ordersCountry = session.Query<Orders>()
            //    .Where(e => e.ShipCountry.Equals("Brazil")).ToList();

            //System.Console.WriteLine(string.Join('\n', ordersCustomer.Select(o => o.OrderID)));

            //System.Console.WriteLine(string.Join('\n', ordersCity.Select(o => o.OrderID)));

            //System.Console.WriteLine(string.Join('\n', ordersCountry.Select(o => o.OrderID)));
        }
예제 #21
0
        private static Configuration ConfigureNHibernate()
        {
            FluentConfiguration fluentConfig = Fluently.Configure()
                                               .Mappings(
                m => m.AutoMappings     // Use mapping by convention.
                // Map all types in current assembly
                //     using default options from StoreConfiguration class.
                .Add(AutoMap.AssemblyOf <Program>(new StoreConfiguration())
                     // Add our specific defaults for Cascade, etc...
                     .Conventions.Add <CollectionConvention>()
                     // Add 'Order' class exceptions to the convention.
                     // The line itself adds any conventions in assembly,
                     //    which is not the only option we have.
                     .UseOverridesFromAssembly(typeof(OrderOverride).Assembly))
                // Display the mappings XML in the console.
                // Typically you should do little XML stuff to output that.
                // It can also output to text file by specifying path.
                .ExportTo(Console.Out)
                )
                                               .Database(() =>
                                                         MsSqlConfiguration.MsSql2008 // Use SQL Server 2008 Dialect
                                                         .ConnectionString(           // Use connection string from app/web.config
                                                             c => c.FromConnectionStringWithKey("NHibernateTest"))
                                                         .ShowSql()                   // Display SQL generated by NH in console.
                                                         .FormatSql()                 // Format / Tabify SQL in console for readability.
                                                                                      // Auto escape names of tables for safe naming.
                                                                                      //    In SQL Server, this uses '[', and ']' not quotes.
                                                                                      // It's worth mentioning: 'Raw' allows us to add config
                                                                                      //     values as key/value strings like XML mappings,
                                                                                      //    and Environment Hbm2DDLKeyWords are NH classes not FNH
                                                         .Raw(Environment.Hbm2ddlKeyWords,
                                                              Hbm2DDLKeyWords.AutoQuote.ToString())
                                                         )
                                               // Use Jose's collection factory.
                                               // This enables us to use .NET 4.0 HashSet not custom Set types.
                                               .CollectionTypeFactory <Net4CollectionTypeFactory>();

            // All this was done using Fluent NHibernate object to build config
            // So, now build the actual NHibernate Configuration object.
            return(fluentConfig.BuildConfiguration());
        }
예제 #22
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            // New code
            //app.UseSession();
            // End new code

            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            container.RegisterSingleton(typeof(IAuthenticationManager), new AspNetCookieAuthenticationAdapter(app.ApplicationServices.GetRequiredService <IHttpContextAccessor>()));

            container.RegisterSingleton(typeof(ICurrentUserContext), new AspNetCurrentUserContext(GetHttpContextProvider(app)));

            var SessionFactory = Fluently.Configure()
                                 .Database(MsSqlConfiguration.MsSql2012.ConnectionString(Configuration["steamdb"]))
                                 .Mappings(m => m.FluentMappings.AddFromAssemblyOf <Startup>())
                                 .BuildSessionFactory();

            container.RegisterSingleton(typeof(ISessionFactory), SessionFactory);

            // Register how to create an ISession using an ISessionFactory.
            container.Register(() => container.GetService <ISessionFactory>().OpenSession(), Lifestyle.Scoped);

            Mapper.Initialize(cfg => cfg.AddProfiles(typeof(Startup).Assembly));

            app.UseStaticFiles();
            app.UseAuthentication();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Account}/{action=Login}/{id?}");
            });
        }
예제 #23
0
        public Configuration BuildConfiguration(SessionFactoryParameters parameters)
        {
            var database         = GetPersistenceConfigurer(parameters.CreateDatabase);
            var persistenceModel = CreatePersistenceModel(parameters.RecordDescriptors.ToList());

            var config = Fluently.Configure();

            parameters.Configurers.Invoke(c => c.Created(config, persistenceModel), Logger);

            config = config.Database(database)
                     .Mappings(m => m.AutoMappings.Add(persistenceModel))
                     .ExposeConfiguration(cfg => {
                cfg
                .SetProperty(NHibernate.Cfg.Environment.FormatSql, Boolean.FalseString)
                .SetProperty(NHibernate.Cfg.Environment.GenerateStatistics, Boolean.FalseString)
                .SetProperty(NHibernate.Cfg.Environment.Hbm2ddlKeyWords, Hbm2DDLKeyWords.None.ToString())
                .SetProperty(NHibernate.Cfg.Environment.PropertyBytecodeProvider, "lcg")
                .SetProperty(NHibernate.Cfg.Environment.PropertyUseReflectionOptimizer, Boolean.TrueString)
                .SetProperty(NHibernate.Cfg.Environment.QueryStartupChecking, Boolean.FalseString)
                .SetProperty(NHibernate.Cfg.Environment.ShowSql, Boolean.FalseString)
                .SetProperty(NHibernate.Cfg.Environment.StatementFetchSize, "100")
                .SetProperty(NHibernate.Cfg.Environment.UseProxyValidator, Boolean.FalseString)
                .SetProperty(NHibernate.Cfg.Environment.UseSqlComments, Boolean.FalseString)
                .SetProperty(NHibernate.Cfg.Environment.WrapResultSets, Boolean.TrueString);

                cfg.EventListeners.LoadEventListeners     = new ILoadEventListener[] { new OrchardLoadEventListener() };
                cfg.EventListeners.PostLoadEventListeners = new IPostLoadEventListener[0];
                cfg.EventListeners.PreLoadEventListeners  = new IPreLoadEventListener[0];

                // don't enable PrepareSql by default as it breaks on SqlCe
                // this can be done per driver by overriding AlterConfiguration
                AlterConfiguration(cfg);

                parameters.Configurers.Invoke(c => c.Building(cfg), Logger);
            })
            ;

            parameters.Configurers.Invoke(c => c.Prepared(config), Logger);

            return(config.BuildConfiguration());
        }
예제 #24
0
        static void Main(string[] args)
        {
            bool            isFluentMapping = false;
            ISessionFactory sessionFactory;

            if (isFluentMapping)
            {
                sessionFactory = Fluently.Configure().Mappings(m => m.FluentMappings.AddFromAssemblyOf <Program>()).BuildSessionFactory();
            }
            else
            {
                sessionFactory = new Configuration().AddAssembly(typeof(Program).Assembly).BuildSessionFactory();
            }

            ISession session = sessionFactory.OpenSession();

            Console.WriteLine("");
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("Departments(filter disabled):");
            Console.WriteLine("------------------------------------------------------");
            foreach (Department Department in session.CreateQuery("from Department").List <Department>())
            {
                Console.WriteLine(string.Format("{0}  {1} {2}", Department.DEPTNO, Department.DNAME, Department.LOC));
            }


            session.EnableFilter("MyFilter").SetParameter("param", 20);

            Console.WriteLine("");
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("Departments (filter enabled):");
            Console.WriteLine("------------------------------------------------------");
            foreach (Department Department in session.CreateQuery("from Department").List <Department>())
            {
                Console.WriteLine(string.Format("{0}  {1} {2}", Department.DEPTNO, Department.DNAME, Department.LOC));
            }

            session.DisableFilter("MyFilter");

            Console.Read();
        }
예제 #25
0
        /// <summary>
        /// Builds the session factory with the given properties. Database is updated if updateSchema is set
        /// </summary>
        /// <param name="nhibernateProperties"></param>
        /// <param name="updateSchema"></param>
        /// <returns></returns>
        public ISessionFactory Build(IDictionary <string, string> nhibernateProperties, bool updateSchema)
        {
            var model = Create.SagaPersistenceModel(typesToScan);

            model.Conventions.Add <IdShouldBeMappedToRowKeyAndPartitionKeyConvention>();

            var scannedAssemblies = typesToScan.Select(t => t.Assembly).Distinct();

            var nhibernateConfiguration = new Configuration().SetProperties(nhibernateProperties);

            foreach (var assembly in scannedAssemblies)
            {
                nhibernateConfiguration.AddAssembly(assembly);
            }

            var fluentConfiguration = Fluently.Configure(nhibernateConfiguration)
                                      .Mappings(m => m.AutoMappings.Add(model));

            ApplyDefaultsTo(fluentConfiguration);

            try
            {
                var factory = fluentConfiguration.BuildSessionFactory();

                if (updateSchema)
                {
                    UpdateDatabaseSchemaUsing(fluentConfiguration, factory);
                }

                return(factory);
            }
            catch (FluentConfigurationException e)
            {
                if (e.InnerException != null)
                {
                    throw new ConfigurationErrorsException(e.InnerException.Message, e);
                }

                throw;
            }
        }
예제 #26
0
        protected ISessionFactory CreateSessionFactory()
        {
            var uriString = ConfigurationManager.AppSettings["JUSTONEDB_DBI_URL"]
                            ?? ConfigurationManager.AppSettings["CHRONICDB_URL"]
                            ?? ConfigurationManager.AppSettings["ELEPHANTSQL_URL"]
                            ?? Environment.GetEnvironmentVariable("DATABASE_URL");
            var uri = new Uri(uriString);
            var connectionString = string.Format("Server={0};Port={1};Database={2};User Id={3};Password={4};",
                                                 uri.Host, uri.Port, uri.AbsolutePath.Trim('/'), uri.UserInfo.Split(':').First(),
                                                 uri.UserInfo.Split(':').Last());

            var autoMap = AutoMap.AssemblyOf <Entity>()
                          .Where(t => typeof(Entity).IsAssignableFrom(t));

            return(Fluently.Configure()
                   .Database(
                       PostgreSQLConfiguration.Standard.ConnectionString(connectionString))
                   .Mappings(m => m.AutoMappings.Add(autoMap))
                   .ExposeConfiguration(TreatConfiguration)
                   .BuildSessionFactory());
        }
        protected override void EstablishContext()
        {
            base.EstablishContext();

            SessionFactory = Fluently.Configure()
                             .Database(
                MsSqlConfiguration.MsSql2005
                .AdoNetBatchSize(100)
                .ConnectionString(s => s.Is("Server=(local);initial catalog=test;Trusted_Connection=yes"))
                .DefaultSchema("dbo")
                .ShowSql()
                .ProxyFactoryFactory("NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle")
                .Raw(Environment.Isolation, IsolationLevel.RepeatableRead.ToString()))
                             .Mappings(m =>
            {
                m.FluentMappings.Add <ConcurrentSagaMap>();
                m.FluentMappings.Add <ConcurrentLegacySagaMap>();
            })
                             .ExposeConfiguration(BuildSchema)
                             .BuildSessionFactory();
        }
예제 #28
0
파일: DataBase.cs 프로젝트: goffman/tms
        private static void OpenConnection()
        {
            ISessionFactory factory = Fluently.Configure()
                                      .Database(MsSqlConfiguration.MsSql2012.ConnectionString(builder =>
                                                                                              builder.Database("tms").
                                                                                              Password("123").
                                                                                              Server("SERVERBD\\SQLSERVER2014").
                                                                                              Username("sa")).ShowSql())
                                      .Mappings(configuration => configuration.FluentMappings.Add <TestirovanieMap>())
                                      .Mappings(configuration => configuration.FluentMappings.Add <LkabinetMap>())
                                      .Mappings(configuration => configuration.FluentMappings.Add <LpuMap>())
                                      .Mappings(configuration => configuration.FluentMappings.Add <VoprosyMap>())
                                      .Mappings(configuration => configuration.FluentMappings.Add <OtvetiMap>())
                                      .Mappings(configuration => configuration.FluentMappings.Add <ProhozhdenieTestaMap>())
                                      .Mappings(configuration => configuration.FluentMappings.Add <DolzhnostMap>())
                                      .Mappings(configuration => configuration.FluentMappings.Add <GruppaDolzhnostMap>())
                                      .ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(false, true))
                                      .BuildSessionFactory();

            _sessionFactory = factory;
        }
예제 #29
0
        public override void Load()
        {
            Bind <ISessionFactory>()
            .ToMethod
            (
                e =>
                Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c =>
                                                                        c.FromConnectionStringWithKey("Data Source=MANSUR\\SQLEXPRESS;Initial Catalog=BlogHopefully;User ID=humzahc;Password=***********")))
                .Cache(c => c.UseQueryCache().ProviderClass <HashtableCacheProvider>())
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf <Post>())
                //.ExposeConfiguration(cfg => new SchemaExport(cfg).Execute(true, true, false))
                .BuildConfiguration()
                .BuildSessionFactory()
            )
            .InSingletonScope();

            Bind <ISession>()
            .ToMethod((ctx) => ctx.Kernel.Get <ISessionFactory>().OpenSession())
            .InRequestScope();
        }
예제 #30
0
 private ISessionFactory SQLServer()
 {
     return(Fluently.Configure()
            .Database(
                MsSqlConfiguration.MsSql2012.ConnectionString(c => c.FromConnectionStringWithKey("ConnectionStringSQL"))
                //MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("ConnectionStringSQL"))
                )
            //.Cache(c => c.UseQueryCache().ProviderClass(typeof(NHibernate.Caches.SysCache2.SysCacheProvider).AssemblyQualifiedName))
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf <PessoaMap>()//x => x.GetProperty("Codigo") != null
                      .Conventions.Setup(GetConventions(true)))
            .ExposeConfiguration(cfg => cfg.SetProperty(Environment.CurrentSessionContextClass, "web"))
            .ExposeConfiguration(cfg => cfg.SetProperty(Environment.UseQueryCache, "true"))
            .ExposeConfiguration(cfg => cfg.SetListener(ListenerType.PostUpdate, new AuditEventListener()))
            .ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(false, true)) //Atualiza o banco com as novas entidades adicionadas
                                                                                    //-----------------------------------------------------------------//
                                                                                    //.ExposeConfiguration(cfg => new SchemaExport(cfg).Drop(false, true))
                                                                                    //.ExposeConfiguration(cfg => new SchemaExport(cfg).Create(false, true))
                                                                                    //Cuidado essa linha acima cria nova base de dados!
            .CurrentSessionContext("web")
            .BuildSessionFactory());
 }