public void UsingLinqViaSessionScopeVariable()
        {
            ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Widget));

            using (ISessionScope scope = new SessionScope())
            {
                Recreate();
                Widget.DeleteAll();

                var widgets = from w in scope.AsQueryable <Widget>() select w;
                Assert.IsNotNull(widgets);
                Assert.AreEqual(0, widgets.Count());

                Widget widget = new Widget {
                    Name = "Hello world"
                };
                widget.Save();

                widgets = from w in scope.AsQueryable <Widget>() where w.Name == "Hello World" select w;
                Assert.IsNotNull(widgets);
                Assert.AreEqual(1, widgets.Count());
            }
        }
        public void Projecting()
        {
            ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Widget));

            using (new SessionScope())
            {
                Recreate();
                Widget.DeleteAll();

                var widget = new Widget {
                    Name = "foo"
                };
                widget.Save();

                var orderedQueryable = ActiveRecordLinqBase <Widget> .Queryable;
                var widgets          = (from w in orderedQueryable
                                        where w.Name.StartsWith("f")
                                        select w.Name).ToList();

                Assert.IsNotNull(widgets);
                Assert.AreEqual("foo", widgets.Single());
            }
        }
Exemplo n.º 3
0
        private static void InitializeFacilities()
        {
            //init for the log system
            var configForLogging = ConfigurationManager.AppSettings["LoggingConfig"].ToServerPath();

            log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(configForLogging));

            //init the database
            var configForDatabase       = ConfigurationManager.AppSettings["DatabaseConfig"].ToServerPath();
            IConfigurationSource source = new XmlConfigurationSource(configForDatabase);

            ActiveRecordStarter.Initialize(source,
                                           typeof(Data.Log), //为避免数据库体积过大,将日志记录至 /tmp 目录下
                                           typeof(Users),
                                           typeof(Roles),
                                           typeof(Account),
                                           typeof(Block),
                                           typeof(Bot),
                                           typeof(Mine),
                                           typeof(MineProfile),
                                           typeof(Share)
                                           );
        }
Exemplo n.º 4
0
        public void CanLoadLazyBelongsToOutsideOfScope()
        {
            ActiveRecordStarter.Initialize(GetConfigSource(), typeof(ScopelessLazy), typeof(ObjectWithLazyAssociation2),
                                           typeof(VeryLazyObject2));

            Recreate();

            var lazy = new VeryLazyObject2();

            lazy.Title = "test";
            ActiveRecordMediator.Save(lazy);

            var obj = new ObjectWithLazyAssociation2();

            obj.LazyObj = lazy;
            ActiveRecordMediator.Save(obj);

            var objFromDb = (ObjectWithLazyAssociation2)ActiveRecordMediator.FindByPrimaryKey(typeof(ObjectWithLazyAssociation2), obj.Id);

            Assert.False(NHibernate.NHibernateUtil.IsInitialized(objFromDb.LazyObj));
            Assert.AreEqual("test", objFromDb.LazyObj.Title);
            Assert.True(NHibernate.NHibernateUtil.IsInitialized(objFromDb.LazyObj));
        }
