public static IDictionary<string, ISessionFactory> BuildSessionFactory()
        {
           // var configure = new Configuration();
            var mapping = GetMappings();
            //configure.Configure();
            //configure.AddDeserializedMapping(mapping, "NHSchema");
            if (!CommonHelper.AllowMultiTenancy(out _ConnectionStringName))
            {
                var config = new Configuration();
                // config.SetInterceptor(new NHSQLInterceptor());
                config.Configure();
                var _host = EngineContext.Current.Resolve<HttpContextBase>().Request.Url.Authority;
                config.AddDeserializedMapping(mapping, "NHSchema");

                config.Configure()
                    .SetProperty(NHibernate.Cfg.Environment.ConnectionStringName, _ConnectionStringName)
                    .
                    SetProperty(NHibernate.Cfg.Environment.ShowSql, "true")
                    .SetProperty(NHibernate.Cfg.Environment.BatchSize, "0")
                    .SetProperty(NHibernate.Cfg.Environment.CacheRegionPrefix, _host);

                if (!_allFactories.ContainsKey(_host))
                    _allFactories.Add(_host, config.BuildSessionFactory());

            }
            else
            {
                XmlNodeList nodes = ConfigurationFile.GetElementsByTagName("Tenant");

                foreach (XmlNode n in nodes)
                {

                    var config = new Configuration();
                    // config.SetInterceptor(new NHSQLInterceptor());
                    config.Configure();

                    config.AddDeserializedMapping(mapping, "NHSchema");

                    config.Configure()
                        .SetProperty(NHibernate.Cfg.Environment.ConnectionString, n["ConnectionString"].InnerText)
                        .
                        SetProperty(NHibernate.Cfg.Environment.ShowSql, "true")
                        .SetProperty(NHibernate.Cfg.Environment.BatchSize, "0")
                        .SetProperty(NHibernate.Cfg.Environment.CacheRegionPrefix, n["HostName"].InnerText);
                    //  config.SetInterceptor(new NHSQLInterceptor());

                    if (!_allFactories.ContainsKey(n["HostName"].InnerText))
                        _allFactories.Add(n["HostName"].InnerText, config.BuildSessionFactory());

                }
            }
            return _allFactories;


        }
Beispiel #2
0
        private string GetConnectionString()
        {
            var config = new Configuration();

            if (string.IsNullOrEmpty(_configurationFilePath))
            {
                config.Configure();
            }
            else
            {
                config.Configure(_configurationFilePath);
            }
            return(config.GetProperty("connection.connection_string"));
        }
Beispiel #3
0
 static void Main(string[] args)
 {
     NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
     cfg.Configure();
     NHibernate.Tool.hbm2ddl.SchemaExport schema = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);
     schema.Create(false, true);
 }
Beispiel #4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSingleton <ISessionFactory>((provider) => {
                var cfg = new NHibernate.Cfg.Configuration();
                cfg.Configure();
                return(cfg.BuildSessionFactory());
            });

            services.AddScoped <ISession>((provider) => {
                var factory = provider.GetService <ISessionFactory>();
                return(factory.OpenSession());
            });
            services.AddScoped <IFlatRepository, FlatRepository>();
            services.AddScoped <IModelRepository, ModelRepository>();
            services.AddScoped <IUserRepository, UserRepository>();
            services.AddAutoMapper(typeof(MappingProfiles));
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "API", Version = "v1"
                });
            });

            services.AddCors(opt =>
            {
                opt.AddPolicy("CorsPolicy", policy =>
                {
                    policy.WithOrigins("https://localhost:4200", "http://localhost:4200")
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials();
                });
            });
        }
Beispiel #5
0
 public static void Init(IHostingEnvironment env)
 {
     try
     {
         NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
         string path = string.Empty;
         if (string.IsNullOrEmpty(configfilepath))
         {
             //  var appEnv = CallContextServiceLocator.Locator.ServiceProvider.GetService(typeof(IHostingEnvironment)) as IHostingEnvironment;
             path = System.IO.Path.Combine(env.ContentRootPath, "hibernate.cfg.xml");
             //path = @"D:\Suresh\BickBucket\src\Api.Socioboard\hibernate.cfg.xml";
         }
         else
         {
             path = configfilepath;
         }
         config.Configure(path);
         config.AddAssembly(Assembly.GetExecutingAssembly());//adds all the embedded resources .hbm.xml
         sFactory = config.BuildSessionFactory();
     }
     catch (Exception ex)
     {
         throw ex;
         //Console.Write(ex.StackTrace);
         //logger.Error(ex.Message);
     }
 }
