private void BuildFirstDomain()
        {
            var domainConfig = DomainConfigurationFactory.CreateWithoutSessionConfigurations();

            domainConfig.Types.Register(myAssembly, typeof(Model_1.Order).Namespace);
            domainConfig.UpgradeMode = DomainUpgradeMode.Recreate;
            var domain = Domain.Build(domainConfig);

            using (var session = domain.OpenSession()) {
                using (var transactionScope = session.OpenTransaction()) {
                    var mMorder =
                        new Model_1.Order(session)
                    {
                        ProductName = "Cheese", Quantity = 10
                    };
                    new Model_1.Order(session)
                    {
                        ProductName = "Wine", Quantity = 2
                    };
                    new Model_1.Order(session)
                    {
                        ProductName = "Wine", Quantity = 5
                    };

                    transactionScope.Complete();
                }
            }
        }
        private Domain GetDomain()
        {
            if (existingDomain == null)
            {
                var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();
                config.UpgradeMode = DomainUpgradeMode.Recreate;
                config.Types.Register(typeof(Person).Assembly, typeof(Person).Namespace);
                config.Types.Register(typeof(CustomSqlCompilerContainer));
                var domain = Domain.Build(config);
                using (var session = domain.OpenSession()) {
                    using (var transactionScope = session.OpenTransaction()) {
                        // Creating initial content
                        new Person(session)
                        {
                            Name = "Tereza", Address = new Address(session)
                            {
                                Country = "Czech Republic", City = "Prague", Street = "Vinohradska", Building = "34"
                            }
                        };
                        new Person(session)
                        {
                            Name = "Ivan", Address = new Address(session)
                            {
                                Country = "Russia", City = "Ekaterinburg", Street = "Lenina", Building = "11/2"
                            }
                        };

                        transactionScope.Complete();
                    }
                }
                existingDomain = domain;
            }
            return(existingDomain);
        }
        private static Domain BuildDomain()
        {
            var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();

            config.Types.Register(typeof(Simple).Assembly, typeof(Simple).Namespace);
            return(Domain.Build(config));
        }
        public void SessionConfigurationTest()
        {
            // Creating new Domain configuration
            var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();

            config.UpgradeMode = DomainUpgradeMode.Recreate;
            // Registering all types in the specified assembly and namespace
            config.Types.Register(typeof(Person).Assembly, typeof(Person).Namespace);
            // And finally building the domain
            var domain = Domain.Build(config);

            // First named Session configuration
            var sessionCongfigOne = new SessionConfiguration {
                BatchSize             = 25,
                DefaultIsolationLevel = IsolationLevel.RepeatableRead,
                CacheSize             = 16384,
                Options = SessionOptions.ServerProfile
            };

            // Second named Session configuration
            var sessionConfigTwo = config.Sessions["TestSession"];

            Assert.AreEqual(sessionConfigTwo.BatchSize, sessionCongfigOne.BatchSize);
            Assert.AreEqual(sessionConfigTwo.DefaultIsolationLevel, sessionCongfigOne.DefaultIsolationLevel);
            Assert.AreEqual(sessionConfigTwo.CacheSize, sessionCongfigOne.CacheSize);
            Assert.AreEqual(sessionConfigTwo.Options, sessionCongfigOne.Options);

            using (domain.OpenSession(sessionConfigTwo)) {
                // ...
            }
        }
        private Domain GetDomain()
        {
            if (existingDomain == null)
            {
                var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();
                config.UpgradeMode = DomainUpgradeMode.Recreate;
                config.Types.Register(typeof(Person).Assembly, typeof(Person).Namespace);
                var domain     = Domain.Build(config);
                var sessionCfg = new SessionConfiguration();
                sessionCfg.Options |= SessionOptions.AutoActivation;
                using (var session = domain.OpenSession(sessionCfg)) {
                    using (var transactionScope = session.OpenTransaction()) {
                        // Creating initial content
                        new Person {
                            Name = "Tereza"
                        };
                        new Person {
                            Name = "Ivan"
                        };

                        transactionScope.Complete();
                    }
                }
                existingDomain = domain;
            }
            return(existingDomain);
        }
        public void BuildFourthDomain()
        {
            var domainConfig = DomainConfigurationFactory.CreateWithoutSessionConfigurations();

            domainConfig.Types.Register(myAssembly, typeof(Model_4.Order).Namespace);
            domainConfig.UpgradeMode = DomainUpgradeMode.PerformSafely;
            var domain = Domain.Build(domainConfig);

            using (var session = domain.OpenSession()) {
                using (var transactionScope = session.OpenTransaction()) {
                    int productCount = session.Query.All <Model_4.Product>().Count();
                    Assert.AreEqual(2, productCount);

                    var order = session.Query.All <Model_4.Order>().First();

                    AssertEx.Throws <Exception>(() => {
#pragma warning disable 612,618
                        var name = order.ProductName;
#pragma warning restore 612,618
                    });

                    transactionScope.Complete();
                }
            }
        }
        public void ConfigTest()
        {
            Require.ProviderIs(StorageProvider.SqlServer);
            var domainConfiguration  = DomainConfigurationFactory.CreateWithoutSessionConfigurations();
            var defaultSessionConfig = new SessionConfiguration(WellKnown.Sessions.Default)
            {
                DefaultCommandTimeout = 100
            };
            var systemSessionConfig = new SessionConfiguration(WellKnown.Sessions.System)
            {
                DefaultCommandTimeout = 6000
            };

            domainConfiguration.Sessions.Add(defaultSessionConfig);
            domainConfiguration.Sessions.Add(systemSessionConfig);

            using (var domain = Domain.Build(domainConfiguration)) {
                using (var session = domain.OpenSession()) {
                    Assert.AreEqual(100, session.CommandTimeout);
                }
                var sessionConfiguration = new SessionConfiguration {
                    DefaultCommandTimeout = 100
                };
                using (var session = domain.OpenSession(sessionConfiguration)) {
                    Assert.AreEqual(100, session.CommandTimeout);
                }
            }
        }
        private Domain GetDomain()
        {
            if (existingDomain == null)
            {
                var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();
                config.UpgradeMode = DomainUpgradeMode.Recreate;
                config.Types.Register(typeof(Person).Assembly, typeof(Person).Namespace);
                config.Types.Register(typeof(CustomLinqCompilerContainer));

                var domain = Domain.Build(config);
                using (var session = domain.OpenSession()) {
                    using (var transactionScope = session.OpenTransaction()) {
                        // Creating initial content
                        new Person(session)
                        {
                            FirstName = "Ivan", LastName = "Semenov"
                        };
                        new Person(session)
                        {
                            FirstName = "John", LastName = "Smith"
                        };
                        new Person(session)
                        {
                            FirstName = "Andrew", LastName = "Politkovsky"
                        };

                        transactionScope.Complete();
                    }
                }
                existingDomain = domain;
            }
            return(existingDomain);
        }
