Implementation of ISessionScope to augment performance by caching the session, thus avoiding too much opens/flushes/closes.
Inheritance: Castle.ActiveRecord.Framework.Scopes.AbstractScope
        public void AnExceptionInvalidatesTheScopeAndPreventItsFlushing()
        {
            using (new SessionScope()) {
                Post.DeleteAll();
                Blog.DeleteAll();
            }

            Post post;

            // Prepare
            using(new SessionScope())
            {
                var blog = new Blog {Author = "hammett", Name = "some name"};
                blog.Save();

                post = new Post(blog, "title", "contents", "castle");
                post.Save();
            }

            using(var session = new SessionScope())
            {
                Assert.IsFalse(session.HasSessionError);

                Assert.Throws<ActiveRecordException>(() => {
                    post = new Post(new Blog(100), "title", "contents", "castle");
                    post.Save();
                    session.Flush();
                });

                Assert.IsTrue(session.HasSessionError);
            }
        }
 public void NHibernateVerification()
 {
     using (var scope = new SessionScope()) {
         scope.Execute<SSAFEntity>(session => {
             using (session.BeginTransaction())
             {
                 session.Save(new SSAFEntity("example"));
                 Assert.AreEqual(1, session.CreateQuery("from " + typeof(SSAFEntity).FullName).List<SSAFEntity>().Count);
             }
         });
     }
 }
 public void SessionTxVerification()
 {
     using (var scope = new SessionScope()) {
         scope.Execute<SSAFEntity>(session => {
             using (ITransaction tx = session.BeginTransaction())
             {
                 Assert.AreSame(tx, session.BeginTransaction());
                 Assert.AreSame(tx, session.Transaction);
             }
         });
     }
 }
Example #4
0
 public static void DisposeScope()
 {
     if (TransactionScope != null)
     {
         TransactionScope.Dispose();
         TransactionScope = null;
     }
     if (Scope != null)
     {
         Scope.Dispose();
         Scope = null;
     }
 }
Example #5
0
        static void Main(string[] args)
        {
            Utils.InitializeCasteActiveRecordFramework();

            using (var sessionScope = new SessionScope())
            {
                var loader = new CsvLoader("EnDeTranslations.txt", '\t');
                var import = new TranslationImport(loader.DataTable, Language.Find(3), Language.Find(1));
                import.DoImport(true);

                Console.Out.WriteLine("Finished import...");
                Console.ReadKey();
            }
        }
Example #6
0
        public virtual void SetUp()
        {
            ActiveRecordStarter.DropSchema();
            ActiveRecordStarter.CreateSchema();
            scope = new SessionScope();

            userRepository = new ActiveRecordRepository<User>();
            postRepository = new ActiveRecordRepository<Post>();

            PopulateUsers();
            PopulatePosts();

            Flush();
        }
Example #7
0
        public ActionResult Create(Product item)
        {
            if (ModelState.IsValid) {
                using (var session = new SessionScope()) {
                    if (item.Make != MakeEnum.Other) {
                        item.MakeName = item.Make.GetDisplayName ();
                    }
                    item.CreationTime = DateTime.Now;
                    item.CreateAndFlush ();
                }

                System.Diagnostics.Debug.WriteLine ("New CashSession [Id = {0}]", item.Id);

                return RedirectToAction ("Details", new { id = item.Id });
            }

            return View (item);
        }
Example #8
0
        public virtual void SetUp()
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("nl-NL");

            Container.IoC.Initialize();

            //delete an existing database.
            //if no file is found file.delete fails silently
            File.Delete("test.db");

            IConfigurationSource config = ActiveRecordSectionHandler.Instance;

            Assembly asm1 = Assembly.Load("JelloScrum.Model");
            ActiveRecordStarter.Initialize(new Assembly[] { asm1 }, config);

            ActiveRecordStarter.CreateSchema();

            sessionScope = new SessionScope(FlushAction.Never);
        }
        public void AnExceptionInvalidatesTheScopeAndPreventItsFlushing()
        {
            ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Post), typeof(Blog));
            Recreate();

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

            Blog blog;
            Post post;

            // Prepare
            using(new SessionScope())
            {
                blog = new Blog();
                blog.Author = "hammett";
                blog.Name = "some name";
                blog.Save();

                post = new Post(blog, "title", "contents", "castle");
                post.Save();
            }

            using(SessionScope session = new SessionScope())
            {
                Assert.IsFalse(session.HasSessionError);

                try
                {
                    // Forcing an exception
                    post = new Post(new Blog(100), "title", "contents", "castle");
                    post.SaveAndFlush();
                    Assert.Fail("Expecting exception as this operation violates a FK constraint");
                }
                catch(ActiveRecordException)
                {
                    // Exception expected
                }

                Assert.IsTrue(session.HasSessionError);
            }
        }
		public void DicardingChanges()
		{
			Post.DeleteAll();
			Blog.DeleteAll();

			SessionScope scope = new SessionScope();
			
			Blog.FindAll(); // side effects only

			BlogService service = (BlogService) container[ typeof(BlogService) ];
			Blog blog = service.Create( "name", "author" );
			
			Assert.AreEqual( 1, Blog.FindAll().Length );

			blog.Name = "joe developer";

			scope.Dispose(true);

			Assert.AreEqual( "name", Blog.FindAll()[0].Name );
		}