Beispiel #6
0
        public static ISessionFactory FactoryGet()
        {
            ISessionFactory factory = null;

            if (HttpContext.Current != null)
            {
                try
                {
                    factory = (ISessionFactory)HttpContext.Current.Application[ContextFactoryKey];
                }
                catch (Exception)
                {
                }
            }

            if (factory == null)
            {
                try
                {
                    NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
                    cfg.Configure(System.Web.HttpContext.Current.Server.MapPath("~/hibernate.cfg.xml.config"));
                    factory = cfg.BuildSessionFactory();

                    if (HttpContext.Current != null)
                    {
                        HttpContext.Current.Application[ContextFactoryKey] = factory;
                    }
                }
                catch (Exception)
                {
                }
            }

            return(factory);
        }
        public void TestFixtureSetUp()
        {
            container = new WindsorContainer();
            log4net.Config.XmlConfigurator.Configure();

            ConfigureWindsorContainer();

            Environment.UseReflectionOptimizer = true;
            Environment.BytecodeProvider       = new EnhancedBytecode(container);

            cfg = new NHibernate.Cfg.Configuration();

            cfg.Configure();

            cfg.Properties[Environment.ProxyFactoryFactoryClass]   = GetProxyFactoryFactory();
            cfg.Properties[Environment.CurrentSessionContextClass] = "thread_static";
            cfg.RegisterEntityNameResolver();
            cfg.Interceptor = GetInterceptor();
            cfg.AddAssembly(typeof(IntegrationBaseTest).Assembly);

            new SchemaExport(cfg).Create(true, true);
            sessions = (ISessionFactoryImplementor)cfg.BuildSessionFactory();


            var componentInterceptor = cfg.Interceptor as Castle.NHibernateInterceptor.ComponentBehaviorInterceptor;

            if (componentInterceptor != null)
            {
                componentInterceptor.SessionFactory = sessions;
            }
        }
       /// <summary>
        /// This method attempts to find a session factory stored in <see cref="_sessionFactories" />
        /// via its name; if it can't be found it creates a new one and adds it the hashtable.
        /// </summary>
        /// <param name="sessionFactoryConfigPath">Path location of the factory config</param>
        public ISessionFactory GetSessionFactoryFor(string sessionFactoryConfigPath) {
            Check.Require(!string.IsNullOrEmpty(sessionFactoryConfigPath),
                "sessionFactoryConfigPath may not be null nor empty");

            //  Attempt to retrieve a stored SessionFactory from the hashtable.
            ISessionFactory sessionFactory = (ISessionFactory) _sessionFactories[sessionFactoryConfigPath];

            //  Failed to find a matching SessionFactory so make a new one.
            if (sessionFactory == null) {
                Check.Require(File.Exists(sessionFactoryConfigPath),
                    "The config file at '" + sessionFactoryConfigPath + "' could not be found");

                NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
                cfg.Configure(sessionFactoryConfigPath);

                //  Now that we have our Configuration object, create a new SessionFactory
                sessionFactory = cfg.BuildSessionFactory();

                if (sessionFactory == null) {
                    throw new InvalidOperationException("cfg.BuildSessionFactory() returned null.");
                }

                _sessionFactories.Add(sessionFactoryConfigPath, sessionFactory);
            }

            return sessionFactory;
        }
Beispiel #9
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);

            var configuration = new NHibernate.Cfg.Configuration();
            configuration.Configure();
            configuration.AddAssembly(typeof(doCS.Models.Project).Assembly);
            SessionFactory = configuration.BuildSessionFactory();

            // Build up your application container and register your dependencies.
            var builder = new ContainerBuilder();
            builder.RegisterControllers(System.Reflection.Assembly.GetExecutingAssembly());
            builder.Register(x => SessionFactory.OpenSession()).As<ISession>().HttpRequestScoped();
            builder.RegisterType<doCS.Web.Helpers.Implimentation.ProjectContext>().As<doCS.Web.Helpers.IProjectContext>().HttpRequestScoped();

            //register extractor helpers
            builder.RegisterType<doCS.Web.Helpers.Implimentation.Extractor.ExtractorHelper>().As<doCS.Web.Helpers.IExtractorHelper>().HttpRequestScoped();
            builder.RegisterType<doCS.Web.Helpers.Implimentation.Extractor.ProjectUpdaterProvider>().InstancePerDependency();

            //register extractor dependencies
            builder.RegisterType<doCS.Extractor.Implementation.Extractor>().As<doCS.Extractor.IExtractor>().HttpRequestScoped();
            builder.RegisterType<doCS.Extractor.Implementation.DllExtractor>();
            builder.RegisterType<doCS.Extractor.Implementation.XmlExtractor>();

            //register view helpers
            builder.RegisterType<doCS.Web.ViewHelpers.XmlDocumentationHelper>();

            _containerProvider = new ContainerProvider(builder.Build());
            ControllerBuilder.Current.SetControllerFactory(new AutofacControllerFactory(ContainerProvider));

            SetupAutoMapper();
        }
Beispiel #10
0
        internal static NHibernate.Cfg.Configuration BuildConfiguration()
        {
            NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
            config.Configure();

            return(config);
        }
        protected NhibernateConfigurator(bool mapDtoAssembly)
        {
            var assembliesToMap = GetAssembliesToMap(mapDtoAssembly);
            var includeBaseTypes = GetIncludeBaseTypes();
            var ignoreBaseTypes = GetIgnoreBaseTypes();
            var discriminatedTypes = GetDiscriminatedTypes();
            var mapDefaultConventions = ShouldMapDefaultConventions();
            var assemblyWithAdditionalConventions = GetAssembliesWithAdditionalConventions();

            _configuration = new Configuration();
            _configuration.Configure();
            var autoPersistenceModel = AutoMap.Assemblies(new AutomappingConfiguration(discriminatedTypes.ToArray()), assembliesToMap);
            includeBaseTypes.Each(x => autoPersistenceModel.IncludeBase(x));
            ignoreBaseTypes.Each(x => autoPersistenceModel.IgnoreBase(x));
            assembliesToMap.Each(x => autoPersistenceModel.UseOverridesFromAssembly(x));
            if (mapDefaultConventions) autoPersistenceModel.Conventions.AddFromAssemblyOf<PrimaryKeyConvention>();
            assemblyWithAdditionalConventions.Each(x => autoPersistenceModel.Conventions.AddAssembly(x));

            _sessionFactory = Fluently.Configure(_configuration)
                .Mappings(x =>
                              {
                                  var mappingsContainer = x.AutoMappings.Add(autoPersistenceModel);
                                  var exportNhibernateMappingsFolder = ConfigurationManager.AppSettings["ExportNhibernateMappingsFolder"];
                                  if (!string.IsNullOrWhiteSpace(exportNhibernateMappingsFolder)) mappingsContainer.ExportTo(exportNhibernateMappingsFolder);
                              })
                .BuildSessionFactory();
        }