Exemplo n.º 5
0
        public void SimpleOperations2()
        {
            ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Post), typeof(Blog));
            Recreate();

            Post.DeleteAll();
            Blog.DeleteAll();

            Blog[] blogs = Blog.FindAll();

            Assert.IsNotNull(blogs);
            Assert.AreEqual(0, blogs.Length);

            Blog blog = new Blog();

            blog.Name   = "hammett's blog";
            blog.Author = "hamilton verissimo";
            blog.Create();

            blogs = Blog.FindAll();
            Assert.AreEqual(blog.Name, blogs[0].Name);
            Assert.AreEqual(blog.Author, blogs[0].Author);

            Assert.IsNotNull(blogs);
            Assert.AreEqual(1, blogs.Length);

            blog.Name   = "something else1";
            blog.Author = "something else2";
            blog.Update();

            blogs = Blog.FindAll();

            Assert.IsNotNull(blogs);
            Assert.AreEqual(1, blogs.Length);
            Assert.AreEqual(blog.Name, blogs[0].Name);
            Assert.AreEqual(blog.Author, blogs[0].Author);
        }
        public void SimpleOperations2()
        {
            ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Post), typeof(Blog));

            using (new SessionScope())
            {
                Recreate();

                Post.DeleteAll();
                Blog.DeleteAll();

                var blogs = Blog.Queryable;
                Assert.IsNotNull(blogs);
                Assert.AreEqual(0, blogs.Count());

                Blog blog = new Blog();
                blog.Name   = "hammett's blog";
                blog.Author = "hamilton verissimo";
                blog.Create();

                Assert.AreEqual(1, (from b in Blog.Queryable select b).Count());

                blogs = Blog.Queryable;
                Assert.AreEqual(blog.Name, blogs.First().Name);
                Assert.AreEqual(blog.Author, blogs.First().Author);

                blog.Name   = "something else1";
                blog.Author = "something else2";
                blog.Update();

                blogs = Blog.Queryable;
                Assert.IsNotNull(blogs);
                Assert.AreEqual(1, Blog.Queryable.Count());
                Assert.AreEqual(blog.Name, blogs.First().Name);
                Assert.AreEqual(blog.Author, blogs.First().Author);
            }
        }
        public void TransactionScopeUsage()
        {
            ISession session1, session2, session3, session4;

            ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Post), typeof(Blog));
            Recreate();

            using (new TransactionScope())
            {
                session1 = Blog.Holder.CreateSession(typeof(Blog));
                session2 = Blog.Holder.CreateSession(typeof(Post));
                session3 = Blog.Holder.CreateSession(typeof(Blog));
                session4 = Blog.Holder.CreateSession(typeof(Post));

                Assert.IsNotNull(session1);
                Assert.IsNotNull(session2);
                Assert.IsNotNull(session3);
                Assert.IsNotNull(session3);

                Assert.IsTrue(session2 == session1);
                Assert.IsTrue(session3 == session1);
                Assert.IsTrue(session4 == session1);
            }

            // Old behavior

            session1 = Blog.Holder.CreateSession(typeof(Blog));
            session2 = Blog.Holder.CreateSession(typeof(Blog));

            Assert.IsNotNull(session1);
            Assert.IsNotNull(session2);
            Assert.IsTrue(session1 != session2);

            Blog.Holder.ReleaseSession(session1);
            Blog.Holder.ReleaseSession(session2);
        }
Exemplo n.º 8
0
        public void InitializeActiveRecord(Type type)
        {
            try
            {
                if (!ActiveRecordStarter.IsInitialized)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Inicializando o ActiveRecord\r\n******************************");
                    }

                    // TODO: Eu tenho que criar algum valor no arquivo de config onde eu possa setar as assemblies que devem ser inicializadas pelo ActiveRecord, se isso não puder ser setado nas próprias sections do ActiveRecord.
                    //Aqui eu estou inicializando o ActiveRecord, dizendo pra achar as classes que implementam [ActiveRecord] apenas neste assembly (por padrão é o assembly que chama).
                    if (type == null)
                    {
                        ActiveRecordStarter.Initialize(ActiveRecordSectionHandler.Instance);
                    }
//						ActiveRecordStarter.Initialize();
                    else
                    {
                        ActiveRecordStarter.Initialize(Assembly.GetAssembly(type), ActiveRecordSectionHandler.Instance);
                    }
                }
            }
            catch (Exception ex)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("\r\n\r\nErro na inicialização do ActiveRecord!!!", ex);
                }

                throw new Castle.ActiveRecord.Framework.ActiveRecordInitializationException(
                          "Não foi possível inicializar o ActiveRecord. Dica: Verifique se todas os BaseDao's estão declarados como abstract.",
                          ex);
            }
        }