示例#9
0
        public async Task MultipleBatchesAsyncTest()
        {
            var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();

            config.UpgradeMode = DomainUpgradeMode.Recreate;
            config.Types.Register(typeof(Person).Assembly, typeof(Person).Namespace);
            var domain = Domain.Build(config);

            int count = 1000;

            using (var session = domain.OpenSession())
                using (var transactionScope = session.OpenTransaction()){
                    var random = new Random(10);
                    for (int i = 0; i < count; i++)
                    {
                        new Person(session)
                        {
                            Name = i.ToString(), Photo = new[] { (byte)(i % 256) }
                        }
                    }
                    ;
                    var persons = session.Query.All <Person>().OrderBy(p => p.Id).ToArray();
                    for (int i = 0; i < count; i++)
                    {
                        var person = persons[i];
                        if (random.Next(5) > 0)
                        {
                            person.Manager = persons[random.Next(count)];
                        }
                    }
                    transactionScope.Complete();
                }

            using (var session = domain.OpenSession())
                using (var transactionScope = session.OpenTransaction()) {
                    var prefetchedPersons = (
                        from person in session.Query.All <Person>()
                        orderby person.Name
                        select person)
                                            .Take(100)
                                            .Prefetch(p => p.Photo)            // Lazy load field
                                            .Prefetch(p => p.Employees         // EntitySet Employees
                                                      .Prefetch(e => e.Photo)) // and lazy load field of each of its items
                                            .Prefetch(p => p.Manager)          // Referenced entity
                                            .AsAsync();
                    foreach (var person in await prefetchedPersons)
                    {
                        Assert.IsTrue(DirectStateAccessor.Get(person).GetFieldState("Photo") == PersistentFieldState.Loaded);
                        Assert.IsTrue(DirectStateAccessor.Get(person).GetFieldState("Manager") == PersistentFieldState.Loaded);
                        Assert.IsTrue(DirectStateAccessor.Get(person.Employees).IsFullyLoaded);
                        foreach (var employee in person.Employees)
                        {
                            Assert.IsTrue(DirectStateAccessor.Get(employee).GetFieldState("Photo") == PersistentFieldState.Loaded);
                        }
                    }
                    transactionScope.Complete();
                }
        }
    }