Beispiel #12
0
        public static void Main(string[] args)
        {
            IList<Product> products;

            // Don't need to use schema export because of the hbm2dll property.
            var cfg = new NHibernate.Cfg.Configuration();
            cfg.Configure();
            // ensure that mapping hbm.xml file is loaded
            cfg.AddAssembly(typeof(MainClass).Assembly);

            Product p = new Product() {Name="Captains of Crush Gripper #1", Category="fitness" };

            ISessionFactory factory =
                cfg.BuildSessionFactory();

            using (ISession session = factory.OpenSession())
            {
                session.Save(p);
                session.Flush();

              	ICriteria sc = session.CreateCriteria<Product>();
              	products = sc.List<Product>();
                Console.WriteLine(products[0].Name);
              	session.Close();
            }
            factory.Close();

            Console.WriteLine( products.Count );

            Console.WriteLine ("Hello World!");
        }
        public void WorkWithOutSharedEngine()
        {
            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
            if (TestConfigurationHelper.hibernateConfigFile != null)
                cfg.Configure(TestConfigurationHelper.hibernateConfigFile);
            string[] mappings =
                new string[]
                    {
                        "Integration.Address.hbm.xml",
                        "Integration.Tv.hbm.xml",
                        "Integration.TvOwner.hbm.xml",
                        "Integration.Martian.hbm.xml",
                        "Integration.Music.hbm.xml"
                    };
            foreach (string file in mappings)
            {
                cfg.AddResource("NHibernate.Validator.Tests" + "." + file, Assembly.GetExecutingAssembly());
            }
            Environment.SharedEngineProvider = null;
            XmlConfiguration nhvc = new XmlConfiguration();
            nhvc.Properties[Environment.ApplyToDDL] = "true";
            nhvc.Properties[Environment.AutoregisterListeners] = "true";
            nhvc.Properties[Environment.ValidatorMode] = "UseAttribute";

            ValidatorInitializer.Initialize(cfg);
        }
        public void ApplyWrongConstraint()
        {
            XmlConfigurator.Configure();
            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
            if (TestConfigurationHelper.hibernateConfigFile != null)
                cfg.Configure(TestConfigurationHelper.hibernateConfigFile);
            cfg.AddResource("NHibernate.Validator.Tests.Integration.WrongClass.whbm.xml", Assembly.GetExecutingAssembly());
            Environment.SharedEngineProvider = null;
            XmlConfiguration nhvc = new XmlConfiguration();
            nhvc.Properties[Environment.ApplyToDDL] = "true";
            nhvc.Properties[Environment.AutoregisterListeners] = "true";
            nhvc.Properties[Environment.ValidatorMode] = "UseAttribute";

            using (LoggerSpy ls = new LoggerSpy(typeof(ValidatorInitializer), Level.Warn))
            {
                ValidatorInitializer.Initialize(cfg);
                int found =
                    ls.GetOccurenceContaining(
                        string.Format("Unable to apply constraints on DDL for [MappedClass={0}]", typeof (WrongClass).FullName));
                Assert.AreEqual(1, found);
                found =
                    ls.GetOccurenceContaining(
                        string.Format("Unable to apply constraints on DDL for [MappedClass={0}]", typeof (WrongClass1).FullName));
                Assert.AreEqual(1, found);
            }
        }
        public FluentConfiguration GetConfiguration(ITenant tenant)
        {
            var assemblyMappingName = tenant.AssemblyMappingName;

            if (string.IsNullOrWhiteSpace(assemblyMappingName))
            {
                throw new InvalidOperationException("AssemblyMappingName não encontrado, por favor defina o assembly que contém os mapeamentos da classe no Web.Config/App.Config ou na classe de implementação da interface ITenant");
            }

            var configuration   = new Configuration();
            var hibernateConfig = DefaultHibernateConfig;

            if (Path.IsPathRooted(hibernateConfig) == false)
            {
                hibernateConfig = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, hibernateConfig);
            }

            if (File.Exists(hibernateConfig))
            {
                configuration.Configure(new XmlTextReader(hibernateConfig));
            }

            if (!string.IsNullOrWhiteSpace(tenant.ConnectionString))
            {
                configuration.SetProperty("connection.connection_string", tenant.ConnectionString);
                if (configuration.Properties.ContainsKey("connection.connection_string_name"))
                {
                    configuration.Properties.Remove("connection.connection_string_name");
                }
            }

            var fluentlyCfg = Fluently.Configure(configuration).Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.Load(assemblyMappingName)));

            return(fluentlyCfg);
        }
Beispiel #16
0
 public static void Init()
 {
     try
     {
         NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
         string path        = string.Empty;
         string wanted_path = System.IO.Directory.GetCurrentDirectory();
         if (string.IsNullOrEmpty(configfilepath))
         {
             path = wanted_path + "\\hibernate.cfg.xml";
         }
         else
         {
             path = configfilepath;
         }
         config.Configure(path);
         config.AddAssembly(Assembly.GetExecutingAssembly());//adds all the embedded resources .hbm.xml
         sFactory = config.BuildSessionFactory();
     }
     catch (Exception ex)
     {
         throw ex;
         //Console.Write(ex.StackTrace);
         //logger.Error(ex.Message);
     }
 }