Example #11
0
		public void DicardingChanges()
		{
			Post.DeleteAll();
			Blog.DeleteAll();

			SessionScope scope = new SessionScope(FlushAction.Never);
			
			Blog.FindAll(); // side effects only

			BlogService service = container.Resolve<BlogService>();
			Blog blog = service.Create( "name", "author" );
			
			Assert.AreEqual( 1, Blog.FindAll().Length );

			blog.Name = "joe developer";

			scope.Dispose();

			Assert.AreEqual( "name", Blog.FindAll()[0].Name );
		}
Example #12
0
        public void can_save_new_issue()
        {
            Company company = new Company();
            company.Name = "Test Company";
            company.CreateAndFlush();

            Issue issue = new Issue();
            issue.Title = "Test issue";
            issue.Type = IssueType.Defect;

            IssueNote note = new IssueNote();
            note.Body = "Test note";
            issue.AddNote(note);

            IssueChange change = new IssueChange();
            change.PropertyName = "Test change";
            issue.AddChange(change);

            IssueAttachment att = new IssueAttachment();
            att.Body = new byte[10];
            att.Title = "Test attachment";
            issue.AddAttachment(att);

            Project project = new Project();
            project.Company = company;
            project.AddIssue(issue);
            project.Name = "Test project";
            project.CreateAndFlush();

            using (SessionScope newScope = new SessionScope())
            {
                Issue actual = Issue.Find(issue.Id);
                Assert.AreEqual("Test issue", actual.Title);
                Assert.AreEqual("Test note", actual.Notes[0].Body);
                Assert.AreEqual("Test change", actual.Changes[0].PropertyName);
                Assert.AreEqual("Test attachment", actual.Attachments[0].Title);
            }

            project.DeleteAndFlush();
            company.DeleteAndFlush();
        }
Example #13
0
		protected void CreateScope()
		{
			scope = new SessionScope();
		}
		/// <summary>
		/// Executes the basic flow which is
		/// <list type="number">
		/// 		<item><description>Resolve the <see cref="ActiveRecordModel"/></description></item>
		/// 		<item><description>Resolve the layout (if not is associated with the controller, defaults to "scaffold")</description></item>
		/// 		<item><description>Invokes <see cref="PerformActionProcess"/> which should perform the correct process for this action</description></item>
		/// 		<item><description>Resolves the template name that the developer might provide by using <see cref="ComputeTemplateName"/></description></item>
		/// 		<item><description>If the template exists, renders it. Otherwise invokes <see cref="RenderStandardHtml"/></description></item>
		/// 	</list>
		/// </summary>
		/// <param name="engineContext">The engine context.</param>
		/// <param name="controller">The controller.</param>
		/// <param name="controllerContext">The controller context.</param>
		public object Execute(IEngineContext engineContext, IController controller, IControllerContext controllerContext)
		{
			// Cancel any rendering
			controllerContext.SelectedViewName = null;

			// We make sure the code is always surrounded by a SessionScope.
			// If none is found, we create one

			SessionScope scope = null;

			if (SessionScope.Current == null)
			{
				scope = new SessionScope(FlushAction.Never);
			}

			try
			{
				model = GetARModel();

				PerformActionProcess(engineContext, controller, controllerContext);

				var templateName = ComputeTemplateName(controllerContext);

				if (engineContext.Services.ViewEngineManager.HasTemplate(templateName))
				{
					controllerContext.SelectedViewName = templateName;
				}
				else
				{
					controllerContext.SelectedViewName = null;
					RenderStandardHtml(engineContext, controller, controllerContext);
				}
			}
			finally
			{
				if (scope != null)
				{
					scope.Dispose();
				}
			}

			return null;
		}
		/// <summary>
		/// Executes the basic flow which is
		/// <list type="number">
		/// <item><description>Resolve the <see cref="ActiveRecordModel"/></description></item>
		/// <item><description>Resolve the layout (if not is associated with the controller, defaults to "scaffold")</description></item>
		/// <item><description>Invokes <see cref="PerformActionProcess"/> which should perform the correct process for this action</description></item>
		/// <item><description>Resolves the template name that the developer might provide by using <see cref="ComputeTemplateName"/></description></item>
		/// <item><description>If the template exists, renders it. Otherwise invokes <see cref="RenderStandardHtml"/></description></item>
		/// </list>
		/// </summary>
		/// <param name="controller"></param>
		public void Execute(Controller controller)
		{
			// We make sure the code is always surrounded by a SessionScope.
			// If none is found, we create one
			
			SessionScope scope = null;
			
			if (SessionScope.Current == null)
			{
				scope = new SessionScope(FlushAction.Never);
			}

			try
			{
				model = GetARModel();

				PerformActionProcess(controller);

				String templateName = ComputeTemplateName(controller);

				if (controller.HasTemplate(templateName))
				{
					controller.RenderSharedView(templateName);
				}
				else
				{
					RenderStandardHtml(controller);
				}
			}
			finally
			{
				if (scope != null)
				{
					scope.Dispose();
				}
			}
		}