Exemplo n.º 9
0
        public void IsUnique2()
        {
            ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Blog3));
            Recreate();

            Blog3.DeleteAll();

            Blog3 blog = new Blog3();

            blog.Id   = "assignedKey";
            blog.Name = "First Blog";
            blog.Create();

            blog      = new Blog3();
            blog.Id   = "assignedKey";
            blog.Name = "Second Blog";

            String[] messages = blog.ValidationErrorMessages;
            Assert.IsTrue(messages.Length == 1);
            Assert.AreEqual("Id is currently in use. Please pick up a new Id.", messages[0]);
            //Assert.AreEqual("The ID you specified already exists.", messages[0]); //TODO: Fix it (custom validation messages).

            blog.Create();
        }
Exemplo n.º 10
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            ActiveRecordStarter.ResetInitializationFlag();

            IDictionary <string, string> properties = new Dictionary <string, string>
            {
                { "connection.driver_class", "NHibernate.Driver.SqlClientDriver" },
                { "dialect", "NHibernate.Dialect.MsSql2008Dialect" },
                { "connection.provider", "NHibernate.Connection.DriverConnectionProvider" },


                //Catalog Name Table. Как создать БД с помощью метода ActiveRecordStarter.CreateSchema();
                //пока выяснить не удалось но CreateSchema() прекрасно добавляет таблицы к БД
                { "connection.connection_string", "Data Source=PC;Initial Catalog=vvv;Integrated Security=True" },
                {
                    "proxyfactory.factory_class",
                    @"NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle"
                }
            };



            try
            {
                InPlaceConfigurationSource source = new InPlaceConfigurationSource();
                source.Add(typeof(ActiveRecordBase), properties);

                ActiveRecordStarter.Initialize(source, MainDBHelper.GetTypes());

                ActiveRecordStarter.CreateSchema();
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.ToString());
            }
        }
Exemplo n.º 11
0
        private static void ConfigureDatabase()
        {
            ActiveRecordStarter.Initialize(
                InPlaceConfigurationSource.BuildForMSSqlServer("localhost", "test"),
                typeof(Customer),
                typeof(CustomerOperation),
                typeof(Operation));
            ActiveRecordStarter.CreateSchema();
            Customer customer = new Customer();

            customer.Name = "oren";
            ActiveRecordMediator.Save(customer);

            Operation op = new Operation();

            op.Name = "View";
            ActiveRecordMediator.Save(op);

            CustomerOperation co = new CustomerOperation();

            co.Customer  = customer;
            co.Operation = op;
            ActiveRecordMediator.Save(co);
        }
Exemplo n.º 12
0
        public void SimpleOperationsShowingBug()
        {
            ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Post), typeof(Blog));

            Recreate();


            Post.DeleteAll();
            Blog.DeleteAll();

            var blogs = from b in Blog.Queryable select b;

            Assert.IsNotNull(blogs);
            Assert.AreEqual(0, blogs.Count());

            var blog = new Blog
            {
                Name   = "hammett's blog",
                Author = "hamilton verissimo"
            };

            blog.Save();


            blogs = from b in Blog.Queryable select b;
            Assert.IsNotNull(blogs);
            Assert.AreEqual(1, blogs.Count());

            // this line will fail because of blogs.Count above
            var retrieved = blogs.First();

            Assert.IsNotNull(retrieved);

            Assert.AreEqual(blog.Name, retrieved.Name);
            Assert.AreEqual(blog.Author, retrieved.Author);
        }
Exemplo n.º 13
0
        public void ExistsTest()
        {
            ActiveRecordStarter.Initialize(GetConfigSource());
            ActiveRecordStarter.RegisterTypes(typeof(Blog), typeof(Post));
            Recreate();

            Blog blog = new Blog();

            blog.Name   = "hammett's blog";
            blog.Author = "hamilton verissimo";
            blog.Save();

            Assert.IsTrue(blog.Id > 0);
            Assert.IsTrue(Blog.Exists(blog.Id));

            blog        = new Blog();
            blog.Name   = "chad's blog";
            blog.Author = "chad humphries";
            blog.Save();

            Assert.IsTrue(Blog.Exists(blog.Id));

            Assert.IsFalse(Blog.Exists(1000));
        }
