示例#1
0
        protected virtual bool CheckDatabaseWasCleaned()
        {
            if (sessions.GetAllClassMetadata().Count == 0)
            {
                // Return early in the case of no mappings, also avoiding
                // a warning when executing the HQL below.
                return(true);
            }

            bool empty;

            using (ISession s = sessions.OpenSession())
            {
                IList objects = s.CreateQuery("from System.Object o").List();
                empty = objects.Count == 0;
            }

            if (!empty)
            {
                log.Error("Test case didn't clean up the database after itself, re-creating the schema");
                DropSchema();
                CreateSchema();
            }

            return(empty);
        }
示例#2
0
        public void EntityNameDemo()
        {
            object savedId;

            using (ISession s = sessions.OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    var a = new Animal {
                        Description = "Dog"
                    };
                    savedId = s.Save(a);
                    tx.Commit();
                    Assert.That(a.Id, Is.GreaterThan(0));
                }

            using (ISession s = sessions.OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    var a = s.Get <Animal>(savedId);
                    Assert.That(a.Description, Is.EqualTo("Dog"));
                    tx.Commit();
                }

            using (ISession s = sessions.OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    s.Delete("from Animal");
                    tx.Commit();
                }
        }
示例#3
0
        private void FillDb()
        {
            var rep = new List <Node>();

            for (int i = 0; i < 2; i++)
            {
                var gp = new Node {
                    Description = "N" + i.ToString("00")
                };
                rep.Add(gp);
                for (int j = 0; j < 5; j++)
                {
                    var c = new Node {
                        Description = gp.Description + "-" + j.ToString("00")
                    };
                    gp.AddChild(c);
                    for (int k = 0; k < 4; k++)
                    {
                        var cc = new Node {
                            Description = c.Description + "-" + k.ToString("00")
                        };
                        c.AddChild(cc);
                    }
                }
            }
            using (ISession s = sessions.OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    foreach (var node in rep)
                    {
                        s.Save(node);
                    }
                    tx.Commit();
                }
        }
        /// <summary>
        /// Opens control session.
        /// </summary>
        /// <returns>control session</returns>
        public ISessionImplementor OpenControlSession()
        {
            Preconditions.CheckState(controlSessionFactory != null);
            ISession session = controlSessionFactory.OpenSession();

            return((ISessionImplementor)session);
        }
示例#5
0
        public void ShouldNotAutoUpdate()
        {
            FillDb();

            using (ISession s = sessionFactory.OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    var reptiles = s.CreateQuery("from ReptilesFamily")
                                   .Future <Family <Reptile> >();

                    var humans = s.CreateQuery("from HumanFamily")
                                 .Future <Family <Human> >();

                    ModifyAll(reptiles);
                    ModifyAll(humans);

                    sessionFactory.Statistics.Clear();

                    s.Update(ReptilesfamilyEntityName, reptiles.First());
                    s.Update(HumanfamilyEntityName, humans.First());

                    tx.Commit();
                }

            sessionFactory.Statistics.EntityUpdateCount
            .Should().Be.EqualTo(7);

            CleanDb();
        }
示例#6
0
 protected ISession BuildOrObtainSession()
 {
     return(factory.OpenSession(
                null,
                IsAutoFlushEnabled(),
                IsAutoCloseEnabled(),
                GetConnectionReleaseMode()));
 }
        public void SaveObjectWithStringChangedToUpper()
        {
            object savedId;
            Foo    f = new Foo("something");

            using (ISession s = sessions.OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    savedId = s.Save(f);
                    tx.Commit();
                }

            using (ISession s = sessions.OpenSession())
            {
                Foo upperFoo = s.Get <Foo>(savedId);

                Assert.AreEqual("[something]", upperFoo.Description);
            }
        }
 public override void BeforeSchemaShutdown(ISessionFactoryImplementor factory)
 {
     using (ISession s = factory.OpenSession())
     {
         using (ITransaction tx = s.BeginTransaction())
         {
             s.Delete("from Foo");
             tx.Commit();
         }
     }
 }