Example #16
0
 public static void CreateScope()
 {
     Scope = new SessionScope();
     TransactionScope = new TransactionScope(OnDispose.Commit);
 }
		/// <summary>
		/// Libera um <see cref="ISessionScope"/> do <c>ActiveRecord</c>.
		/// ร‰ chamado toda vez que uma requisiรงรฃo รฉ finalizada, no evento
		/// <see cref="HttpApplication.EndRequest"/>.
		/// </summary>
		protected virtual void DisposeActiveRecordSessionScope(SessionScope scope)
		{
			scope.Dispose();
		}
 public IUnitOfWorkImplementor Create(IDbConnection maybeUserProvidedConnection, IUnitOfWorkImplementor previous)
 {
     InitializeIfNecessary();
     ISessionScope scope;
     if (maybeUserProvidedConnection == null)
         scope = new SessionScope(FlushAction.Never);
     else
         scope = new DifferentDatabaseScope(maybeUserProvidedConnection);
     return new ActiveRecordUnitOfWorkAdapter(scope, previous);
 }
Example #19
0
 protected override void OnPreInit(EventArgs e)
 {
     _session = new SessionScope();
     base.OnPreInit(e);
 }
 public virtual void Setup()
 {
     ActiveRecordStarter.ResetInitializationFlag();
     ActiveRecordStarter.Initialize(GetConfigSource());
     RegisterTypes();
     ActiveRecordStarter.CreateSchema();
     Scope = new SessionScope();
 }