示例#10
0
        public void MainTest()
        {
            var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();

            config.UpgradeMode = DomainUpgradeMode.Recreate;
            config.Types.Register(typeof(Person));
            Domain.Build(config);
        }
        private Domain BuildDomain()
        {
            var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();

            config.UpgradeMode = DomainUpgradeMode.Recreate;
            config.Types.Register(typeof(User).Assembly, typeof(User).Namespace);
            return(Domain.Build(config));
        }
        protected override DomainConfiguration BuildConfiguration()
        {
            var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();

            config.UpgradeMode = DomainUpgradeMode.Recreate;
            config.Types.Register(typeof(Person).Assembly, typeof(Person).Namespace);
            return(config);
        }
示例#13
0
        public void MainTest()
        {
            var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();

            config.UpgradeMode = DomainUpgradeMode.Recreate;
            config.Types.Register(typeof(Product));
//      config.Types.Register(typeof(Document).Assembly, typeof(Document).Namespace);
            Domain.Build(config);
        }
示例#14
0
 private Domain GetDomain()
 {
     if (existingDomain == null)
     {
         var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();
         config.UpgradeMode = DomainUpgradeMode.Recreate;
         config.Types.Register(typeof(Person).Assembly, typeof(Person).Namespace);
         var domain = Domain.Build(config);
         existingDomain = domain;
     }
     return(existingDomain);
 }
示例#15
0
        public void MainTest()
        {
            var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();

            config.UpgradeMode = DomainUpgradeMode.Recreate;
            config.Types.Register(typeof(Pet).Assembly, typeof(Pet).Namespace);
            var domain = Domain.Build(config);

            using (var session = domain.OpenSession()) {
                using (var t = session.OpenTransaction()) {
                    // ...
                }
            }
        }
示例#16
0
        public void MainTest()
        {
            // Creatign new Domain configuration
            var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();

            config.UpgradeMode = DomainUpgradeMode.Recreate;
            // Modifying it by registering the persistent types
            config.Types.Register(typeof(User).Assembly, typeof(User).Namespace);
            // And finally building the domain
            var domain = Domain.Build(config);

            using (var session = domain.OpenSession()) {
                using (var transactionScope = session.OpenTransaction()) {
                    // Creating user
                    var dmitri = new User(session)
                    {
                        Name = "Dmitri"
                    };

                    // Modifying the entity
                    dmitri.Name = "Dmitri Maximov";

                    // Opening new nested transaction
                    using (var nestedScope = session.OpenTransaction(TransactionOpenMode.New)) {
                        // Removing the entity
                        dmitri.Remove();
                        Assert.IsTrue(dmitri.IsRemoved);
                        AssertEx.Throws <InvalidOperationException>(() => {
                            var dmitryName = dmitri.Name;
                        });
                        // No nestedScope.Complete(), so nested transaction will be rolled back
                    }

                    // Transparent Entity state update
                    Assert.IsFalse(dmitri.IsRemoved);
                    Assert.AreEqual("Dmitri Maximov", dmitri.Name);

                    // Repeating the same, but using transactional method
                    AssertEx.Throws <InvalidOperationException>(dmitri.RemoveAndCancel);

                    // Transparent Entity state update
                    Assert.IsFalse(dmitri.IsRemoved);
                    Assert.AreEqual("Dmitri Maximov", dmitri.Name);

                    // Marking the transaction scope as completed to commit it
                    transactionScope.Complete();
                }
            }
        }
示例#17
0
 private Domain GetDomain()
 {
     if (existingDomain == null)
     {
         var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();
         config.UpgradeMode = DomainUpgradeMode.Recreate;
         config.Sessions.Add(new SessionConfiguration("Default")
         {
             DefaultIsolationLevel = IsolationLevel.Serializable
         });
         config.Types.Register(typeof(Counter).Assembly, typeof(Counter).Namespace);
         var domain = Domain.Build(config);
         existingDomain = domain;
     }
     return(existingDomain);
 }