示例#9
0
        public void SomebodySaidIsABug()
        {
            var version = typeof(Person).Assembly.GetName().Version.ToString();

            Console.WriteLine("Running version {0}", version);

            object savedId;

            using (ISession s = sessions.OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    var a = new Person {
                        FirstName = "Pasqual", LastName = "Angulo"
                    };
                    savedId = s.Save(a);
                    tx.Commit();
                }

            using (ISession s = sessions.OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    var a = s.Get <Person>(savedId);
                    if (version == "1.0.0.0")
                    {
                        Assert.That(a.FullName, Is.EqualTo("Pasqual-Angulo"));
                    }
                    else
                    {
                        Assert.That(a.FullName, Is.EqualTo("Angulo*Pasqual"));
                    }
                    tx.Commit();
                }

            using (ISession s = sessions.OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    s.Delete("from Person");
                    tx.Commit();
                }
        }
示例#10
0
 /// <summary>
 /// establish a Session using the SessionFactoryImplementor associated
 /// with this Shard and Apply any OpenSessionEvents that have been added.  If
 /// the Session has already been established just return it.
 /// </summary>
 /// <returns></returns>
 public ISession EstablishSession()
 {
     if (session == null)
     {
         if (interceptor == null)
         {
             session = sessionFactory.OpenSession();
         }
         else
         {
             session = sessionFactory.OpenSession(interceptor);
         }
         if (openSessionEvents != null)
         {
             foreach (IOpenSessionEvent ose in openSessionEvents)
             {
                 ose.OnOpenSession(session);
             }
             openSessionEvents.Clear();
         }
     }
     return(session);
 }
 public override void AfterSessionFactoryBuilt(ISessionFactoryImplementor sessionFactory)
 {
     using (ISession s = sessionFactory.OpenSession())
     {
         using (ITransaction tx = s.BeginTransaction())
         {
             for (int i = 0; i < TotalFoo; i++)
             {
                 var f = new Foo("N" + i, "D" + i);
                 s.Save(f);
             }
             tx.Commit();
         }
     }
 }
示例#12
0
        public void GenerateLockHintAtEndForExtraLazyCount()
        {
            var selectMethod = typeof(AbstractCollectionPersister).GetMethod(
                "GenerateSelectSizeString",
                BindingFlags.Instance | BindingFlags.NonPublic);

            Assert.That(selectMethod, Is.Not.Null, "Unable to find GenerateSelectSizeString method");

            using (var s = _sessionFactory.OpenSession())
            {
                var select = (SqlString)selectMethod.Invoke(_bagPersister, new object[] { s });
                Assert.That(select.ToString(), Does.EndWith(DialectWithReadLockHint.ReadOnlyLock));

                s.EnableFilter("CurrentOnly");
                select = (SqlString)selectMethod.Invoke(_bagPersister, new object[] { s });
                Assert.That(select.ToString(), Does.EndWith(DialectWithReadLockHint.ReadOnlyLock));
            }
        }
示例#13
0
        public static Object GetTargetFromProxy(ISessionFactoryImplementor sessionFactoryImplementor, INHibernateProxy proxy)
        {
            if (!proxy.HibernateLazyInitializer.IsUninitialized)
            {
                return(proxy.HibernateLazyInitializer.GetImplementation());
            }

            ISessionImplementor sessionImplementor = proxy.HibernateLazyInitializer.Session;
            //ORIG: ISession tempSession = sessionImplementor==null ? sessionFactoryImplementor.openTemporarySession() : sessionImplementor.Factory.openTemporarySession();
            ISession tempSession = sessionImplementor == null?sessionFactoryImplementor.OpenSession(null, false, false, ConnectionReleaseMode.AfterStatement) :
                                       sessionImplementor.Factory.OpenSession(null, false, false, ConnectionReleaseMode.AfterStatement);

            try {
                proxy.HibernateLazyInitializer.Session = (ISessionImplementor)tempSession;
                proxy.HibernateLazyInitializer.Initialize();
                return(proxy.HibernateLazyInitializer.GetImplementation());
            } finally {
                tempSession.Close();
            }
        }
        public void ReturnedValueIsGuid()
        {
            try
            {
                var str = Dialect.Dialect.GetDialect().SelectGUIDString;
            }
            catch (NotSupportedException)
            {
                Assert.Ignore("This test does not apply to {0}", Dialect.Dialect.GetDialect());
            }

            var gen = new NativeGuidGenerator();

            using (ISession s = sessions.OpenSession())
            {
                object result = gen.Generate((ISessionImplementor)s, null);
                Assert.That(result, Is.TypeOf(typeof(Guid)));
                Assert.That(result, Is.Not.EqualTo(Guid.Empty));
            }
        }
