Beispiel #1
0
        private async Task <IActionResult> ExportPoints <T>(int groupid) where T : class
        {
            try

            {
                using (NHibernate.IStatelessSession session = sessionFactory.OpenStatelessSession())
                {
                    //DigitalOutputGroup s;s.
                    var @object = await session.CreateCriteria <T>().Add(Restrictions.Eq("Groupid", groupid)).ListAsync <T>();

                    if (@object == null || @object.Count == 0)
                    {
                        return(BadRequest(ApiResult.BadRequest($"대상 GROUP ID {groupid}가 존재하지 않습니다")));
                    }

                    byte[] data     = ExportCSVFormat <T>(@object);
                    string filename = $"{typeof(T).Name}.csv";

                    System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
                    {
                        FileName = Uri.EscapeUriString(filename),
                        Inline   = false // false = prompt the user for downloading;  true = browser to try to show the file inline
                    };
                    Response.Headers.Add("Content-Disposition", cd.ToString());
                    Response.Headers.Add("X-Content-Type-Options", "nosniff");
                    return(File(data, "application/octet-stream"));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(ApiResult.BadRequest(ex.Message)));
            }
        }
        private void Receive(object state)
        {
            if (!_lastPayloadId.HasValue)
            {
                try
                {
                    using (var session = _sessionFactory.OpenStatelessSession())
                    {
                        _lastPayloadId = (long?)session.Query <TIdType>().Select(i => i.PayloadId).FirstOrNull();
                    }
                    //_lastPayloadId = (long?)lastPayloadIdOperation.ExecuteScalar();
                    Queried();

                    _trace.TraceVerbose("{0}SqlReceiver started, initial payload id={1}", _tracePrefix, _lastPayloadId);


                    // Complete the StartReceiving task as we've successfully initialized the payload ID
                    //tcs.TrySetResult(null);
                }
                catch (Exception ex)
                {
                    _trace.TraceError("{0}SqlReceiver error starting: {1}", _tracePrefix, ex);

                    //tcs.TrySetException(ex);
                    return;
                }
            }
            TryReceive();
            if (_timer == null)
            {
                _timer          = new Timer(interval);
                _timer.Elapsed += (a, b) => { TryReceive(); };
                _timer.Start();
            }
        }
 public EmployeeClassification FindByName(string employeeClassificationName)
 {
     using (var session = m_SessionFactory.OpenStatelessSession())
     {
         return(session.QueryOver <EmployeeClassification>().Where(ec => ec.EmployeeClassificationName == employeeClassificationName).SingleOrDefault());
     }
 }
Beispiel #4
0
 public ReadOnlyEmployeeClassification?FindByName(string employeeClassificationName)
 {
     using (var session = m_SessionFactory.OpenStatelessSession())
     {
         return(session.QueryOver <EmployeeClassification>().Where(e => e.EmployeeClassificationName == employeeClassificationName).List()
                .Select(x => new ReadOnlyEmployeeClassification(x)).SingleOrDefault());
     }
 }
Beispiel #5
0
 public IList <DbIrtPeptide> GetPeptides()
 {
     using (var session = new StatelessSessionWithLock(_sessionFactory.OpenStatelessSession(), _databaseLock,
                                                       false, CancellationToken.None))
     {
         return(session.CreateCriteria(typeof(DbIrtPeptide)).List <DbIrtPeptide>());
     }
 }
        public async Task <Person> FirstAsync()
        {
            IncreaseId();

            using IStatelessSession session = sessionFactory.OpenStatelessSession();

            return(await session.Query <Person>().FirstAsync(x => x.Id == CurrentId));
        }
 public IList <EmployeeDetail> FindByEmployeeClassificationKey(int employeeClassificationKey)
 {
     using (var session = m_SessionFactory.OpenStatelessSession())
     {
         return(session.QueryOver <EmployeeDetail>()
                .Where(ed => ed.EmployeeClassificationKey == employeeClassificationKey)
                .List());
     }
 }
Beispiel #8
0
        internal static IStatelessSession OpenStatelessSessionEx(this ISessionFactory sessionFactory, IDbConnection connection)
        {
            if (connection == null)
            {
                return(sessionFactory.OpenStatelessSession());
            }

            return(sessionFactory.OpenStatelessSession(connection));
        }