示例#18
0
        public void MainTest()
        {
            var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();

            config.UpgradeMode = DomainUpgradeMode.Recreate;
            config.Types.Register(typeof(Person).Assembly, typeof(Person).Namespace);
            var domain = Domain.Build(config);

            using (var session = domain.OpenSession())
                using (var transactionScope = session.OpenTransaction()) {
                    var employee = new Person(session)
                    {
                        Name = "Employee"
                    };
                    var manager = new Person(session)
                    {
                        Name = "Manager"
                    };
                    manager.Employees.Add(employee);

                    var simpleCompiledQuery = session.Query.Execute(qe =>
                                                                    from person in qe.All <Person>()
                                                                    orderby person.Name
                                                                    select person
                                                                    );
                    var managedPersonCount = session.Query.CreateDelayedQuery(qe => (
                                                                                  from person in qe.All <Person>()
                                                                                  where person.Manager != null
                                                                                  select person
                                                                                  ).Count());
                    var personsWithEmployees = session.Query.CreateDelayedQuery(qe =>
                                                                                from person in session.Query.All <Person>()
                                                                                where person.Employees.Count != 0
                                                                                select person
                                                                                );

                    Console.WriteLine("All persons: {0}",
                                      simpleCompiledQuery.ToCommaDelimitedString());
                    Console.WriteLine("Managed person count: {0}",
                                      managedPersonCount.Value);
                    Console.WriteLine("Person with employees: {0}",
                                      personsWithEmployees.ToCommaDelimitedString());

                    transactionScope.Complete();
                }
        }
示例#19
0
        public void CombinedTest()
        {
            // Creating new Domain configuration
            var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();

            config.UpgradeMode = DomainUpgradeMode.Recreate;
            // Registering all types in the specified assembly and namespace
            config.Types.Register(typeof(Author).Assembly, typeof(Author).Namespace);
            // And finally building the domain
            var domain = Domain.Build(config);

            using (var session = domain.OpenSession()) {
                using (var transactionScope = session.OpenTransaction()) {
                    // Creating two authors
                    var joseph = new Author(session)
                    {
                        Name = "Joseph Albahari"
                    };
                    var ben = new Author(session)
                    {
                        Name = "Ben Albahari"
                    };

                    // Creating the Book book with book.Id = joseph.Id
                    var book = new Book(session, joseph.Id)
                    {
                        Name = "C# 4.0 in a Nutshell"
                    };
                    book.Authors.Add(joseph);
                    book.Authors.Add(ben);

                    // Testing ProxyKeyGenerator
                    Assert.AreSame(joseph, session.Query.SingleOrDefault(joseph.Key));
                    Assert.AreSame(ben, session.Query.SingleOrDefault(ben.Key));
                    // Must fail, if [KeyGenerator(typeof(ProxyKeyGenerator<Book, Author>))]
                    // line is commented
                    Assert.AreSame(book, session.Query.SingleOrDefault(book.Key));

                    // Let's finally print the Book
                    Console.WriteLine(book);

                    transactionScope.Complete();
                }
            }
        }
示例#20
0
        public void BuildThirdDomain()
        {
            var domainConfig = DomainConfigurationFactory.CreateWithoutSessionConfigurations();

            domainConfig.Types.Register(myAssembly, typeof(Model_3.Order).Namespace);
            domainConfig.UpgradeMode = DomainUpgradeMode.PerformSafely;
            var domain = Domain.Build(domainConfig);

            using (var session = domain.OpenSession()) {
                using (var transactionScope = session.OpenTransaction()) {
                    var cheeseOrder = session.Query.All <Model_3.Order>().FirstOrDefault(o => o.ProductName == "Cheese");

                    Assert.IsNotNull(cheeseOrder);
                    Assert.AreEqual(10, cheeseOrder.Quantity);
                    Assert.AreEqual("Michael", cheeseOrder.Customer.FullName);

                    transactionScope.Complete();
                }
            }
        }
        public void MainTest()
        {
            var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();

            config.UpgradeMode = DomainUpgradeMode.Recreate;
            config.Types.Register(typeof(Product).Assembly, typeof(Product).Namespace);
            config.Types.Register(typeof(CustomLinqCompilerContainer));
            var domain = Domain.Build(config);

            using (var session = domain.OpenSession()) {
                using (var t = session.OpenTransaction()) {
                    var apple = new Product(session)
                    {
                        Name = "Apple", Price = 2.0
                    };
                    var appleOrder = new Order(session)
                    {
                        Product = apple, Quantity = 1
                    };
                    // var banana = new Product {Name = "Banana", Price = 1.0};
                    // var bananaOrder = new Order {Product = banana, Quantity = 2};

                    // First time calculation
                    CheckTotalPrice(appleOrder);

                    using (session.OpenTransaction(TransactionOpenMode.New)) {
                        appleOrder.Quantity = 3;
                        apple.Price         = 3;
                        // Automatic update
                        CheckTotalPrice(appleOrder);
                        // No transactionScope.Complete(), so here we get a rollback
                    }

                    // Recovery after rollback
                    CheckTotalPrice(appleOrder);

                    Console.WriteLine("Sleeping for 1 sec.");
                    Thread.Sleep(TimeSpan.FromSeconds(1.1));
                }
            }
        }