示例#15
0
        public void TestFixtureSetup()
        {
            log4net.Config.XmlConfigurator.Configure();

            var interceptor = new DataBindingInterceptor();

            config = new Configuration();
            config.SetInterceptor(interceptor);
            config.Properties[Environment.CollectionTypeFactoryClass] = typeof(ObservableCollectionTypeFactory).AssemblyQualifiedName;
            config.Properties[Environment.CurrentSessionContextClass] = "thread_static";
            config.SetListener(global::NHibernate.Event.ListenerType.PostInsert, SaveNotificationEventListener.Instance);
            config.SetListener(global::NHibernate.Event.ListenerType.PostUpdate, SaveNotificationEventListener.Instance);
            config.Configure();
            sessions = (ISessionFactoryImplementor)config.BuildSessionFactory();

            interceptor.SessionFactory = sessions;

            provider = new NHibernateGraphTypeProvider(string.Empty, new Type[] { typeof(Request), typeof(Priority), typeof(User), typeof(Category) });

            provider.SessionFactory = sessions;
            CurrentSessionContext.Bind(sessions.OpenSession());
        }
示例#16
0
		protected virtual ISession BuildSession(ISessionFactoryImplementor factory)
		{
			return factory.OpenSession(null, false, false, factory.Settings.ConnectionReleaseMode);
		}
示例#17
0
        public void DomainAbstraction()
        {
            using (ISession s = sessions.OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    var rf = DI.Resolver.Resolve <IReptile>();
                    rf.Description = "Crocodile";

                    var rm = DI.Resolver.Resolve <IReptile>();
                    rm.Description = "Crocodile";

                    var rc1 = DI.Resolver.Resolve <IReptile>();
                    rc1.Description = "Crocodile";

                    var rc2 = DI.Resolver.Resolve <IReptile>();
                    rc2.Description = "Crocodile";

                    var rfamily = DI.Resolver.Resolve <IFamily <IReptile> >();
                    rfamily.Father = rf;
                    rfamily.Mother = rm;
                    rfamily.Childs = new HashedSet <IReptile> {
                        rc1, rc2
                    };

                    s.Save(rfamily);
                    tx.Commit();
                }

            using (ISession s = sessions.OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    var hf = DI.Resolver.Resolve <IHuman>();
                    hf.Description = "Flinstone";
                    hf.Name        = "Fred";

                    var hm = DI.Resolver.Resolve <IHuman>();
                    hm.Description = "Flinstone";
                    hm.Name        = "Wilma";

                    var hc1 = DI.Resolver.Resolve <IHuman>();
                    hc1.Description = "Flinstone";
                    hc1.Name        = "Pebbles";

                    var hfamily = DI.Resolver.Resolve <IFamily <IHuman> >();
                    hfamily.Father = hf;
                    hfamily.Mother = hm;
                    hfamily.Childs = new HashedSet <IHuman> {
                        hc1
                    };

                    s.Save(hfamily);
                    tx.Commit();
                }

            using (ISession s = sessions.OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    var hf = s.CreateQuery("from HumanFamily").List <IFamily <IHuman> >();

                    Assert.That(hf.Count, Is.EqualTo(1));
                    Assert.That(hf[0].Father.Name, Is.EqualTo("Fred"));
                    Assert.That(hf[0].Mother.Name, Is.EqualTo("Wilma"));
                    Assert.That(hf[0].Childs.Count, Is.EqualTo(1));

                    var rf = s.CreateQuery("from ReptilesFamily").List <IFamily <IReptile> >();

                    Assert.That(rf.Count, Is.EqualTo(1));
                    Assert.That(rf[0].Childs.Count, Is.EqualTo(2));

                    tx.Commit();
                }

            using (ISession s = sessions.OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    s.Delete("from HumanFamily");
                    s.Delete("from ReptilesFamily");
                    tx.Commit();
                }
        }
 protected void ForceNewSession()
 {
     Session.Close();
     Session      = _sessionFactory.OpenSession();
     _auditReader = null;
 }
        public void CRUDUsingRefectionOptimizer()
        {
            IServiceLocator serviceLocator = ServiceLocator.Current;

            Product p1;
            Product p2;

            using (ISession s = sessions.OpenSession())
            {
                using (ITransaction tx = s.BeginTransaction())
                {
                    p1 = new Product {
                        Description = "P1", Price = 10
                    };
                    p2 = new Product {
                        Description = "P2", Price = 20
                    };
                    s.Save(p1);
                    s.Save(p2);
                    tx.Commit();
                }
            }

            var invoice = serviceLocator.GetInstance <IInvoice>();

            invoice.Tax = 1000;
            invoice.AddItem(p1, 1);
            invoice.AddItem(p2, 2);
            Assert.That(invoice.Total, Is.EqualTo((decimal)(10 + 40 + 1000)));

            object savedInvoice;

            using (ISession s = sessions.OpenSession())
            {
                using (ITransaction tx = s.BeginTransaction())
                {
                    savedInvoice = s.Save(invoice);
                    tx.Commit();
                }
            }

            using (ISession s = sessions.OpenSession())
            {
                invoice = s.Get <Invoice>(savedInvoice);
                Assert.That(invoice.Total, Is.EqualTo((decimal)(10 + 40 + 1000)));
            }

            using (ISession s = sessions.OpenSession())
            {
                invoice = (IInvoice)s.Load(typeof(Invoice), savedInvoice);
                Assert.That(invoice.Total, Is.EqualTo((decimal)(10 + 40 + 1000)));
            }

            using (ISession s = sessions.OpenSession())
            {
                IList <IInvoice> l = s.CreateQuery("from Invoice").List <IInvoice>();
                invoice = l[0];
                Assert.That(invoice.Total, Is.EqualTo((decimal)(10 + 40 + 1000)));
            }

            using (ISession s = sessions.OpenSession())
            {
                using (ITransaction tx = s.BeginTransaction())
                {
                    s.Delete("from Invoice");
                    s.Delete("from Product");
                    tx.Commit();
                }
            }
        }