Example #21
0
        public ActionResult UploadPhoto(int id, HttpPostedFileBase file)
        {
            var path = string.Format ("~/Photos/{0:000000}", id);
            var filename = string.Format ("{0}/{1}.jpg", path, Guid.NewGuid ());

            if (file == null || !file.ContentType.StartsWith ("image")) {
                Product item;
                ModelState.AddModelError ("", "Archivo invรกlido, no es una imagen.");
                using (var session = new SessionScope()) {
                    item = Product.TryFind (id);
                    item.Photos.ToList ();
                }
                return View ("Details", item);
            }

            Photo photo = new Photo {
                Product = Product.TryFind (id),
                Path = filename
            };

            SavePhotoAsJpeg (photo.Path, file);
            photo.Create ();

            return RedirectToAction ("Details", new { id = id });
        }
        public void TwoSessionsOneScope()
        {
            using (var scope1 = new SessionScope())
            using (var scope2 = new SessionScope()) {
                var session1 = scope1.OpenSession<Blog>();
                var session2 = scope2.OpenSession<Blog>();
                Assert.IsNotNull( session1 );
                Assert.IsNotNull( session2 );
                Assert.IsTrue( session1 == session2 ); // will use parent scope's sessions
            }

            using (var scope = new SessionScope()) {
                var session1 = scope.OpenSession<Blog>();
                var session2 = scope.OpenSession<Blog>();
                Assert.IsNotNull( session1 );
                Assert.IsNotNull( session2 );
                Assert.IsTrue( session1 == session2 );
            }
        }
        public void SessionScopeFlushModeNever()
        {
            using (new SessionScope()) {
                Post.DeleteAll();
                Blog.DeleteAll();
            }

            using(var scope = new SessionScope(FlushAction.Never))
            {
                var blog = new Blog {Author = "hammett", Name = "some name"};

                //This gets flushed automatically because of the identity field
                blog.Save();

                var blogs = Blog.FindAll().ToArray();
                Assert.AreEqual(1, blogs.Length);

                //This change won't be saved to the db
                blog.Author = "A New Author";
                blog.Save(false);

                //The change should not be in the db
                blogs = Blog.FindAllByProperty("Author", "A New Author").ToArray();
                Assert.AreEqual(0, blogs.Length);

                scope.Flush();

                //The change should now be in the db
                blogs = Blog.FindAllByProperty("Author", "A New Author").ToArray();
                Assert.AreEqual(1, blogs.Length);

                //This change will be save to the db
                blog.Name = "A New Name";
                blog.Save();

                //The change should now be in the db
                blogs = Blog.FindAllByProperty("Name", "A New Name").ToArray();
                Assert.AreEqual(1, blogs.Length);

                //This deletion should not get to the db
                blog.Delete(false);

                blogs = Blog.FindAll().ToArray();
                Assert.AreEqual(1, blogs.Length);

                scope.Flush();

                //The deletion should now be in the db
                blogs = Blog.FindAll().ToArray();
                Assert.AreEqual(0, blogs.Length);
            }
        }
 public void UsingSessionScopeUsingExplicitFlush()
 {
     using (var scope = new SessionScope())
     {
         new SSAFEntity("example").Save();
         scope.Flush();
         Assert.AreEqual(1, SSAFEntity.FindAll().Count());
     }
     using (new SessionScope())
         Assert.AreEqual(1, SSAFEntity.FindAll().Count());
 }
        public ActionResult Index(Subscriber input)
        {
            if (!IsValidEmailAddress (input.Email)) {
                ModelState.AddModelError ("Email", "No es una direcciรณn de email vรกlida.");
            }

            if (ModelState.IsValid) {
                Subscriber item = Subscriber.TryFind (input.Email);

                if (item == null) {
                    using (var session = new SessionScope()) {
                        input.IsActive = true;
                        input.CreateAndFlush ();
                    }
                } else {
                    using (var session = new SessionScope()) {
                        item.IsActive = true;
                        item.UpdateAndFlush ();
                    }
                }

                return PartialView ("_Success");
            }

            return PartialView ("_Form", input);
        }