Beispiel #9
0
 public IList <Employee> SortByFirstName(string lastName)
 {
     using (var session = m_SessionFactory.OpenStatelessSession())
     {
         return(session.QueryOver <Employee>().Where(x => x.LastName == lastName)
                .OrderBy(x => x.FirstName).Asc
                .List());
     }
 }
 public async Task <IEnumerable <EducationOrganizationIdentifiers> > GetAllEducationOrganizationIdentifiers()
 {
     using (var session = _sessionFactory.OpenStatelessSession())
     {
         return(await session.CreateSQLQuery(Sql + " ORDER BY EducationOrganizationId;")
                .SetResultTransformer(Transformers.AliasToBean <EducationOrganizationIdentifiers>())
                .ListAsync <EducationOrganizationIdentifiers>()
                .ConfigureAwait(false));
     }
 }
 public async Task <EmployeeClassification?> FindByNameAsync(string employeeClassificationName, CancellationToken cancellationToken = default)
 {
     using (var session = m_SessionFactory.OpenStatelessSession())
     {
         return((await session.QueryOver <EmployeeClassification>()
                 .Where(ec => ec.EmployeeClassificationName == employeeClassificationName)
                 .ListAsync(cancellationToken).ConfigureAwait(false))
                .SingleOrDefault());
     }
 }
Beispiel #12
0
 private Dictionary <string, LocalizedString> FindLocalizationsByResource(string resource, CultureInfo culture)
 {
     using (var session = sessionFactory.OpenStatelessSession())
     {
         return(session.Query <LocalizedStringResource>()
                .Where(q => q.Culture.Name == culture.Name)
                .Where(q => q.Resource == resource)
                .Select(q => new LocalizedString(q.Key, q.Text, false, q.Resource))
                .ToDictionary(q => q.Name, q => q));
     }
 }
Beispiel #13
0
 protected override void InsertMultipleTest(int count)
 {
     using (var statelessSession = _factory.OpenStatelessSession())
         using (var transaction = statelessSession.BeginTransaction())
         {
             for (int i = 0; i < count; i++)
             {
                 var s = new Simplest(i, i);
                 statelessSession.Insert(s);
             }
             transaction.Commit();
         }
     InstanceCount = count;
 }
Beispiel #14
0
        private IList <Message> FetchPendingMessages()
        {
            List <Message> messagesToPush;

            using (var session = sessionFactory.OpenStatelessSession())
            {
                messagesToPush = session.Query <Message>()
                                 .OrderBy(m => m.Id)
                                 .Take(50)
                                 .ToList();
            }

            return(messagesToPush);
        }