示例#20
0
 public ISession CurrentSession()
 {
     return(_sessionFactoryImplementor.OpenSession());
 }
示例#21
0
        public void DynamicClasses()
        {
            IDictionary cars;
            IList       models;

            using (ISession s = sessions.OpenSession())
            {
                using (ITransaction t = s.BeginTransaction())
                {
                    cars = new Hashtable();
                    cars["Description"] = "Cars";

                    IDictionary ferrari = new Hashtable();
                    ferrari["ProductLine"] = cars;
                    ferrari["Name"]        = "Dino";
                    ferrari["Description"] = "Ferrari Dino.";

                    IDictionary lamborghini = new Hashtable();
                    lamborghini["ProductLine"] = cars;
                    lamborghini["Name"]        = "Countach";
                    lamborghini["Description"] = "Lamborghini Countach";

                    models = new List <IDictionary> {
                        ferrari, lamborghini
                    };

                    cars["Models"] = models;

                    s.Save("ProductLine", cars);
                    t.Commit();
                }
            }

            using (ISession s = sessions.OpenSession())
            {
                using (ITransaction t = s.BeginTransaction())
                {
                    cars   = (IDictionary)s.CreateQuery("from ProductLine pl order by pl.Description").UniqueResult();
                    models = (IList)cars["Models"];

                    Assert.That(models.Count == 2);

                    s.Clear();

                    IList list  = s.CreateQuery("from Model m").List();
                    var   model = (IDictionary)list[0];

                    Assert.That(((IList)((IDictionary)model["ProductLine"])["Models"]).Contains(model));

                    s.Clear();
                    t.Commit();
                }
            }

            using (ISession s = sessions.OpenSession())
            {
                using (ITransaction t = s.BeginTransaction())
                {
                    cars = (IDictionary)s.CreateQuery("from ProductLine pl order by pl.Description").UniqueResult();
                    s.Delete(cars);
                    t.Commit();
                }
            }
        }
示例#22
0
 protected virtual ISession OpenSession()
 {
     lastOpenedSession = _sessions.OpenSession();
     return(lastOpenedSession);
 }