Beispiel #17
0
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);

            // NHibernate configuration
            var configuration = new NHibernate.Cfg.Configuration();

            configuration.Configure();
            configuration.AddAssembly(typeof(Log).Assembly);
            ISessionFactory sessionFactory = configuration.BuildSessionFactory();

            // Ninject
            Ninject.IKernel container = new StandardKernel();

            // Set Web API Resolver
            GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(container);
            container.Bind <ISessionFactory>().ToConstant(sessionFactory);

            container.Bind <ISessionManager>().To <SessionManager>();
            container.Bind <IRepository>().To <GenericRepository>();

            container.Bind <IApplicationService>().To <ApplicationService>();
            container.Bind <ITokenService>().To <TokenService>();
            container.Bind <ILogService>().To <LogService>();

            container.Bind <IApplicationMapper>().To <ApplicationMapper>();
        }
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            log4net.Config.XmlConfigurator.Configure();
            MvcHandler.DisableMvcResponseHeader = true;

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            EmailVerifier.RuntimeLicenseKey = "G016NUILAeGgF81JMB03zbbnuDKKCWJhQ9XYfo8HVhhJLA+Uk2l8Jqyqumxb9Pn78MEhaA==";

            DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAttribute), typeof(RegularExpressionAttributeAdapter));

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            Core.User.CurrentUserId = "NewWebsite";
            foreach (var t in  typeof(Area).Assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(MetaBase))))
            {
                BaseEntity.MetaTypes.Add(t);
            }

            var config = new NHibernate.Cfg.Configuration();

            config.Configure();
            config.AddAssembly(typeof(NHibernateHelper).Assembly);
            config.AddAssembly(typeof(Page).Assembly);
            Global.SessionFactory = config.BuildSessionFactory();
        }
        public void WorkWithOutSharedEngine()
        {
            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
            if (TestConfigurationHelper.hibernateConfigFile != null)
            {
                cfg.Configure(TestConfigurationHelper.hibernateConfigFile);
            }
            string[] mappings =
                new string[]
            {
                "Integration.Address.hbm.xml",
                "Integration.Tv.hbm.xml",
                "Integration.TvOwner.hbm.xml",
                "Integration.Martian.hbm.xml",
                "Integration.Music.hbm.xml"
            };
            foreach (string file in mappings)
            {
                cfg.AddResource("NHibernate.Validator.Tests" + "." + file, Assembly.GetExecutingAssembly());
            }
            Environment.SharedEngineProvider = null;
            XmlConfiguration nhvc = new XmlConfiguration();

            nhvc.Properties[Environment.ApplyToDDL]            = "true";
            nhvc.Properties[Environment.AutoregisterListeners] = "true";
            nhvc.Properties[Environment.ValidatorMode]         = "UseAttribute";

            ValidatorInitializer.Initialize(cfg);
        }
Beispiel #20
0
        /// <summary>
        /// 创建StatelessDbSession对象
        /// </summary>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="dbDialectProvider">数据库特性对象提供程序</param>
        /// <param name="mappingXml">实体关系映射配置Xml文本</param>
        /// <returns>返回StatelessDbSession对象</returns>
        public virtual StatelessDbSession CreateStatelessDbSession(string connectionString, IDbDialectProvider dbDialectProvider, string mappingXml)
        {
            ISessionFactory sf = null;
            while (!sessionFactories.TryGetValue(connectionString, out sf))
            {
                IDictionary<string, string> dbSetting = new Dictionary<string, string>
                {
                    ["dialect"] = dbDialectProvider.DialectName,
                    ["connection.connection_string"] = connectionString,
                };
                CustomizeNHSessionFactory(dbSetting);
                var x = new NHibernate.Cfg.Configuration();
                x = x.AddProperties(dbSetting);
                //允许采用配置文件修改NHibernate配置
                var hc = ConfigurationManager.GetSection(CfgXmlHelper.CfgSectionName) as NHibernate.Cfg.IHibernateConfiguration;
                if ((hc != null && hc.SessionFactory != null) || File.Exists(GetDefaultConfigurationFilePath()))
                {
                    x = x.Configure();
                }
                if (System.Transactions.Transaction.Current != null)
                {
                    //如果在分布式事务范围内,就将连接释放模式更改为on_close模式,防止auto模式下,重新获取连接,导致分布式事务升级
                    x.AddProperties(new Dictionary<string, string> {["connection.release_mode"] = "on_close" });
                }
                //添加实体关系映射
                if (!string.IsNullOrWhiteSpace(mappingXml))
                {
                    x.AddXml(mappingXml);
                }

                sf = x.BuildSessionFactory();
                sessionFactories.TryAdd(connectionString, sf);
            }
            return new StatelessDbSession(sf, connectionString);
        }
 /// <summary>
 /// Standar Configuration for tests.
 /// </summary>
 /// <returns>The configuration using merge between App.Config and hibernate.cfg.xml if present.</returns>
 public static NHibernate.Cfg.Configuration GetDefaultConfiguration()
 {
     NHibernate.Cfg.Configuration result = new NHibernate.Cfg.Configuration();
     if (hibernateConfigFile != null)
         result.Configure(hibernateConfigFile);
     return result;
 }
        /// <summary>
        /// 静态构造函数
        /// </summary>
        static NHHelper()
        {
            var config = new NHibernate.Cfg.Configuration();

            config.Configure();
            factory = config.BuildSessionFactory();
        }