示例#22
0
        public void MainTest()
        {
            var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();

            config.UpgradeMode = DomainUpgradeMode.Recreate;
            config.Types.Register(typeof(Range).Assembly, typeof(Range).Namespace);
            var domain = Domain.Build(config);

            using (var session = domain.OpenSession()) {
                using (var t = session.OpenTransaction()) {
                    // Example 1
                    Range range = new Range(session);
                    range.Left.X = 0;
                    range.Left.Y = 0;

                    // getting "range.Left" value
                    Point point = range.Left;
                    // "range.Left" & "point" are the same instance
                    Assert.IsTrue(ReferenceEquals(point, range.Left));

                    // Let's modify "point" instance.
                    // "range.Left" will be changed automatically
                    point.X = 10;
                    Assert.AreEqual(10, range.Left.X);

                    // Example 2
                    // Copy-on-assignment behavior
                    range.Right = range.Left;
                    // Instances are not equal although they have the same values
                    Assert.IsFalse(ReferenceEquals(range.Right, range.Left));
                    Assert.AreEqual(range.Right.X, range.Left.X);
                    Assert.AreEqual(range.Right.Y, range.Left.Y);

                    // Example 3
                    var points = session.Query.All <Range>().Select(r => r.Left);
                    // or
                    var ranges = session.Query.All <Range>().Where(r => r.Left == new Point(0, 10));
                }
            }
        }
        public void MainTest()
        {
            var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();

            config.UpgradeMode = DomainUpgradeMode.Recreate;
            config.Types.Register(typeof(Person));
            var domain = Domain.Build(config);

            using (var session = domain.OpenSession()) {
                using (var transactionScope = session.OpenTransaction()) {
                    var alex = new Person(session)
                    {
                        FirstName = "Alex", LastName = "Kofman", Age = 26
                    };
                    var ivan = new Person(session)
                    {
                        FirstName = "Ivan", LastName = "Galkin", Age = 28
                    };

                    Assert.AreEqual(alex, GetPersonByName(session, "Alex", "Kofman"));

                    var adults = GetPersonOverAge(session, 27);
                    Assert.AreEqual(1, adults.Count());
                    Assert.AreEqual(ivan, adults.First());

                    transactionScope.Complete();
                }

                AssertEx.Throws <StorageException>(() => {
                    using (var transactionScope = session.OpenTransaction()) {
                        new Person(session)
                        {
                            FirstName = "Alex", LastName = "Kofman", Age = 0
                        };
                        transactionScope.Complete();
                    }
                });
            }
        }
        public void OpenSessionTest()
        {
            #region Domain sample

            // Creating new Domain configuration
            var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();
            config.UpgradeMode = DomainUpgradeMode.Recreate;
            // Registering all types in the specified assembly and namespace
            config.Types.Register(typeof(Person).Assembly, typeof(Person).Namespace);
            // And finally building the domain
            var domain = Domain.Build(config);

            using (var session = domain.OpenSession()) {
                using (var transactionScope = session.OpenTransaction()) {
                    var person = new Person(session);
                    person.Name = "Barack Obama";

                    transactionScope.Complete();
                }
            }

            #endregion
        }
示例#25
0
        public void MainTest()
        {
            // Creatign new Domain configuration
            var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();

            // Modifying it by registering the persistent types
            config.Types.Register(typeof(MyEntity).Assembly, typeof(MyEntity).Namespace);
            // And finally building the domain
            var domain = Domain.Build(config);

            using (var session = domain.OpenSession()) {
                // Session don't activated by default
                Debug.Assert(Session.Current == null);
            }

            var sessionConfiguration = new SessionConfiguration(SessionOptions.ServerProfile | SessionOptions.AutoActivation);

            using (var session = domain.OpenSession(sessionConfiguration))
                using (var transactionScope = session.OpenTransaction()) {
                    Debug.Assert(Session.Current == session);
                    var helloWorld = new MyEntity {
                        Text = "Hello World!"
                    };
                    // Marking transaction as committable
                    transactionScope.Complete();
                }

            // Reading all persisted objects from another Session
            using (var session = domain.OpenSession())
                using (var transactionScope = session.OpenTransaction()) {
                    foreach (var myEntity in session.Query.All <MyEntity>())
                    {
                        Console.WriteLine(myEntity.Text);
                    }
                    transactionScope.Complete();
                }
        }