示例#23
0
        public void CrudWithAnonimous()
        {
            object       savedId;
            IProductLine productLine;

            using (ISession s = sessions.OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    var line = new
                    {
                        Description = "High quality cars",
                        Models      = new ArrayList(),
                        Pizza       = "calda"
                    };
                    var ferrari = new
                    {
                        ProductLine = line,
                        Name        = "Dino",
                        Description = "Ferrari Dino",
                        Fuel        = "Gasoline"
                    };
                    var lamborghini = new
                    {
                        ProductLine = line,
                        Name        = "Countach",
                        Description = "Lamborghini Countach",
                        Origin      = "Italy"
                    };
                    line.Models.Add(ferrari);
                    line.Models.Add(lamborghini);

                    savedId = s.SaveDynamic("ProductLine", line);
                    t.Commit();
                }

            using (ISession s = sessions.OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    // Reload the saved dynamic entity
                    var entity = s.Get("ProductLine", savedId);
                    // Transform it to a know type
                    productLine = entity.AsDynamic <IProductLine>();

                    // Modify through know type
                    productLine.Description = "Quality cars";
                    productLine.Models.Add(
                        (new
                    {
                        ProductLine = entity,
                        Name = "Locus",
                        Description = "Audi Locus"
                    }).AsDynamic <IModel>());

                    t.Commit();             // Persist modification
                }

            // Test over modifications
            using (ISession s = sessions.OpenSession())
            {
                var entity = s.Get("ProductLine", savedId);
                productLine = entity.AsDynamic <IProductLine>();
                productLine.Description.Should().Be.EqualTo("Quality cars");
                productLine.Models.Count.Should().Be.EqualTo(3);
            }

            using (ISession s = sessions.OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    // Delete the detached dynamic entity
                    s.DeleteDynamic("ProductLine", productLine);
                    t.Commit();
                }

            using (ISession s = sessions.OpenSession())
            {
                // check entity deletation with cascade
                s.Get("ProductLine", savedId).Should().Be.Null();
                s.CreateQuery("from Model").List().Count.Should().Be.EqualTo(0);
            }
        }
 protected virtual ISession BuildSession(ISessionFactoryImplementor factory)
 {
     return(factory.OpenSession(null, false, false, factory.Settings.ConnectionReleaseMode));
 }
示例#25
0
 protected virtual ISession OpenSession()
 {
     return(Sfi.OpenSession());
 }
示例#26
0
 public SqlLiteContext(ISessionFactoryImplementor factoryImplementor){
     session = factoryImplementor.OpenSession();
 }
示例#27
0
        public void EntityNameDemo()
        {
            using (ISession s = sessions.OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    var rf = new Reptile {
                        Description = "Crocodile"
                    };
                    var rm = new Reptile {
                        Description = "Crocodile"
                    };
                    var rc1 = new Reptile {
                        Description = "Crocodile"
                    };
                    var rc2 = new Reptile {
                        Description = "Crocodile"
                    };
                    var rfamily = new Family <Reptile>
                    {
                        Father = rf,
                        Mother = rm,
                        Childs = new HashedSet <Reptile> {
                            rc1, rc2
                        }
                    };
                    s.Save("ReptilesFamily", rfamily);
                    tx.Commit();
                }

            using (ISession s = sessions.OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    var hf = new Human {
                        Description = "Flinstone", Name = "Fred"
                    };
                    var hm = new Human {
                        Description = "Flinstone", Name = "Wilma"
                    };
                    var hc1 = new Human {
                        Description = "Flinstone", Name = "Pebbles"
                    };
                    var hfamily = new Family <Human>
                    {
                        Father = hf,
                        Mother = hm,
                        Childs = new HashedSet <Human> {
                            hc1
                        }
                    };
                    s.Save("HumanFamily", hfamily);
                    tx.Commit();
                }

            using (ISession s = sessions.OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    IList <Family <Human> > hf = s.CreateQuery("from HumanFamily").List <Family <Human> >();
                    Assert.That(hf.Count, Is.EqualTo(1));
                    Assert.That(hf[0].Father.Name, Is.EqualTo("Fred"));
                    Assert.That(hf[0].Mother.Name, Is.EqualTo("Wilma"));
                    Assert.That(hf[0].Childs.Count, Is.EqualTo(1));

                    IList <Family <Reptile> > rf = s.CreateQuery("from ReptilesFamily").List <Family <Reptile> >();
                    Assert.That(rf.Count, Is.EqualTo(1));
                    Assert.That(rf[0].Childs.Count, Is.EqualTo(2));

                    tx.Commit();
                }

            using (ISession s = sessions.OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    s.Delete("from HumanFamily");
                    s.Delete("from ReptilesFamily");
                    tx.Commit();
                }
        }