Beispiel #23
0
        private static ISessionFactory GetFactory()
        {
            if (sessionFactory == null)
            {
                HttpContext currentContext = HttpContext.Current;

                NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();

                if (config == null)
                {
                    throw new InvalidOperationException("Nhibernate configuration is null");
                }

                var path = string.IsNullOrEmpty(HttpRuntime.AppDomainAppId) ? AppDomain.CurrentDomain.BaseDirectory : HttpRuntime.AppDomainAppPath;

                config.Configure(string.Format("{0}/Config/Nhibernate/HttpReadNHibernate.cfgl.xml", path));

                sessionFactory = config.BuildSessionFactory();

                if (sessionFactory == null)
                {
                    throw new InvalidOperationException("Call to Configuration.BuildSessionFactory() returned null.");
                }
            }
            return(sessionFactory);
        }
Beispiel #24
0
 public static void Init()
 {
     try
     {
         NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
         string path        = string.Empty;
         string wanted_path = System.IO.Directory.GetCurrentDirectory();
         if (string.IsNullOrEmpty(configfilepath))
         {
             //                  var appEnv = CallContextServiceLocator.Locator.ServiceProvider
             //.GetService(typeof(IApplicationEnvironment)) as IApplicationEnvironment;
             //  path = System.IO.Path.Combine(System.Reflection.Assembly.GetExecutingAssembly().Location, "hibernate.cfg.xml");
             //path = System.Reflection.Assembly.GetExecutingAssembly().Location;
             // path = @"D:\bitbucket\Updated\src\SocioboardDataServices\hibernate.cfg.xml";
             path = wanted_path + "\\hibernate.cfg.xml";
         }
         else
         {
             path = configfilepath;
         }
         config.Configure(path);
         config.AddAssembly(Assembly.GetExecutingAssembly());//adds all the embedded resources .hbm.xml
         sFactory = config.BuildSessionFactory();
     }
     catch (Exception ex)
     {
         throw ex;
         //Console.Write(ex.StackTrace);
         //logger.Error(ex.Message);
     }
 }
        public void ApplyWrongConstraint()
        {
            XmlConfigurator.Configure();
            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
            if (TestConfigurationHelper.hibernateConfigFile != null)
            {
                cfg.Configure(TestConfigurationHelper.hibernateConfigFile);
            }
            cfg.AddResource("NHibernate.Validator.Tests.Integration.WrongClass.whbm.xml", Assembly.GetExecutingAssembly());
            Environment.SharedEngineProvider = null;
            XmlConfiguration nhvc = new XmlConfiguration();

            nhvc.Properties[Environment.ApplyToDDL]            = "true";
            nhvc.Properties[Environment.AutoregisterListeners] = "true";
            nhvc.Properties[Environment.ValidatorMode]         = "UseAttribute";

            using (LoggerSpy ls = new LoggerSpy(typeof(ValidatorInitializer), Level.Warn))
            {
                ValidatorInitializer.Initialize(cfg);
                int found =
                    ls.GetOccurenceContaining(
                        string.Format("Unable to apply constraints on DDL for [MappedClass={0}]", typeof(WrongClass).FullName));
                Assert.AreEqual(1, found);
                found =
                    ls.GetOccurenceContaining(
                        string.Format("Unable to apply constraints on DDL for [MappedClass={0}]", typeof(WrongClass1).FullName));
                Assert.AreEqual(1, found);
            }
        }
Beispiel #26
0
        /// <summary>
        ///   Initializes this instance.
        /// </summary>
        /// <param name="configure"></param>
        public void Initialize(Action <Configuration> configure)
        {
            Configuration = new Configuration();
            if (string.IsNullOrWhiteSpace(ConfigurationFile))
            {
                missingConfigurations.Add(
                    new MissingConfiguration(
                        "Property ConfigurationFile of NHibernateContext is required. Maybe you forgot to add the key NHibernate.ConfigurationFile in the <appSettings> section of your configuration file."));
                return;
            }

            var path = LocalPath.From(ConfigurationFile);

            Log.Info(string.Format("Loading NHibernate Configuration from {0}", path));
            Configuration.Configure(path);
            Log.Info(string.Format("End Loading NHibernate Configuration from {0}", path));

            if (!ValidateConnectionStringExistence(Configuration))
            {
                return;
            }

            configure(Configuration);

            Log.Info("Building new Hibernate Session Factory");
            sessionFactory = Configuration.BuildSessionFactory();
            Log.Info("En Building new Hibernate Session Factory");
        }
 public NHibernate.Cfg.Configuration ConfigureNHibernate()
 {
     var cfg = new NHibernate.Cfg.Configuration();
     if (TestConfigurationHelper.hibernateConfigFile != null)
         cfg.Configure(TestConfigurationHelper.hibernateConfigFile);
     cfg.AddResource("NHibernate.Validator.Tests.Specifics.NHV82.Person.hbm.xml", Assembly.GetExecutingAssembly());
     return cfg;
 }
 private SessionManager()
 {
     Configuration config = new Configuration();
     config.Properties[NHibernate.Cfg.Environment.ConnectionString] =
         ConfigurationManager.ConnectionStrings["AtomicCms"].ConnectionString;
     config.Configure();
     this.sessionFactory = config.BuildSessionFactory();
 }
 /// <summary>
 /// Generate the database schema, apply it to the database and save the DDL used into a file.
 /// </summary>
 public static void CreateDatabase()
 {
     Configuration configuration = new Configuration();
     configuration.Configure();
     SchemaExport schemaExport = new SchemaExport(configuration);
     schemaExport.SetOutputFile("SQLite database schema.ddl");
     schemaExport.Create(true, true);
 }