示例#26
0
        private void BuildSecondDomain()
        {
            var domainConfig = DomainConfigurationFactory.CreateWithoutSessionConfigurations();

            domainConfig.Types.Register(myAssembly, typeof(Model_2.Order).Namespace);
            domainConfig.UpgradeMode = DomainUpgradeMode.PerformSafely;
            var domain = Domain.Build(domainConfig);

            using (var session = domain.OpenSession()) {
                using (var transactionScope = session.OpenTransaction()) {
                    var cheeseOrder = session.Query.All <Model_2.Order>().FirstOrDefault(o => o.ProductName == "Cheese");

                    Assert.IsNotNull(cheeseOrder);
                    Assert.AreEqual(10, cheeseOrder.Quantity);
                    Assert.IsNull(cheeseOrder.Customer);
                    cheeseOrder.Customer = new Model_2.Customer(session)
                    {
                        Name = "Michael"
                    };

                    var customer = new Model_2.Customer(session)
                    {
                        Name = "Tony"
                    };
                    foreach (var order in session.Query.All <Model_2.Order>())
                    {
                        if (order.Customer == null)
                        {
                            order.Customer = customer;
                        }
                    }

                    transactionScope.Complete();
                }
            }
        }
示例#27
0
        public void MainTest()
        {
            var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();

            config.UpgradeMode = DomainUpgradeMode.Recreate;
            config.Types.Register(typeof(Author).Assembly, typeof(Author).Namespace);
            var domain = Domain.Build(config);

            using (var session = domain.OpenSession()) {
                using (var transactionScope = session.OpenTransaction()) {
                    var author = new Author(session);
                    var sciFi  = new SciFi(session)
                    {
                        Author = author
                    };
                    var horror = new Horror(session)
                    {
                        Author = author
                    };

                    transactionScope.Complete();
                }
            }
        }
        public void CurrentSessionTest()
        {
            #region Session sample

            // Creating new Domain configuration
            var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();
            config.UpgradeMode = DomainUpgradeMode.Recreate;

            // Registering all types in the specified assembly and namespace
            config.Types.Register(typeof(Person).Assembly, typeof(Person).Namespace);
            // And finally building the domain
            var domain = Domain.Build(config);

            int personId;
            using (var session = domain.OpenSession()) {
                using (var transactionScope = session.OpenTransaction()) {
                    personId = new Person(session).Id;

                    transactionScope.Complete();
                }
            }

            // Opens the session with default configuration - ServerProfile. Auto actiovation option is disabled.
            using (var session = domain.OpenSession()) {
                using (var transactionScope = session.OpenTransaction()) {
                    // you need to provide session explicitly
                    var newPerson     = new Person(session);
                    var fetchedPerson = session.Query.Single <Person>(personId);

                    Console.WriteLine("Current session is null: {0}", Session.Current == null);
                    Console.WriteLine("New entity is bound to our session: {0}", newPerson.Session == session);
                    Console.WriteLine("Fetched entity is bound to our session: {0}", fetchedPerson.Session == session);

                    transactionScope.Complete();
                }
            }

            // New session configuration with actiovation option enabled.
            var sessionConfiguration = new SessionConfiguration(SessionOptions.AutoActivation | SessionOptions.AutoSaveChanges);
            using (var session = domain.OpenSession(sessionConfiguration)) {
                using (var transactionScope = session.OpenTransaction()) {
                    // you don't need to provide session explicitly. Active session will be used instead.
                    var newPerson     = new Person();
                    var fetchedPerson = session.Query.Single <Person>(personId);

                    Console.WriteLine("Our session is current: {0}", Session.Current == session);
                    Console.WriteLine("New entity is bound to our session: {0}", newPerson.Session == session);
                    Console.WriteLine("Fetched entity is bound to our session: {0}", fetchedPerson.Session == session);

                    transactionScope.Complete();
                }
            }

            #endregion

            using (var session = domain.OpenSession()) {
                using (var transactionScope = session.OpenTransaction()) {
                    var person = new Person(session);
                    person.Name = "Barack Obama";

                    transactionScope.Complete();
                }
            }
        }