Exemplo n.º 14
0
        public void RelationsOneToOne()
        {
            ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Employee), typeof(Award));
            Recreate();

            Award.DeleteAll();
            Employee.DeleteAll();

            Award    award;
            Employee emp = new Employee();

            using (new SessionScope())
            {
                emp.FirstName = "john";
                emp.LastName  = "doe";
                emp.Save();

                Assert.AreEqual(1, Employee.FindAll().Length);
                Assert.AreEqual(0, Award.FindAll().Length);

                award             = new Award(emp);
                award.Description = "Invisible employee";
                award.Save();
            }

            Assert.AreEqual(1, Award.FindAll().Length);
            Assert.AreEqual(1, Employee.FindAll().Length);

            Employee emp2 = Employee.Find(emp.ID);

            Assert.IsNotNull(emp2);
            Assert.IsNotNull(emp2.Award);
            Assert.AreEqual(emp.FirstName, emp2.FirstName);
            Assert.AreEqual(emp.LastName, emp2.LastName);
            Assert.AreEqual(award.Description, emp2.Award.Description);
        }
Exemplo n.º 15
0
        public void IsUniqueDoesNotDeadlockOnAutoflushTransaction()
        {
            InPlaceConfigurationSource source       = (InPlaceConfigurationSource)GetConfigSource();
            DefaultFlushType           originalType = source.DefaultFlushType;

            try
            {
                ActiveRecordStarter.Initialize(source, typeof(Blog2));
                Recreate();
                source.DefaultFlushType = DefaultFlushType.Auto;

                using (new TransactionScope())
                {
                    Blog2.DeleteAll();
                    Blog2 blog = new Blog2();
                    blog.Name = "FooBar";
                    blog.Save();
                }
            }
            finally
            {
                source.DefaultFlushType = originalType;
            }
        }
Exemplo n.º 16
0
        public void RelationsOneToManyWithWhereAndOrder()
        {
            ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Post), typeof(Blog));
            Recreate();

            Post.DeleteAll();
            Blog.DeleteAll();

            Blog blog = new Blog();

            blog.Name   = "hammett's blog";
            blog.Author = "hamilton verissimo";
            blog.Save();

            Post post1 = new Post(blog, "title1", "contents", "category1");
            Post post2 = new Post(blog, "title2", "contents", "category2");
            Post post3 = new Post(blog, "title3", "contents", "category3");

            post1.Save();
            System.Threading.Thread.Sleep(1000);             // Its a smalldatetime (small precision)
            post2.Save();
            System.Threading.Thread.Sleep(1000);             // Its a smalldatetime (small precision)
            post3.Published = true;
            post3.Save();

            blog = Blog.Find(blog.Id);

            Assert.IsNotNull(blog);
            Assert.AreEqual(2, blog.UnPublishedPosts.Count);
            Assert.AreEqual(1, blog.PublishedPosts.Count);

            Assert.AreEqual(3, blog.RecentPosts.Count);
            Assert.AreEqual(post3.Id, (blog.RecentPosts[0] as Post).Id);
            Assert.AreEqual(post2.Id, (blog.RecentPosts[1] as Post).Id);
            Assert.AreEqual(post1.Id, (blog.RecentPosts[2] as Post).Id);
        }
        /// <summary>
        /// Initialize Active Record, and initialize the container.
        /// If <paramref name="rhinoContainerConfig"/> is <see langword="null" /> or <see cref="string.Empty">string.Empty</see>
        /// a <see cref="RhinoContainer">RhinoContainer</see> will not be initialized.
        /// </summary>
        /// <param name="rhinoContainerConfig">The configuration file to initialize a <see cref="RhinoContainer">RhinoContainer</see>
        /// or <see langword="null" />.</param>
        /// <param name="cfg">The configuration to supply to AR</param>
        /// <param name="assemblies">The assemblies to load for NHibernate mapping files.</param>
        public void OneTimeInitalize(string rhinoContainerConfig, InPlaceConfigurationSource cfg, params Assembly[] assemblies)
        {
            if (cfg == null)
            {
                throw new ArgumentNullException("cfg");
            }

            if (init)
            {
                return;
            }
            init = true;

            cfg.Add(typeof(ActiveRecordBase), CreateProperties());

            //here we either configure the IUnitOfWorkFactory appropriately (which calls ActiveRecordStarter)
            //or we configure ActiveRecordStarter ourselves

            if (!string.IsNullOrEmpty(rhinoContainerConfig))
            {
                if (!IoC.IsInitialized)
                {
                    IoC.Initialize(new RhinoContainer(rhinoContainerConfig));
                }
                IHandler unitOfWorkFactoryHandler = IoC.Container.Kernel
                                                    .GetHandler(typeof(IUnitOfWorkFactory));
                unitOfWorkFactoryHandler
                .AddCustomDependencyValue("configurationSource", cfg);
                unitOfWorkFactoryHandler
                .AddCustomDependencyValue("assemblies", assemblies);
            }
            else
            {
                ActiveRecordStarter.Initialize(assemblies, cfg);
            }
        }