Beispiel #15
0
        public DataTable FindByFlags(bool isExempt, bool isEmployee)
        {
            //Note that this uses ":ParameterName" instead of SQL Server's normal "@ParameterName".
            var sql = @"SELECT ec.EmployeeClassificationKey, ec.EmployeeClassificationName, ec.IsExempt, ec.IsEmployee FROM HR.EmployeeClassification ec WHERE ec.IsExempt = :IsExempt AND ec.IsEmployee = :IsEmployee;";

            using (var session = m_SessionFactory.OpenStatelessSession())
            {
                var sqlQuery = session.CreateSQLQuery(sql);
                sqlQuery.SetParameter("IsExempt", isExempt);
                sqlQuery.SetParameter("IsEmployee", isEmployee);
                var transformedQuery = sqlQuery.SetResultTransformer(new DataTableResultTransformer());
                return(transformedQuery.List().OfType <DataTable>().Single());
            }
        }
        public async Task <TimeoutsChunk> GetNextChunk(DateTime startSlice)
        {
            var now = DateTime.UtcNow;

            //Every timeoutsCleanupExecutionInterval we extend the query window back in time to make
            //sure we will pick-up any missed timeouts which might exists due to TimeoutManager timeout storage race-condition
            if (lastTimeoutsCleanupExecution.Add(timeoutsCleanupExecutionInterval) < now)
            {
                lastTimeoutsCleanupExecution = now;
                //We cannot use DateTime.MinValue as sql supports dates only back to 1 January 1753
                startSlice = SqlDateTime.MinValue.Value;
            }

            using (new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled))
                using (var session = SessionFactory.OpenStatelessSession())
                    using (var tx = session.BeginTransaction(IsolationLevel.ReadCommitted))
                    {
                        var list = await session.QueryOver <TimeoutEntity>()
                                   .Where(x => x.Endpoint == EndpointName)
                                   .And(x => x.Time > startSlice && x.Time <= now)
                                   .OrderBy(x => x.Time).Asc
                                   .Select(x => x.Id, x => x.Time)
                                   .ListAsync <object[]>().ConfigureAwait(false);

                        var results = list
                                      .Select(p =>
                        {
                            var id      = (Guid)p[0];
                            var dueTime = (DateTime)p[1];
                            return(new TimeoutsChunk.Timeout(id.ToString(), dueTime));
                        })
                                      .ToArray();

                        //Retrieve next time we need to run query
                        var startOfNextChunk = await session.QueryOver <TimeoutEntity>()
                                               .Where(x => x.Endpoint == EndpointName && x.Time > now)
                                               .OrderBy(x => x.Time).Asc
                                               .Select(x => x.Time)
                                               .Take(1)
                                               .SingleOrDefaultAsync <DateTime?>().ConfigureAwait(false);

                        var nextTimeToRunQuery = startOfNextChunk ?? DateTime.UtcNow.AddMinutes(10);

                        await tx.CommitAsync()
                        .ConfigureAwait(false);

                        return(new TimeoutsChunk(results, nextTimeToRunQuery));
                    }
        }
Beispiel #17
0
 private void Save(FailureInfo info)
 {
     using (IStatelessSession statelessSession = _sessionFactory.OpenStatelessSession())
     {
         statelessSession.Insert(info);
     }
 }
Beispiel #18
0
        public static IStatelessSession GetSession()
        {
            if (session == null)
            {
                ISessionFactory factory = Fluently.Configure()
                                          .Database(MySQLConfiguration.Standard
                                                    .ConnectionString(c => c
                                                                      .Server("192.168.137.150")
                                                                      .Database("acegi")
                                                                      .Username("root")
                                                                      .Password("linroor2012")))
                                          .Mappings(m => m.FluentMappings.Add(typeof(UsuarioMap)))
                                          .Mappings(m => m.FluentMappings.Add(typeof(FuncaoMenuMap)))
                                          .Mappings(m => m.FluentMappings.Add(typeof(FuncaoSubMenuMap)))
                                          .Mappings(m => m.FluentMappings.Add(typeof(IdiomaMap)))
                                          .Mappings(m => m.FluentMappings.Add(typeof(MoedaMap)))
                                          .Mappings(m => m.FluentMappings.Add(typeof(NRIntervaloMap)))
                                          .Mappings(m => m.FluentMappings.Add(typeof(PaisMap)))
                                          .Mappings(m => m.FluentMappings.Add(typeof(CategoriaCambioMap)))
                                          .Mappings(m => m.FluentMappings.Add(typeof(FatorConversaoMap)))
                                          .ExposeConfiguration(x => x.SetProperty("hbm2ddl.keywords", "auto"))
                                          .BuildSessionFactory();

                session = factory.OpenStatelessSession();
            }
            return(session);
        }