Beispiel #30
0
        public Database()
        {
            var configuration = new NHibernate.Cfg.Configuration();

            configuration.Configure();
            configuration.AddAssembly(Assembly.GetExecutingAssembly());
            sessionFactory = configuration.BuildSessionFactory();
        }
        public NHibernate.Cfg.Configuration GetConfiguration()
        {
            if (_configuration != null)
            {
                return(_configuration);
            }

            var cfg = new NHibernate.Cfg.Configuration();

            {
                cfg.Configure(@"OrmNhib/NHibernateConfig/hibernate.cfg.xml");

                foreach (var mapping in cfg.ClassMappings)
                {
                    string x = $"(1) {mapping.ClassName}, (2) {mapping.Discriminator}, (3) {mapping.DiscriminatorValue}, (4) {mapping.IsDiscriminatorValueNotNull}";
                    System.Diagnostics.Debug.WriteLine(x);
                }

                var schemaExport = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);
                schemaExport.SetOutputFile(@"db.Postgre.sql").Execute(
                    useStdOut: true, execute: true, justDrop: false);

                // Alternately, we can use SchemaUpdate.Execute, as in done in 1P
                NHibernate.Tool.hbm2ddl.SchemaUpdate schemaUpdate = new NHibernate.Tool.hbm2ddl.SchemaUpdate(cfg);
                schemaUpdate.Execute(useStdOut: true, doUpdate: true);

                try
                {
                    SchemaValidator schemaValidator = new SchemaValidator(cfg);
                    schemaValidator.Validate();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Exception: {ex}");
                }


                // Note
                // SchemaUpdate.Execute is way cooler than SchemaExport.Filename.Execute
                // When I added a new property in Movie.hbm.xml (and in the .cs), SchemaUpdate automatically created statement
                // to tell the diff in schema, and only this got executed:

                /*
                 *  alter table Movie
                 *      add column NewProp VARCHAR(255)
                 *
                 * */
                //
                // However, it does not work as expected all the times, for eg,
                // if I rename a column in HBM, it just adds a new column with new name
                // if I change the sql-type from VARCHAR(255) to VARCHAR(100), nothing is executed and the column type remains unchanged
                // So we will need manual scripts for migration
                //
            }

            _configuration = cfg;
            return(_configuration);
        }
Beispiel #32
0
        private static Configuration RecuperaConfiguracao()
        {
            Configuration cfg = new Configuration();

            cfg.Configure();
            cfg.AddAssembly(Assembly.GetExecutingAssembly());

            return(cfg);
        }
 public static ISessionFactory GetSessionFactory()
 {
     var configuration = new NHibernate.Cfg.Configuration();
     configuration.Configure();
     configuration.AddAssembly(typeof(SessionFactoryFactory).Assembly.GetName().Name);
     log4net.Config.XmlConfigurator.Configure();
     var sessionFactory = configuration.BuildSessionFactory();
     return sessionFactory;
 }
        public void CanGenerateSchema()
        {
            var cfg = new NHibernate.Cfg.Configuration();

            cfg.Configure();
            cfg.AddAssembly(Assembly.Load("InfoHub.Entity"));

            new SchemaExport(cfg).Execute(false, true, false);
        }
Beispiel #35
0
        private SessionManager()
        {
            Configuration config = new Configuration();

            config.Properties[NHibernate.Cfg.Environment.ConnectionString] =
                ConfigurationManager.ConnectionStrings["AtomicCms"].ConnectionString;
            config.Configure();
            this.sessionFactory = config.BuildSessionFactory();
        }
 /// <summary>
 /// Standar Configuration for tests.
 /// </summary>
 /// <returns>The configuration using merge between App.Config and hibernate.cfg.xml if present.</returns>
 public static NHibernate.Cfg.Configuration GetDefaultConfiguration()
 {
     NHibernate.Cfg.Configuration result = new NHibernate.Cfg.Configuration();
     if (hibernateConfigFile != null)
     {
         result.Configure(hibernateConfigFile);
     }
     return(result);
 }
Beispiel #37
0
        public void CreateDatabase()
        {
            var cfg = new NHibernate.Cfg.Configuration();

            cfg.Configure();

            var schema = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);

            schema.Execute(true, false, false);
        }
 public NHibernateConfigurator()
 {
     _configuration = new Configuration();
     _configuration.Configure();
     _configuration.Properties.Add("use_proxy_validator", "false");
     if (NHProfilerIsEnable())
     {
         NHibernateProfiler.Initialize();
     }
 }
Beispiel #39
0
        /// <summary>
        /// Generate the database schema, apply it to the database and save the DDL used into a file.
        /// </summary>
        public static void CreateDatabase()
        {
            Configuration configuration = new Configuration();

            configuration.Configure();
            SchemaExport schemaExport = new SchemaExport(configuration);

            schemaExport.SetOutputFile("SQLite database schema.ddl");
            schemaExport.Create(true, true);
        }
Beispiel #40
0
        private static ISessionFactory InitializeSessionFactory()
        {
            var cfg = new NHibernate.Cfg.Configuration();
            cfg.Configure();

            return Fluently.Configure(cfg)
                .Mappings(m => m.AutoMappings
                    .Add(CreateAutomappings))
                .BuildSessionFactory();
        }
        public static ISessionFactory GetSessionFactory()
        {
            var configuration = new NHibernate.Cfg.Configuration();

            configuration.Configure();
            configuration.AddAssembly(typeof(SessionFactoryFactory).Assembly.GetName().Name);
            log4net.Config.XmlConfigurator.Configure();
            var sessionFactory = configuration.BuildSessionFactory();

            return(sessionFactory);
        }
Beispiel #42
0
        static void Generate()
        {
            var cfg = new NHibernate.Cfg.Configuration();

            cfg.Configure();
            cfg.AddAssembly(typeof(Job).Assembly);
            //var n = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg).Execute(false, true, false, false);
            var export = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);

            export.Create(false, true);
        }