Example #26
0
		/// <summary>
		/// Saves the Character to the DB instantly.
		/// Blocking call.
		/// See: <see cref="SaveLater()"/>.
		/// When calling this method directly, make sure to set m_saving = true
		/// </summary>
		internal protected bool SaveNow()
		{
			if (!m_record.CanSave)
			{
				return false;
			}

			if (DebugUtil.Dumps)
			{
				var writer = DebugUtil.GetTextWriter(m_client.Account);
				writer.WriteLine("Saving {0}...", Name);
			}

			try
			{
				if (m_record == null)
				{
					throw new InvalidOperationException("Cannot save Character while not in world.");
				}

				UpdatePlayedTime();

				// always make sure that the values saved to DB, will not be influenced by buffs etc
				m_record.Race = Race;
				m_record.Class = Class;
				m_record.Gender = Gender;
				m_record.Skin = Skin;
				m_record.Face = Facial;
				m_record.HairStyle = HairStyle;
				m_record.HairColor = HairColor;
				m_record.FacialHair = FacialHair;
				m_record.Outfit = Outfit;
				m_record.Name = Name;
				m_record.Level = Level;
				if (m_Map != null)
				{
					// only save position information if we are in world
					m_record.PositionX = Position.X;
					m_record.PositionY = Position.Y;
					m_record.PositionZ = Position.Z;
					m_record.Orientation = Orientation;
					m_record.MapId = m_Map.Id;
					m_record.InstanceId = m_Map.InstanceId;
					m_record.Zone = ZoneId;
				}
				m_record.DisplayId = DisplayId;
				m_record.BindX = m_bindLocation.Position.X;
				m_record.BindY = m_bindLocation.Position.Y;
				m_record.BindZ = m_bindLocation.Position.Z;
				m_record.BindMap = m_bindLocation.MapId;
				m_record.BindZone = m_bindLocation.ZoneId;

				m_record.Health = Health;
				m_record.BaseHealth = BaseHealth;
				m_record.Power = Power;
				m_record.BasePower = BasePower;
				m_record.Money = Money;
				m_record.WatchedFaction = WatchedFaction;
				m_record.BaseStrength = GetBaseStatValue(StatType.Strength);
				m_record.BaseStamina = GetBaseStatValue(StatType.Stamina);
				m_record.BaseSpirit = GetBaseStatValue(StatType.Spirit);
				m_record.BaseIntellect = GetBaseStatValue(StatType.Intellect);
				m_record.BaseAgility = GetBaseStatValue(StatType.Agility);
				m_record.Xp = Experience;
				m_record.RestXp = RestXp;

				// Honor and Arena
				m_record.KillsTotal = KillsTotal;
				m_record.HonorToday = HonorToday;
				m_record.HonorYesterday = HonorYesterday;
				m_record.LifetimeHonorableKills = LifetimeHonorableKills;
				m_record.HonorPoints = HonorPoints;
				m_record.ArenaPoints = ArenaPoints;


				// Finished quests
				if (m_questLog.FinishedQuests.Count > 0)
				{
					m_record.FinishedQuests = new uint[m_questLog.FinishedQuests.Count];
					m_questLog.FinishedQuests.CopyTo(m_record.FinishedQuests);
				}

				// Taxis
				if (LatestTaxiPathNode != null && LatestTaxiPathNode.Next != null)
				{
					m_record.NextTaxiVertexId = (int)LatestTaxiPathNode.Next.Value.Id;
				}
				else
				{
					m_record.NextTaxiVertexId = 0;
				}

				// cooldowns & runes
				PlayerSpells.OnSave();

				// taxi mask
				m_record.TaxiMask = m_taxiNodeMask.Mask;

				if (m_record.Level > 1 &&
					m_record.Level > Account.HighestCharLevel)
				{
					// tell auth server about the new highest level
					Account.HighestCharLevel = m_record.Level;
				}
			}
			catch (Exception e)
			{
				OnSaveFailed(e);
				return false;
			}

			try
			{
				using (var saveScope = new SessionScope(FlushAction.Never))
				{
					// Interface settings
					Account.AccountData.Save();

					// Items
					var items = new List<ItemRecord>();
					m_inventory.SaveAll(items);
					m_record.UpdateItems(items);

					// Skills
					foreach (var skill in m_skills)
					{
						skill.Save();
					}

					// Pets
					SaveEntourage();

					// Quests
					m_questLog.SaveQuests();

					// Specs
					foreach (var spec in SpecProfiles)
					{
						if (spec.IsDirty)
						{
							spec.Save();
						}
					}

					// Achievements
					m_achievements.SaveNow();

					// Auras
					m_auras.SaveAurasNow();

					// General Character data
					m_record.Save();

					saveScope.Flush();
				}
				m_record.LastSaveTime = DateTime.Now;

				if (DebugUtil.Dumps)
				{
					var writer = DebugUtil.GetTextWriter(m_client.Account);
					writer.WriteLine("Saved {0} (Map: {1}).", Name, m_record.MapId);
				}

				return true;
			}
			catch (Exception ex)
			{
				OnSaveFailed(ex);
				return false;
			}
			finally
			{
			}
		}
Example #27
0
 public static void InitializeCasteActiveRecordFramework()
 {
     var config = ActiveRecordSectionHandler.Instance;
     ActiveRecordStarter.Initialize(config, typeof(Baseword), typeof(Language), typeof(Wordtype), typeof(Flexion), typeof(GramFunction), typeof(Connection), typeof(Translation), typeof(Specialty), typeof(LinguisticFeature));
     _sessionScope = new SessionScope();
 }
Example #28
0
 public virtual void FixtureSetup()
 {
     ActiveRecordStarter.Initialize(Assembly.Load("StoryVerse.Core"),
         ActiveRecordSectionHandler.Instance);
     scope = new SessionScope();
 }
		protected void CreateScope()
		{
			scope = new SessionScope(FlushAction.Never);
		}
Example #30
0
        /// <summary>
        /// Mains the specified args.
        /// </summary>
        /// <param name="args">The args.</param>
        public static void Main(string[] args)
        {
            string option;
            if (args.Length == 0)
            {
                Console.WriteLine("Please specify a valid option...");
                Console.WriteLine("Valid parameter values are: -update|-bootstrap|-tests [-show_workflow]");
                option = Console.ReadLine();
            }
            else
            {
                option = args[0];
            }

            Console.WriteLine("Initializing framework...");
            var source = new XmlConfigurationSource(@"SchemaConfig.xml");
            RedCelularActiveRecordBase<Product>.Initialize(source);
            __sessionScope = new SessionScope();
            switch (option)
            {
                case "-update":
                    UpdateSchema();
                    break;
                case "-bootstrap":
                    BootstrapDatabase();
                    break;
                case "-fill": // The database needs to be already created (bootstrap)
                    FillDatabase();
                    break;
                case "-tests":
                    PrepareTestsDatabase();
                    break;
                default:
                    Console.WriteLine("Valid parameter values are: -update|-bootstrap|-tests [-show_workflow]");
                    Console.ReadKey();
                    return;
            }

            __sessionScope.Flush();
        }