Exemplo n.º 18
0
        public void ErrorMessages()
        {
            Thread.CurrentThread.CurrentCulture       =
                Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-us");

            ActiveRecordStarter.Initialize(GetConfigSource(), typeof(User));

            User         user = new User();
            Type         type = user.GetType();
            PropertyInfo info;
            ArrayList    propertyMessages;

            Assert.IsFalse(user.IsValid());
            Assert.AreEqual(5, user.ValidationErrorMessages.Length);
            Assert.AreEqual("This is a required field", user.ValidationErrorMessages[0]);
            Assert.AreEqual("This is a required field", user.ValidationErrorMessages[1]);
            Assert.AreEqual("This is a required field", user.ValidationErrorMessages[2]);
            Assert.AreEqual("This is a required field", user.ValidationErrorMessages[3]);
            Assert.AreEqual("This is a required field", user.ValidationErrorMessages[4]);

            Assert.AreEqual(5, user.PropertiesValidationErrorMessages.Count);

            info = type.GetProperty("Login");
            Assert.IsTrue(user.PropertiesValidationErrorMessages.Contains(info));
            propertyMessages = (ArrayList)user.PropertiesValidationErrorMessages[info];
            Assert.AreEqual(1, propertyMessages.Count);
            Assert.AreEqual("This is a required field", propertyMessages[0]);

            info = type.GetProperty("Name");
            Assert.IsTrue(user.PropertiesValidationErrorMessages.Contains(info));
            propertyMessages = (ArrayList)user.PropertiesValidationErrorMessages[info];
            Assert.AreEqual(1, propertyMessages.Count);
            Assert.AreEqual("This is a required field", propertyMessages[0]);

            info = type.GetProperty("Email");
            Assert.IsTrue(user.PropertiesValidationErrorMessages.Contains(info));
            propertyMessages = (ArrayList)user.PropertiesValidationErrorMessages[info];
            Assert.AreEqual(1, propertyMessages.Count);
            Assert.AreEqual("This is a required field", propertyMessages[0]);

            info = type.GetProperty("Password");
            Assert.IsTrue(user.PropertiesValidationErrorMessages.Contains(info));
            propertyMessages = (ArrayList)user.PropertiesValidationErrorMessages[info];
            Assert.AreEqual(1, propertyMessages.Count);
            Assert.AreEqual("This is a required field", propertyMessages[0]);

            info = type.GetProperty("ConfirmationPassword");
            Assert.IsTrue(user.PropertiesValidationErrorMessages.Contains(info));
            propertyMessages = (ArrayList)user.PropertiesValidationErrorMessages[info];
            Assert.AreEqual(1, propertyMessages.Count);
            Assert.AreEqual("This is a required field", propertyMessages[0]);

            user.Name                 = "hammett";
            user.Login                = "******";
            user.Email                = "*****@*****.**";
            user.Password             = "******";
            user.ConfirmationPassword = "******";

            Assert.IsFalse(user.IsValid());
            Assert.AreEqual(1, user.ValidationErrorMessages.Length);
            Assert.AreEqual("Fields do not match", user.ValidationErrorMessages[0]);

            info = type.GetProperty("Password");
            Assert.IsTrue(user.PropertiesValidationErrorMessages.Contains(info));
            propertyMessages = (ArrayList)user.PropertiesValidationErrorMessages[info];
            Assert.AreEqual(1, propertyMessages.Count);
            Assert.AreEqual("Fields do not match", propertyMessages[0]);

            user.Password = "******";

            Assert.IsTrue(user.IsValid());
            Assert.AreEqual(0, user.ValidationErrorMessages.Length);
        }