Beispiel #43
0
        public NHibernate.Cfg.Configuration ConfigureNHibernate()
        {
            var cfg = new NHibernate.Cfg.Configuration();

            if (TestConfigurationHelper.hibernateConfigFile != null)
            {
                cfg.Configure(TestConfigurationHelper.hibernateConfigFile);
            }
            cfg.AddResource("NHibernate.Validator.Tests.Specifics.NHV82.Person.hbm.xml", Assembly.GetExecutingAssembly());
            return(cfg);
        }
Beispiel #44
0
 DomainAccess()
 {
     var cfg = new NHibernate.Cfg.Configuration();
     cfg.Configure();
     session = Fluently.Configure()
         .Database(MsSqlConfiguration.MsSql2005.ConnectionString(x => x.FromConnectionStringWithKey("Database"))
         .DoNot.UseReflectionOptimizer())
         .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Page>()
             .Conventions.Add(FluentNHibernate.Conventions.Helpers.DefaultLazy.Never()))
         .BuildSessionFactory();
 }
Beispiel #45
0
        Configuration createNHConfiguration()
        {
            var cfg = new Configuration();

            ModelMapper mapping = new ModelMapper();

            mapping.AddMappings(typeof(ProfileMapping).Assembly.GetTypes());
            cfg.AddMapping(mapping.CompileMappingForAllExplicitlyAddedEntities());
            cfg.Configure();
            return(cfg);
        }
Beispiel #46
0
 /// <summary>
 /// The main method for the application.
 /// </summary>
 /// <param name="args">
 /// The command-line arguments.
 /// </param>
 public static void Main(string[] args)
 {
     NHibernate.Cfg.Configuration configuration = new NHibernate.Cfg.Configuration();
     configuration.Configure();
     configuration.AddAssembly(typeof(Manufacturer).Assembly);
     new SchemaExport(configuration).Execute(true, false, true);
     Application.Init();
     MainWindow win = new MainWindow();
     win.Show();
     Application.Run();
 }
Beispiel #47
0
        public static void ClassInitialize(TestContext context)
        {
            var cfg = new NHibernate.Cfg.Configuration();

            Assembly assembly = Assembly.GetAssembly(typeof (TestDomain));
            var stream = assembly.GetManifestResourceStream("Jobsearch.Model.Tests.hibernate.cfg.xml");
            var reader = new XmlTextReader(stream);

            cfg.Configure(reader);
            NHibernateProfiler.Initialize();
            Session = cfg.BuildSessionFactory().OpenSession();
        }
Beispiel #48
0
        private void GenerateDb(Action <Configuration> cfgAction)
        {
            var cfg = new Configuration()
                      .SetProperty(Environment.ConnectionString,
                                   ConfigurationManager.ConnectionStrings["Database"].ConnectionString);

            Fluently.Configure(cfg.Configure())
            .Mappings(v => Assemblies.ForEach(
                          a => v.FluentMappings.AddFromAssembly(a).Conventions.Add(ConventionsList.ToArray())))
            .ExposeConfiguration(cfgAction)
            .BuildSessionFactory();
        }
        private UnitOfWorkFactory()
        {
            DefaultFlushMode = FlushMode.Auto;

            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
            cfg.Configure();
            //NHibernate.Mapping.PersistentClass pc = cfg.GetClassMapping ("");
            //pc.Table.Name;
            //foreach( NHibernate.Mapping.Column col in pc.GetProperty("").ColumnIterator )
            //    col.Name
            _sessionFactory = cfg.BuildSessionFactory();
        }
Beispiel #50
0
 static NHibernateHelperSimple()
 {
     // Create the initial SessionFactory from the default configuration files
     try
     {
         Configuration cfg = new Configuration();
         SessionFactory = cfg.Configure().BuildSessionFactory();
     }
     catch(Exception ex)
     {
         throw new Exception("Building SessionFactory failed", ex);
     }
 }
        public void FluentlyConfigurationFromFile() {
            var configuration = new NHibernate.Cfg.Configuration();
            configuration.Configure("hibernate.fluent.cfg.xml");

            var cfg =
                Fluently.Configure(configuration)
                    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<FluentProductMap>())
                    .BuildConfiguration();

            cfg.Should().Not.Be.Null();

            var sessionFactory = cfg.BuildSessionFactory();
            sessionFactory.Should().Not.Be.Null();
        }
Beispiel #52
0
        private static ISessionFactory CreateSessionFactory()
        {
            var mapper = new ModelMapper();
            mapper.AddMappings(Assembly.Load("MessageBoard.Domain").GetTypes());
            HbmMapping domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            config = new NHibernate.Cfg.Configuration();
            config.Configure();
               config.AddDeserializedMapping(domainMapping,"domainMapping");

             config.Properties[NHibernate.Cfg.Environment.CurrentSessionContextClass]="web";
             config.SetProperty(NHibernate.Cfg.Environment.ShowSql, "true").SetProperty(NHibernate.Cfg.Environment.BatchSize, "100");
            return config.BuildSessionFactory();
        }
        public ISessionFactory GetSessionFactory()
        {
            var autoMappedModel = AutoMap.AssemblyOf<Project>().Where(IsNotResource).Where(type => type != typeof(ProductBacklog));

            var configuration = new NHibernate.Cfg.Configuration();
            configuration.Configure();

            var cfg = Fluently.Configure(configuration)
                              .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
                              .Mappings(m => m.AutoMappings.Add(autoMappedModel))
                              .BuildConfiguration();

            return cfg.BuildSessionFactory();
        }