示例#29
0
        public void MainTest()
        {
            var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();

            config.UpgradeMode = DomainUpgradeMode.Recreate;
            config.Types.Register(typeof(Person).Assembly, typeof(Person).Namespace);
            var domain = Domain.Build(config);

            DumpAutoRegisteredGenericInstances(domain);

            Cat    tom;
            Cat    musya;
            Person alex;

            using (var session = domain.OpenSession())
                using (var ss = session.Activate()) {
                    using (var tx = session.OpenTransaction()) {
                        tom = new Cat(session)
                        {
                            Name = "Tom"
                        };
                        new Dog(session)
                        {
                            Name = "Sharik"
                        };
                        tx.Complete();
                    }
                    using (var tx = session.OpenTransaction()) {
                        Assert.AreEqual(1, session.Query.All <TransactionInfo>().Count());
                        Assert.AreEqual(2, session.Query.All <AuditRecord <Animal> >().Count());
                        musya = new Cat(session);
                        tx.Complete();
                    }

                    // Auto transactions
                    using (var tx = session.OpenTransaction()) {
                        musya.Name = "Musya";
                        musya.Remove();
                        tx.Complete();
                    }

                    // Rollback test
                    using (var tx = session.OpenTransaction()) {
                        tom.Name = "Shushera";
                        // tx.Complete();
                    }

                    // Another session & transaction
                    using (Session.Deactivate()) // Blocks session switching check
                        using (var session2 = domain.OpenSession()) {
                            using (var tx = session2.OpenTransaction()) {
                                alex = new Person(session2)
                                {
                                    Name = "Alex"
                                };
                                tx.Complete();
                            }
                        }

                    using (var tx = session.OpenTransaction()) {
                        alex = session.Query.Single <Person>(alex.Key); // Materializing entity from enother Session here
                    }

                    using (var tx = session.OpenTransaction())
                    {
                        tom.Owner = alex;
                        tx.Complete();
                    }

                    // And now - the magic!
                    using (var tx = session.OpenTransaction()) {
                        DumpAuditLog();
                    }
                }
        }