Beispiel #19
0
        public static ISessionFactory CreateSessionFactory(string filePath, bool mainSession)
        {
            Configuration configuration = new Configuration()
                                          .SetProperty("dialect", typeof(CustomSQLiteDialect).AssemblyQualifiedName)
                                          .SetProperty("hibernate.cache.use_query_cache", "true")
                                          .SetProperty("proxyfactory.factory_class", typeof(NHibernate.ByteCode.Castle.ProxyFactoryFactory).AssemblyQualifiedName)
                                          //.SetProperty("adonet.batch_size", batchSize.ToString())
                                          .SetProperty("connection.connection_string", "Data Source=" + filePath + ";Version=3;")
                                          .SetProperty("connection.driver_class", typeof(NHibernate.Driver.SQLite20Driver).AssemblyQualifiedName)
                                          .SetProperty("connection.provider", typeof(NHibernate.Connection.DriverConnectionProvider).AssemblyQualifiedName)
                                          .SetProperty("connection.release_mode", "on_close")
            ;

            ConfigureMappings(configuration);

            ISessionFactory sessionFactory = null;

            lock (mutex)
                sessionFactory = configuration.BuildSessionFactory();

            if (mainSession)
            {
                sessionFactory.OpenStatelessSession().CreateSQLQuery(@"PRAGMA default_cache_size=500000;
                                                                   PRAGMA temp_store=MEMORY").ExecuteUpdate();

                var schema = new NHibernate.Tool.hbm2ddl.SchemaUpdate(configuration);
                schema.Execute(false, true);
            }

            return(sessionFactory);
        }
        public void WhenBeginTransactionFailsStatelessSessionIsRemovedFromSessionStore()
        {
            using (mockRepository.Record())
            {
                Expect.Call(kernel.Resolve <ITransactionManager>()).Return(transactionManager);
                Expect.Call(transactionManager.CurrentTransaction).Return(transaction);
                Expect.Call(factoryResolver.GetSessionFactory(Alias)).Return(sessionFactory);
                Expect.Call(sessionFactory.OpenStatelessSession()).Return(statelessSession);
                Expect.Call(transaction.Context).Return(contextDictionary).Repeat.Any();
                Expect.Call(transaction.IsolationMode).Return(DefaultIsolationMode).Repeat.Any();
                Expect.Call(statelessSession.BeginTransaction(DefaultIsolationLevel)).Throw(new Exception());
            }

            using (mockRepository.Playback())
            {
                try
                {
                    sessionManager.OpenStatelessSession(Alias);
                    Assert.Fail("DbException not thrown");
                }
                catch (Exception)
                {
                    //ignore
                    //Console.WriteLine(ex.ToString());
                }
                Assert.IsNull(
                    sessionStore.FindCompatibleStatelessSession(Alias),
                    "The sessionStore shouldn't contain compatible session if the session creation fails");
            }
        }
Beispiel #21
0
        private void InsertItems(IList <BaseClass> items, ISessionFactory factory, Type type)
        {
            var failedItems           = new List <BaseClass>();
            var longStringProperties  = type.GetProperties().Where(p => p.PropertyType == typeof(LongString)).ToList();
            var hasLongStringProperty = longStringProperties.Count() > 0;

            using (var session = factory.OpenStatelessSession())
                using (var transaction = session.BeginTransaction())
                {
                    foreach (var item in items)
                    {
                        if (hasLongStringProperty)
                        {
                            foreach (var prop in longStringProperties)
                            {
                                var value = prop.GetValue(item);
                                if (value == null || String.IsNullOrWhiteSpace((value as LongString)?.ToString()))
                                {
                                    prop.SetValue(item, new LongString(String.Empty));
                                }
                            }
                        }
                        session.Insert(item);
                    }
                    transaction.Commit();
                }
        }
        /// <summary>
        /// Gets the stateless session.
        /// </summary>
        /// <returns>An IStatelessSession object.</returns>
        public IStatelessSession GetStatelessSession()
        {
            ISessionFactory   sessionFactory   = _sessionFactoryProvider.GetFactory(null);
            IStatelessSession statelessSession = sessionFactory.OpenStatelessSession();

            return(statelessSession);
        }
Beispiel #23
0
        public InMemoryDatabaseTest(Assembly assemblyContainingMapping, bool showLog)
        {
            _log = new TestWithLog();
            if (showLog)
            {
                _log.EnableLogger();
            }

            if (_configuration == null)
            {
                _configuration = new Configuration()
                                 .SetProperty(Environment.ReleaseConnections, "on_close")
                                 .SetProperty(Environment.Dialect, typeof(SQLiteDialect).AssemblyQualifiedName)
                                 .SetProperty(Environment.ConnectionDriver, typeof(SQLite20Driver).AssemblyQualifiedName)
                                 .SetProperty(Environment.ConnectionString, "data source = :memory:")
                                 .SetProperty(Environment.ProxyFactoryFactoryClass, typeof(ProxyFactoryFactory).AssemblyQualifiedName)
                                 .SetProperty(Environment.ShowSql, "false")
                                 .AddAssembly(assemblyContainingMapping);

                _sessionFactory = _configuration.BuildSessionFactory();
            }

            _session          = _sessionFactory.OpenSession();
            _statelessSession = _sessionFactory.OpenStatelessSession();

            // This needs to go into the [Setup] _Init() method for the derived test class
            // new SchemaExport(_configuration).Execute(true, true, false, _session.Connection, Console.Out);
        }
Beispiel #24
0
        public void FindCompatibleStatelessSessionWithTwoThreads()
        {
            ISessionStore   store   = container.Resolve <ISessionStore>();
            ISessionFactory factory = container.Resolve <ISessionFactory>();

            IStatelessSession session = factory.OpenStatelessSession();

            StatelessSessionDelegate sessionDelegate = new StatelessSessionDelegate(true, session, store);

            store.Store(Constants.DefaultAlias, sessionDelegate);

            IStatelessSession session2 = store.FindCompatibleStatelessSession(Constants.DefaultAlias);

            Assert.IsNotNull(session2);
            Assert.AreSame(sessionDelegate, session2);

            Thread newThread = new Thread(FindCompatibleStatelessSessionOnOtherThread);

            newThread.Start();

            arEvent.WaitOne();

            sessionDelegate.Dispose();

            Assert.IsTrue(store.IsCurrentActivityEmptyFor(Constants.DefaultAlias));
        }
Beispiel #25
0
        private async Task InsertTbPv(float[] pvPowers, float[] pvtotal, float[] pvtodays, CancellationToken token)
        {
            try
            {
                using (var session = mysqlSessionFactory.OpenStatelessSession())
                    using (var trans = session.BeginTransaction())
                    {
                        TbPv pv = new TbPv();
                        pv.Date    = DateTime.Now;
                        pv.Energy1 = pvtotal[0];
                        pv.Energy2 = pvtotal[1];
                        pv.Energy3 = pvtotal[2];
                        pv.Energy4 = pvtotal[3];

                        pv.Power1 = pvPowers[0];
                        pv.Power2 = pvPowers[1];
                        pv.Power3 = pvPowers[2];
                        pv.Power4 = pvPowers[3];

                        pv.Pv1_Today_Eng = pvtodays[0];
                        pv.Pv2_Today_Eng = pvtodays[1];
                        pv.Pv3_Today_Eng = pvtodays[2];
                        pv.Pv4_Today_Eng = pvtodays[3];
                        await session.InsertAsync(pv);

                        await trans.CommitAsync(token);
                    }
            }
            catch (Exception ex)
            {
                logger.Error(ex, ex.Message);
            }
        }
        private static void InsertProductWithGuidId(ISessionFactory sessionFactory, Stopwatch stopWatch)
        {
            Console.WriteLine("Start executing insert product with guid id");

            stopWatch.Start();

            using (var session = sessionFactory.OpenStatelessSession())
                using (var transaction = session.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
                {
                    for (var i = 0; i < AmountOfInserts; i++)
                    {
                        var product = new ProductWithGuid()
                        {
                            Id          = Guid.NewGuid(),
                            Name        = "A very long productname",
                            Description = "A very long description of a product with a very long name",
                            Price       = 22,
                            Category    = "Books"
                        };
                        session.Insert(product);
                    }

                    transaction.Commit();
                }

            stopWatch.Stop();
            var result = stopWatch.ElapsedMilliseconds;

            Console.WriteLine("Total time (in milliseconds) for executing query: " + result);
        }
Beispiel #27
0
        private void SetUpInitialData(InstallModel model, IDatabaseProvider provider)
        {
            var configurator = new NHibernateConfigurator(provider);

            ISessionFactory   sessionFactory   = configurator.CreateSessionFactory();
            ISession          session          = sessionFactory.OpenFilteredSession();
            IStatelessSession statelessSession = sessionFactory.OpenStatelessSession();
            var kernel = MrCMSApplication.Get <IKernel>();

            kernel.Rebind <ISession>().ToMethod(context => session);
            kernel.Rebind <IStatelessSession>().ToMethod(context => statelessSession);
            var site = new Site
            {
                Name      = model.SiteName,
                BaseUrl   = model.SiteUrl,
                CreatedOn = DateTime.UtcNow,
                UpdatedOn = DateTime.UtcNow
            };

            using (ITransaction transaction = statelessSession.BeginTransaction())
            {
                statelessSession.Insert(site);
                transaction.Commit();
            }
            CurrentRequestData.CurrentSite = site;

            kernel.Get <IInitializeDatabase>().Initialize(model);
            kernel.Get <ICreateInitialUser>().Create(model);
            kernel.GetAll <IOnInstallation>()
            .OrderBy(installation => installation.Priority)
            .ForEach(installation => installation.Install(model));
        }
Beispiel #28
0
 protected OrmFactBase(ITestOutputHelper output)
 {
     Output           = output;
     sessionFactory   = CreateSessionFactory(ConnectionString);
     Session          = sessionFactory.OpenSession();
     StatelessSession = sessionFactory.OpenStatelessSession();
 }
Beispiel #29
0
        public async Task InitDatabase()
        {
            var nhibernateConfiguration = new Configuration();

            nhibernateConfiguration.SetProperties(
                new Dictionary <string, string>
            {
                { "connection.provider", configuration["DatabaseConnection:Provider"] },
                { "connection.driver_class", configuration["DatabaseConnection:DriverClass"] },
                { "connection.connection_string", configuration["DatabaseConnection:ConnectionString"] },
                { "dialect", configuration["DatabaseConnection:Dialect"] },
            });
            nhibernateConfiguration.CurrentSessionContext <AsyncLocalSessionContext>();

            IEnumerable <string> dataMappingFiePaths =
                Directory.EnumerateFiles(Path.Combine(Directory.GetCurrentDirectory(), "Mappings"));

            foreach (string dataMappingFiePath in dataMappingFiePaths)
            {
                nhibernateConfiguration.AddXmlFile(dataMappingFiePath);
            }

            using ISessionFactory sessionFactory = nhibernateConfiguration.BuildSessionFactory();
            using IStatelessSession session      = sessionFactory.OpenStatelessSession();
            await new SchemaExport(nhibernateConfiguration).CreateAsync(true, true);
        }
        public Task <OutboxMessage> Get(string messageId, ContextBag context)
        {
            object[] possibleIds =
            {
                EndpointQualifiedMessageId(messageId),
                messageId,
            };

            if (Transaction.Current != null)
            {
                throw new Exception("The endpoint is configured to use Outbox but a TransactionScope has been detected. Outbox mode is not compatible with "
                                    + $"TransactionScope. Do not configure the transport to use '{nameof(TransportTransactionMode.TransactionScope)}' transaction mode with Outbox.");
            }

            using (new TransactionScope(TransactionScopeOption.Suppress))
            {
                TEntity result;
                using (var session = sessionFactory.OpenStatelessSession())
                {
                    using (var tx = session.BeginTransaction(IsolationLevel.ReadCommitted))
                    {
                        //Explicitly using ICriteria instead of QueryOver for performance reasons.
                        //It seems QueryOver uses quite a bit reflection and that takes longer.
                        result = session.CreateCriteria <TEntity>()
                                 .Add(Restrictions.In(nameof(IOutboxRecord.MessageId), possibleIds))
                                 .UniqueResult <TEntity>();

                        tx.Commit();
                    }
                }

                if (result == null)
                {
                    return(Task.FromResult <OutboxMessage>(null));
                }
                if (result.Dispatched)
                {
                    return(Task.FromResult(new OutboxMessage(result.MessageId, new TransportOperation[0])));
                }
                var transportOperations = ConvertStringToObject(result.TransportOperations)
                                          .Select(t => new TransportOperation(t.MessageId, t.Options, t.Message, t.Headers))
                                          .ToArray();

                var message = new OutboxMessage(result.MessageId, transportOperations);
                return(Task.FromResult(message));
            }
        }
        /// <summary>
        /// This method is invoked to allow
        /// the scope to create a properly configured session
        /// </summary>
        /// <param name="sessionFactory">From where to open the session</param>
        /// <param name="interceptor">the NHibernate interceptor</param>
        /// <returns>the newly created session</returns>
        protected override ISession CreateSession(ISessionFactory sessionFactory, IInterceptor interceptor)
        {
            ISession session = new StatelessSessionWrapper(sessionFactory.OpenStatelessSession());

            session.BeginTransaction();

            return session;
        }
Beispiel #32
0
 public static void ExecuteAuxilliaryDatabaseScripts(this Configuration configuration, ISessionFactory sf)
 {
     dynamic exposed = new ExposedObjectSimple(configuration);
     foreach (var aux in exposed.auxiliaryDatabaseObjects)
     {
         var script = ((dynamic)new ExposedObjectSimple(aux)).sqlCreateString;
         using (var s = sf.OpenStatelessSession())
         {
             s.CreateSQLQuery((string)script).ExecuteUpdate();
         }
     }
 }
Beispiel #33
0
        public static void ClearDatabase(Configuration cfg, ISessionFactory factory)
        {
            var tableNames = new List<string>();

            foreach (var clazz in cfg.ClassMappings)
            {
                tableNames.Add(clazz.Table.Name);
            }

            using (IStatelessSession session = factory.OpenStatelessSession())
            {
                using (IDbCommand cmd = session.Connection.CreateCommand())
                {
                    cmd.CommandType = CommandType.Text;

                    foreach (var tableName in tableNames)
                    {
                        cmd.CommandText = string.Format("DELETE FROM {0}", tableName);
                        cmd.ExecuteNonQuery();
                    }
                }
            }
        }
Beispiel #34
0
 static void RunSql(ISessionFactory sessionFactory)
 {
     using (var session = sessionFactory.OpenStatelessSession())
     {
         //session.CreateSQLQuery("SELECT {v.*} FROM [Value] v").AddEntity("v", typeof(Value)).List<Value>();
         session.CreateSQLQuery("SELECT v.* FROM [Value] v").List();
     }
 }
Beispiel #35
0
 static void RunStatelessSession(ISessionFactory sessionFactory)
 {
     using (var session = sessionFactory.OpenStatelessSession())
     {
         session.Query<Value>().ToList();
     }
 }
		private void CreateTestData(ISessionFactory sessionFactory)
		{
			using (IStatelessSession session = sessionFactory.OpenStatelessSession())
			using (ITransaction tx = session.BeginTransaction())
			{
				NorthwindDbCreator.CreateNorthwindData(session);

				tx.Commit();
			}

			using (ISession session = sessionFactory.OpenSession())
			using (ITransaction tx = session.BeginTransaction())
			{
				NorthwindDbCreator.CreateMiscTestData(session);
				NorthwindDbCreator.CreatePatientData(session);
				tx.Commit();
			}
		}
		/// <summary>
		/// If the <see cref="AbstractScope.WantsToCreateTheSession"/> returned
		/// <c>true</c> then this method is invoked to allow
		/// the scope to create a properly configured session
		/// </summary>
		/// <param name="sessionFactory">From where to open the session</param>
		/// <param name="interceptor">the NHibernate interceptor</param>
		/// <returns>the newly created session</returns>
		public override ISession OpenSession(ISessionFactory sessionFactory, IInterceptor interceptor)
		{
			return new StatelessSessionWrapper(sessionFactory.OpenStatelessSession());
		}
Beispiel #38
0
 public UnitOfWork(ISessionFactory sessionFactory)
 {
    _sessionFactory = sessionFactory;
    _readSession = _sessionFactory.OpenStatelessSession();
 }
        private static IUnitOfWork StartUnitOfWork(ISessionFactory sessionFactory, IEnumerable<UnitOfWorkOption> options)
        {
            if (options != null && options.Contains(UnitOfWorkOption.Stateless))
            {
                return new UnitOfWork(sessionFactory.OpenStatelessSession());
            }

            var session = sessionFactory.OpenSession();
            session.FlushMode = FlushMode.Commit;
            return new UnitOfWork(session) {ObjectContainer = Core.ObjectContainer.Get<IObjectContainer>()};
        }
        public void Setup()
        {
            _sessionFactory = _configuration.BuildSessionFactory();
			_session = _sessionFactory.OpenStatelessSession();
            _transaction = _session.BeginTransaction();
        }