Beispiel #54
0
        private static void BuildSessionFactory()
        {
            try
            {
                _configuration = new Configuration();
                _configuration.Configure();

                _sessionFactory = _configuration.BuildSessionFactory();
            }
            catch(Exception ex)
            {
                log4net.LogManager.GetLogger(typeof(NHibernateHelper)).Error(ex);
                throw;
            }
        }
        /// <summary>
        ///     Constructor
        /// </summary>
        /// <remarks>
        ///     Static contructors are called automatically before the first instance is created or any static members are referenced.
        ///     A static constructor is executed only once.
        /// </remarks>
        static NHibernateHelper()
        {
            var applicationSettings = new ApplicationSettings();

            // Build NHibernate session factory, expensive proces, should only fire when application first starts
            // Configuration is set in .config file
            Configuration = new Configuration();
            Configuration.SetProperty(NHibernate.Cfg.Environment.ConnectionString, applicationSettings.ConnectionString);
            Configuration.Configure();

            SessionFactory = Fluently.Configure(Configuration)
                .Mappings(m =>
                  m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
                //.Mappings(m=>m.FluentMappings.ExportTo("c:\\temp"))
                .BuildSessionFactory();
        }
        public void ShouldAppendToExistingListeners()
        {
            var cfg = new NHibernate.Cfg.Configuration();
            if (TestConfigurationHelper.hibernateConfigFile != null)
                cfg.Configure(TestConfigurationHelper.hibernateConfigFile);
            cfg.SetListener(ListenerType.PreInsert, new ListenersStub());
            cfg.SetListener(ListenerType.PreUpdate, new ListenersStub());
            var nhvc = new XmlConfiguration();
            nhvc.Properties[Environment.ApplyToDDL] = "true";
            nhvc.Properties[Environment.AutoregisterListeners] = "true";
            nhvc.Properties[Environment.ValidatorMode] = "UseAttribute";

            ValidatorInitializer.Initialize(cfg);
            Assert.That(cfg.EventListeners.PreInsertEventListeners.Length, Is.EqualTo(2));
            Assert.That(cfg.EventListeners.PreInsertEventListeners[1], Is.TypeOf<ValidatePreInsertEventListener>());
            Assert.That(cfg.EventListeners.PreUpdateEventListeners.Length, Is.EqualTo(2));
            Assert.That(cfg.EventListeners.PreUpdateEventListeners[1], Is.TypeOf<ValidatePreUpdateEventListener>());
        }
        protected void OnStartUp()
        {
            rootPath = Path.GetDirectoryName(
                Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory));

            XmlTextReader configReader = new XmlTextReader(new MemoryStream(Properties.Resources.Configuration));
            Configuration cfg = new Configuration();
            cfg.Configure(configReader);
            cfg.AddDirectory(new DirectoryInfo(Path.Combine(rootPath, "Hbm")));


            string strConnection = string.Format(ConfigurationManager.ConnectionStrings["dbc2"].ConnectionString, rootPath);
            cfg.SetProperty("connection.connection_string", strConnection);

            if (BeforeBuilding != null)
                this.BeforeBuilding.Invoke(cfg);

            sessionFactory = cfg.BuildSessionFactory();
        }
Beispiel #58
0
        public void MakeConnection(User user)
        {
            NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
               config.Configure().Configure("hibernate.cfg.xml");
               config.AddAssembly(typeof(User).Assembly);

               NHibernate.ISessionFactory factory = config.BuildSessionFactory();
               NHibernate.ISession session = factory.OpenSession();
             //    NHibernate.ITransaction transaction = session.BeginTransaction();
               /*      Console.Write("Saving");
               session.Save(user);   */

               IQuery iquery = session.CreateQuery("from User u where u.Username='******'");
               IList<User> returnUser = iquery.List<User>();
               Console.Write(returnUser[0].Age);

            //         transaction.Commit();
               session.Close();
        }
Beispiel #59
0
        public static void MyClassInitialize(TestContext testContext)
        {
            // define mapping schema
            HbmSerializer.Default.HbmAssembly = typeof(Product).Assembly.GetName().FullName;
            //HbmSerializer.Default.HbmNamespace = typeof( Product ).Namespace;
            HbmSerializer.Default.HbmAutoImport = true;
            HbmSerializer.Default.Validate = true;
            HbmSerializer.Default.WriteDateComment = false;
            HbmSerializer.Default.HbmDefaultAccess = "field";
            //HbmSerializer.Default.Serialize(typeof(Product).Assembly, "output.hbm.xml"); // serialize mapping xml into file to spectate it

            // create configuration and load assembly
            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
            //cfg.Properties[NHibernate.Cfg.Environment.CollectionTypeFactoryClass] = typeof(Net4CollectionTypeFactory).AssemblyQualifiedName;
            cfg.Configure();
            //cfg.AddAssembly( typeof( Product ).Assembly ); // use this only, if hbm.xml exists in the assembly
            cfg.AddInputStream(HbmSerializer.Default.Serialize(typeof(Product).Assembly)); // ez bármikor müxik, de lassabb

            try
            {
                SchemaValidator schemaValidator = new SchemaValidator(cfg);
                schemaValidator.Validate(); // validate the database schema
            }
            catch (Exception)
            {
                SchemaUpdate schemaUpdater = new SchemaUpdate(cfg); // try to update schema
                schemaUpdater.Execute(false, true);
                if (schemaUpdater.Exceptions.Count > 0)
                {
                    throw new Exception("FAILED TO UPDATE SCHEMA");
                }
            }

            //SchemaExport export = new SchemaExport(cfg);
            //export.Execute( false, true, false );
            //new SchemaExport( cfg ).Execute( false, true, false );
            mSessionFactory = cfg.BuildSessionFactory();
        }