示例#30
0
        public void MainTest()
        {
            // Creatign new Domain configuration
            var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();

            config.UpgradeMode = DomainUpgradeMode.Recreate;
            // Modifying it by registering the persistent types
            config.Types.Register(typeof(User).Assembly, typeof(User).Namespace);
            // And finally building the domain
            var domain = Domain.Build(config);

            Key    dmitriKey;
            int    dmitriId;
            string dmitriKeyString;

            // Opening Session
            using (var session = domain.OpenSession()) {
                // Opening transaction
                using (var transactionScope = session.OpenTransaction()) {
                    // Creating user
                    var dmitri = new User(session)
                    {
                        Name = "Dmitri"
                    };

                    // Storing entity key
                    dmitriKey       = dmitri.Key;
                    dmitriKeyString = dmitriKey.Format();
                    dmitriId        = dmitri.Id;

                    Console.WriteLine("Dmitri's Key (human readable): {0}", dmitriKey);
                    Console.WriteLine("Dmitri's Key (serializable): {0}", dmitriKeyString);
                    Console.WriteLine("Dmitri's Id: {0}", dmitriId);

                    // Marking the transaction scope as completed to commit it
                    transactionScope.Complete();
                }

                // Opening another transaction
                using (var transactionScope = session.OpenTransaction()) {
                    // Parses the serialized key
                    var anotherDimtriKey = Key.Parse(session.Domain, dmitriKeyString);
                    // Keys are equal
                    Assert.AreEqual(dmitriKey, anotherDimtriKey);

                    // Materialization on fetch
                    var dmitri = session.Query.Single <User>(dmitriKey);
                    // Alternative way to do the same
                    var anotherDmitri = session.Query.SingleOrDefault <User>(dmitriKey);
                    Assert.AreSame(dmitri, anotherDmitri);
                    // Fetching by key value(s)
                    anotherDmitri = session.Query.Single <User>(dmitriId);
                    Assert.AreSame(dmitri, anotherDmitri);

                    // Querying the storage using regular LINQ query
                    var query =
                        from user in session.Query.All <User>()
                        where user.Name == "Dmitri"
                        select user;
                    Assert.AreSame(dmitri, query.First());

                    // Querying the storage using compiled query
                    anotherDmitri = session.Query.Execute(qe => // Default caching key is methodof( () => ... )
                                                          from user in session.Query.All <User>()
                                                          where user.Name == "Dmitri"
                                                          select user).First();
                    Assert.AreSame(dmitri, anotherDmitri);

                    // Querying the storage using compiled future scalar query
                    var delayedDmitry1 = session.Query.ExecuteDelayed(qe => (
                                                                          from user in qe.All <User>()
                                                                          where user.Name == "Dmitri"
                                                                          select user
                                                                          ).FirstOrDefault());
                    var delayedDmitry2 = session.Query.ExecuteDelayed(qe => (
                                                                          from user in qe.All <User>()
                                                                          where user.Id == dmitriId
                                                                          select user
                                                                          ).First());
                    Assert.AreSame(dmitri, delayedDmitry1.Value); // Both queries are executed at once here
                    Assert.AreSame(dmitri, delayedDmitry2.Value);

                    // Modifying the entity
                    dmitri.Name = "Dmitri Maximov";

                    // Opening new nested transaction
                    using (var nestedScope = session.OpenTransaction(TransactionOpenMode.New)) {
                        // Removing the entity
                        dmitri.Remove();
                        Assert.IsTrue(dmitri.IsRemoved);
                        AssertEx.Throws <InvalidOperationException>(() => {
                            var dmitryName = dmitri.Name;
                        });
                        // No nestedScope.Complete(), so nested transaction will be rolled back
                    }

                    // Transparent Entity state update
                    Assert.IsFalse(dmitri.IsRemoved);
                    Assert.AreEqual("Dmitri Maximov", dmitri.Name);

                    // Creating few more objects
                    var xtensiveWebPage = new WebPage(session)
                    {
                        Title = "Xtensive Web Site",
                        Url   = "http://www.x-tensive.com"
                    };
                    var alexYakuninBlogPage = new WebPage(session)
                    {
                        Title = "Alex Yakunin's Blog",
                        Url   = "http://blog.alexyakunin.com"
                    };
                    var subsonicPage = new WebPage(session)
                    {
                        Title = "SubSonic project page",
                        Url   = "http://www.subsonicproject.com/"
                    };

                    // Adding the items to EntitySet
                    dmitri.FavoritePages.Add(xtensiveWebPage);
                    dmitri.FavoritePages.Add(alexYakuninBlogPage);
                    dmitri.FavoritePages.Add(subsonicPage);

                    // Removing the item from EntitySet
                    dmitri.FavoritePages.Remove(subsonicPage);

                    // Getting count of items in EntitySet
                    Console.WriteLine("Dmitri's favorite page count: {0}", dmitri.FavoritePages.Count);
                    Assert.AreEqual(2, dmitri.FavoritePages.Count);
                    Assert.AreEqual(2, dmitri.FavoritePages.Count()); // The same, but by LINQ query

                    // Enumerating EntitySet
                    foreach (var page in dmitri.FavoritePages)
                    {
                        Console.WriteLine("Dmitri's favorite page: {0} ({1})", page.Title, page.Url);
                    }

                    // Checking for the containment
                    Assert.IsTrue(dmitri.FavoritePages.Contains(xtensiveWebPage));
                    Assert.IsTrue(dmitri.FavoritePages.Contains(alexYakuninBlogPage));
                    Assert.IsFalse(dmitri.FavoritePages.Contains(subsonicPage));

                    // Opening new nested transaction
                    using (var nestedScope = session.OpenTransaction(TransactionOpenMode.New)) {
                        // Clearing the EntitySet
                        dmitri.FavoritePages.Clear();
                        Assert.IsFalse(dmitri.FavoritePages.Contains(xtensiveWebPage));
                        Assert.IsFalse(dmitri.FavoritePages.Contains(alexYakuninBlogPage));
                        Assert.IsFalse(dmitri.FavoritePages.Contains(subsonicPage));
                        Assert.AreEqual(0, dmitri.FavoritePages.Count);
                        Assert.AreEqual(0, dmitri.FavoritePages.Count()); // By query
                        // No nestedScope.Complete(), so nested transaction will be rolled back
                    }

                    // Transparent EntitySet state update
                    Assert.IsTrue(dmitri.FavoritePages.Contains(xtensiveWebPage));
                    Assert.IsTrue(dmitri.FavoritePages.Contains(alexYakuninBlogPage));
                    Assert.IsFalse(dmitri.FavoritePages.Contains(subsonicPage));
                    Assert.AreEqual(2, dmitri.FavoritePages.Count);
                    Assert.AreEqual(2, dmitri.FavoritePages.Count()); // The same, but by LINQ query

                    // Finally, let's query the EntitySet:

                    // Query construction
                    var dmitryFavoriteBlogs =
                        from page in dmitri.FavoritePages
                        where page.Url.ToLower().Contains("blog")
                        select page;

                    // Query execution
                    var dmitryFavoriteBlogList = dmitryFavoriteBlogs.ToList();

                    // Printing the results
                    Console.WriteLine("Dmitri's favorite blog count: {0}", dmitryFavoriteBlogList.Count);
                    foreach (var page in dmitryFavoriteBlogList)
                    {
                        Console.WriteLine("Dmitri's favorite blog: {0} ({1})", page.Title, page.Url);
                    }

                    Assert.IsTrue(dmitryFavoriteBlogList.Contains(alexYakuninBlogPage));
                    Assert.IsFalse(dmitryFavoriteBlogList.Contains(xtensiveWebPage));
                    Assert.AreEqual(1, dmitryFavoriteBlogList.Count);

                    // Marking the transaction scope as completed to commit it
                    transactionScope.Complete();
                }
            }
        }