Exemplo n.º 19
0
        static void Main(string[] args)
        {
            IConfigurationSource config = ActiveRecordSectionHandler.Instance;

            ActiveRecordStarter.Initialize(Assembly.GetExecutingAssembly(), config);
            ActiveRecordStarter.CreateSchema();

            using (new SessionScope())
            {
                var monorail = new Project {
                    Name = "MonoRail"
                };
                monorail.Save();

                var windsor = new Project {
                    Name = "Windsor"
                };
                windsor.Save();

                var activeRecord = new Project {
                    Name = "ActiveRecord"
                };
                activeRecord.Save();

                var issue1 = new Issue
                {
                    Summary     = "Something went wrong",
                    Description = "blah blah",
                    Project     = monorail,
                    Type        = IssueType.Bug
                };
                issue1.Save();

                var issue2 = new Issue
                {
                    Summary     = "Here is a great idea",
                    Description = "blah blah",
                    Project     = windsor,
                    Type        = IssueType.NewFeature
                };
                issue2.Save();

                var issue3 = new Issue
                {
                    Summary     = "Another thing went wrong",
                    Description = "blah blah",
                    Project     = windsor,
                    Type        = IssueType.Bug
                };
                issue3.Save();
            }

            using (new SessionScope())
            {
                var mr = Project.Find(1);
                mr.Name = "MonoRail 2.0";
                mr.Save();

                IList <Issue> bugs = Issue.FindAllBugs();
                foreach (var bug in bugs)
                {
                    Console.WriteLine("Bug found: " + bug.Summary + ", in project: " + bug.Project.Name);
                }
            }

            Console.WriteLine("Done");
            Console.ReadLine();
        }
Exemplo n.º 20
0
 protected void Recreate()
 {
     ActiveRecordStarter.CreateSchema();
 }
Exemplo n.º 21
0
 public static void InitTable()
 {
     ActiveRecordStarter.CreateSchema();
 }
Exemplo n.º 22
0
 internal void Connect()
 {
     ActiveRecordStarter.Initialize(Assembly.GetExecutingAssembly(), CreateSource());
 }
Exemplo n.º 23
0
 public void Execute(IDocumentStore dataStore)
 {
     ActiveRecordStarter.GenerateCreationScripts("Cricket.sql");
 }
Exemplo n.º 24
0
 protected void Application_Start(Object sender, EventArgs e)
 {
     ActiveRecordStarter.Initialize(ConfigurationSettings.GetConfig("activerecord") as IConfigurationSource, typeof(Movie));
 }
Exemplo n.º 25
0
 public void GenerateCreationScripts(string filePath)
 {
     ActiveRecordStarter.GenerateCreationScripts(filePath);
 }
Exemplo n.º 26
0
 /// <summary>
 /// Drops the Schema of all tables that this has originally initialized with
 /// </summary>
 public static void DropSchema()
 {
     ActiveRecordStarter.DropSchema();
 }
Exemplo n.º 27
0
 /// <summary>
 /// (Drops and re-)creates the Schema of all tables that this has originally initialized with.
 /// </summary>
 public static void CreateSchema()
 {
     ActiveRecordStarter.CreateSchema();
 }
 private void InitializeLazy()
 {
     ActiveRecordStarter.Initialize(GetConfigSource(), typeof(PostLazy), typeof(BlogLazy));
     Recreate();
 }
Exemplo n.º 29
0
 public App()
 {
     ActiveRecordStarter.Initialize(typeof(Post).Assembly, ActiveRecordSectionHandler.Instance);
     sessionScope = new SessionScope();
 }
Exemplo n.º 30
0
        public void Init()
        {
            ActiveRecordStarter.Initialize(GetConfigSource(), typeof(NullableModel));

            Recreate();
        }