public void adds_all_waiting_submissions_to_the_queue() { const int submitted = 11; var factory = new TestDatabaseConfiguration().DatabaseConfiguration.BuildSessionFactory(); using (var scope = new SessionScope(factory)) { var contest = new Contest(); contest.Beginning = contest.Ending = new DateTime(1990, 7, 7); var problem = new Problem { Contest = contest }; scope.Session.Save(contest); scope.Session.Save(problem); for (int i = 0; i < submitted; i++) { scope.Session.Save(ConstructSubmission(i, problem)); } } using (var scope = new SessionScope(factory)) { var builder = new SubmissionQueueBuilder(scope.Session); var queue = new TestQueue(); builder.FillQueue(queue); Assert.Equal(submitted, queue.Count); } }
public void unpack_tests_from_real_zip() { var factory = new TestDatabaseConfiguration().DatabaseConfiguration.BuildSessionFactory(); byte[] zip = File.ReadAllBytes(@".\..\..\TestData\a_plus_b.zip"); var problem = new Problem(); using (var scope = new SessionScope(factory)) scope.Session.Save(problem); Assert.Equal(0, problem.TestInfo.Tests.Count); using (var scope = new SessionScope(factory)) { var consumer = new UnpackTestInfoConsumer(new TestsZipper("in", "out"), scope.Session); consumer.Consume(new UnpackTestInfo { ProblemId = problem.Id, ZipArchive = zip }); } using (var scope = new SessionScope(factory)) { var newProblem = scope.Session.Get <Problem>(problem.Id); Assert.Equal(5, newProblem.TestInfo.Tests.Count); } }
protected override void PerformActionProcess(Controller controller) { ARDataBinder binder = new ARDataBinder(); object instance = binder.BindObject(Model.Type, "", controller.Params); SessionScope scope = new SessionScope(); try { CommonOperationUtils.SaveInstance(instance, controller, errors, prop2Validation); scope.Dispose(); controller.Redirect(controller.AreaName, controller.Name, "list" + Model.Type.Name); } catch (Exception ex) { errors.Add("Could not save " + Model.Type.Name + ". " + ex.Message); scope.Dispose(true); } if (errors.Count != 0) { controller.Context.Flash["errors"] = errors; controller.Redirect(controller.AreaName, controller.Name, "new" + Model.Type.Name); } }
public DatabaseVersion Upgrade(string oldDbFile) { //ISession session=NHibernateSessionManager.SessionFactory.OpenSession(); using (var scope = new SessionScope()) { //var transaction = session.BeginTransaction(); try { Log.WriteInfo("DatabaseUpdater11To20. OldFile={0}", oldDbFile); if (File.Exists(oldDbFile)) { Log.WriteInfo("File exists. Start converting db from 1.1.0.1 to 2.0.0.0"); importProfiles(oldDbFile); } Log.WriteInfo("Set database version to 2.0.0.0"); DatabaseVersion version = new DatabaseVersion("2.0.0.0"); //session.SaveOrUpdate(version); version.Create(); //transaction.Commit(); Log.WriteInfo("DatabaseUpdater11To20. Everything is ok"); return(version); } catch (Exception) { //transaction.Rollback(); throw; } finally { //session.Close(); } } }
public DifferentDatabaseScope(IDbConnection connection) : base(SessionScopeType.Custom) { if (connection == null) { throw new ArgumentNullException("connection"); } this.connection = connection; ISessionScope parentScope = ScopeUtil.FindPreviousScope(this, true); if (parentScope != null) { if (parentScope.ScopeType == SessionScopeType.Simple) { parentSimpleScope = (SessionScope)parentScope; } else if (parentScope.ScopeType == SessionScopeType.Transactional) { parentTransactionScope = (TransactionScope)parentScope; parentTransactionScope.OnTransactionCompleted += new EventHandler(OnTransactionCompleted); } else { // Not supported? } } }
public void reading_is_persisted_correctly() { using (var scope = new SessionScope(factory)) { var readings = new MessagesForContestant { Contest = contest, Contestant = isenbaev } .List(scope.Session); Assert.True(readings.All(x => !x.IsRead)); var answerReading = readings.Single(x => x.Message is Answer); Assert.False(answerReading.IsRead); answerReading.IsRead = true; scope.Session.Save(answerReading); } using (var scope = new SessionScope(factory)) { var readings = new MessagesForContestant { Contest = contest, Contestant = isenbaev } .List(scope.Session); var answerReading = readings.Single(x => x.Message is Answer); Assert.True(answerReading.IsRead); } }
/// <summary> /// Initializes a new instance of the <see cref="DifferentDatabaseScope"/> class. /// </summary> /// <param name="connection">The connection.</param> /// <param name="flushAction">The flush action.</param> public DifferentDatabaseScope(IDbConnection connection, FlushAction flushAction) : base(flushAction, SessionScopeType.Custom) { if (connection == null) throw new ArgumentNullException("connection"); this.connection = connection; ISessionScope parentScope = ScopeUtil.FindPreviousScope(this, true); if (parentScope != null) { if (parentScope.ScopeType == SessionScopeType.Simple) { parentSimpleScope = (SessionScope) parentScope; } else if (parentScope.ScopeType == SessionScopeType.Transactional) { parentTransactionScope = (TransactionScope) parentScope; parentTransactionScope.OnTransactionCompleted += OnTransactionCompleted; } else { // Not supported? } } }
public void enqueues_submission_to_the_queue() { var queue = new TestQueue(); var submission = new Submission { Source = new ProgramSource { Code = "test" }, SubmittedAt = new DateTime(1990, 7, 7), Problem = new Problem { TestInfo = new TestInfo(), Contest = new Contest { Beginning = new DateTime(1990, 7, 7), Ending = new DateTime(1992, 7, 7) } } }; var factory = new TestDatabaseConfiguration().DatabaseConfiguration.BuildSessionFactory(); using (var scope = new SessionScope(factory)) scope.Session.Save(submission); using (var scope = new SessionScope(factory)) { var consumer = new JudgeSubmissionConsumer(queue, scope.Session); consumer.Consume(new JudgeSubmission { SubmissionId = submission.Id }); } Assert.Equal(1, queue.Count); Assert.Equal(submission.Source.Code, ((SubmissionInfo)queue.Dequeue().WorkItem).Source.Code); }
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); } }
/// <summary> /// starts a new AR sessionscope /// </summary> private void BeginARSession() { try { now = DateTime.Now; string logMessage; //if there is one, flush it if (RoSession.Instance["nh.sessionscope"] != null) { SessionScope scope = RoSession.Instance["nh.sessionscope"] as SessionScope; if (scope != null) { scope.Flush(); } logMessage = " maintained opened"; //used on redirects } //create one if there is none else { RoSession.Instance["nh.sessionscope"] = new SessionScope(FlushAction.Auto); logMessage = " opened"; } logMessage = "nh.sessionscope " + RoSession.Instance["nh.sessionscope"].GetHashCode() + logMessage; RoLog.Instance.WriteToLog(""); Console.WriteLine(""); RoLog.Instance.WriteToLog(logMessage); Console.WriteLine(logMessage); } catch (ActiveRecordException ex) { RoLog.Instance.WriteToLog("Problems initializing the session:" + ex.Message + "/r/n" + ex, TracedAttribute.ERROR); } }
public void ConfigurationIsCustomizable() { using (var scope = new SessionScope()) { Blog.FindAll(); Assert.AreEqual(FlushMode.Commit, scope.OpenSession<Blog>().FlushMode); } }
public void ConfigurationIsCustomizable() { using (var scope = new SessionScope()) { Blog.FindAll(); Assert.AreEqual(FlushMode.Commit, scope.OpenSession <Blog>().FlushMode); } }
public void should_not_commit_nested_unit_of_work() { //act UnitOfWork.Do(uow => UnitOfWork.Do(nested => nested.Commit())); //assert A.CallTo(() => SessionScope.Commit()).MustHaveHappened(Repeated.Exactly.Once); }
public void should_not_rollback_nested_unit_of_work() { //act UnitOfWork.Do(uow => UnitOfWork.Do(nested => nested.Rollback())); //assert A.CallTo(() => SessionScope.Rollback()).MustNotHaveHappened(); }
public ChatSession(SecondaryUser attemptingUser, long chatIdentifier, long userIdentifier, SessionScope scope) { ChatIdentifier = chatIdentifier; UserIdentifier = userIdentifier; AttemptingUser = attemptingUser; Messages = new List <SessionMessage>(); Scope = scope; LastUpdateAt = DateTime.Now; }
/// <summary> /// Called when the request ends, dipose of the scope /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private static void OnEndRequest(object sender, EventArgs e) { SessionScope session = (SessionScope)HttpContext.Current.Items[SessionKey]; if (session != null) { session.Dispose(); } }
public void should_commit_and_dispose() { //act UnitOfWork.Do(uow => { }); //assert A.CallTo(() => SessionScope.Commit()).MustHaveHappened(Repeated.Exactly.Once); A.CallTo(() => SessionScope.Dispose()).MustHaveHappened(Repeated.Exactly.Once); }
/// <summary> /// Commit database transaction explicitly(not necessarily to use in standard configuration, because transaction will be committed anyway in the end of the "Do" block). /// </summary> public void Commit() { Perform(() => { if (Settings.EnableCommit) { SessionScope.Commit(); } }); }
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 T Get <T>(string key, SessionScope scope) { string sessionKey = key; if (scope == SessionScope.Page) { sessionKey = _page.ScreenId + "|" + key; } return((T)_page.Session[sessionKey]); }
public void ClearItem(string key, SessionScope scope) { string sessionKey = key; if (scope == SessionScope.Page) { sessionKey = _page.ScreenId + "|" + key; } _page.Session.Remove(sessionKey); }
/// <summary> /// Perform the check that the property value is unqiue in the table /// </summary> /// <param name="instance"></param> /// <param name="fieldValue"></param> /// <returns><c>true</c> if the field is OK</returns> public override bool IsValid(object instance, object fieldValue) { Type instanceType = instance.GetType(); ActiveRecordModel model = ActiveRecordBase.GetModel(instance.GetType()); while (model != null) { if (model.PrimaryKey != null) { pkModel = model.PrimaryKey; } model = model.Parent; } if (pkModel == null) { throw new ValidationFailure("We couldn't find the primary key for " + instanceType.FullName + " so we can't ensure the uniqueness of any field. Validatior failed"); } IsUniqueValidator.fieldValue = fieldValue; SessionScope scope = null; FlushMode? originalMode = null; if (SessionScope.Current == null /*|| * SessionScope.Current.ScopeType != SessionScopeType.Transactional*/) { scope = new SessionScope(); } else { originalMode = ActiveRecordBase.holder.CreateSession(instanceType).FlushMode; ActiveRecordBase.holder.CreateSession(instanceType).FlushMode = FlushMode.Never; } try { return((bool)ActiveRecordMediator.Execute(instanceType, CheckUniqueness, instance)); } finally { if (scope != null) { scope.Dispose(); } if (originalMode != null) { ActiveRecordBase.holder.CreateSession(instanceType).FlushMode = originalMode ?? FlushMode.Commit; } } }
public bool Contains(string key, SessionScope scope) { string sessionKey = key; if (scope == SessionScope.Page) { sessionKey = _page.ScreenId + "|" + key; } return(_page.Session[sessionKey] != null); }
public void should_mark_as_deleted() { //act Repository.Delete(new TestEntity() { Id = 4, Field = "Super" }); //assert A.CallTo(() => SessionScope.MarkAsDeleted(A <TestEntity> .That.Matches(t => t.Id == 4 && t.Field == "Super"))).MustHaveHappened(); }
public void judge_should_view_all_messages() { using (var scope = new SessionScope(factory)) { var readings = new MessagesForJudge { Contest = contest, Judge = isenbaev } .List(scope.Session); Assert.Equal(6, readings.Count); } }
public void Set(string key, object data, SessionScope scope) { string sessionKey = key; if (scope == SessionScope.Page) { sessionKey = _page.ScreenId + "|" + key; } _page.Session[sessionKey] = data; }
public void should_not_commit() { //act UnitOfWork.Do(uow => { }, new UnitOfWorkSettings() { EnableCommit = false }); //assert A.CallTo(() => SessionScope.Commit()).MustNotHaveHappened(); }
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()); }
/// <summary> /// Perform the check that the property value is unqiue in the table /// </summary> /// <param name="instance"></param> /// <param name="fieldValue"></param> /// <returns><c>true</c> if the field is OK</returns> public override bool IsValid(object instance, object fieldValue) { Type instanceType = instance.GetType(); ActiveRecordModel model = ActiveRecordBase.GetModel(instance.GetType()); while(model != null) { if (model.PrimaryKey != null) { pkModel = model.PrimaryKey; } model = model.Parent; } if (pkModel == null) { throw new ValidationFailure("We couldn't find the primary key for " + instanceType.FullName + " so we can't ensure the uniqueness of any field. Validatior failed"); } IsUniqueValidator.fieldValue = fieldValue; SessionScope scope = null; FlushMode? originalMode = null; if (SessionScope.Current == null /*|| SessionScope.Current.ScopeType != SessionScopeType.Transactional*/) { scope = new SessionScope(); } else { originalMode = ActiveRecordBase.holder.CreateSession(instanceType).FlushMode; ActiveRecordBase.holder.CreateSession(instanceType).FlushMode = FlushMode.Never; } try { return (bool) ActiveRecordMediator.Execute(instanceType, CheckUniqueness, instance); } finally { if (scope != null) { scope.Dispose(); } if (originalMode != null) { ActiveRecordBase.holder.CreateSession(instanceType).FlushMode = originalMode ?? FlushMode.Commit; } } }
public void should_commit() { //act UnitOfWork.Do(uow => { }, new UnitOfWorkSettings() { RollbackOnDispose = false }); //assert A.CallTo(() => SessionScope.Rollback()).MustNotHaveHappened(); A.CallTo(() => SessionScope.Commit()).MustHaveHappened(); }
public void OperateTheOtherOne() { using (new SessionScope()) { var authors = AR.FindAll<Author>().ToArray(); Assert.AreEqual(0, authors.Length); CreateAuthor(); } using (var scope = new SessionScope()) { Assert.AreEqual(1, scope.Count<Author>()); } }
public void OperateOne() { using (new SessionScope()) { var blogs = Blog.FindAll().ToArray(); Assert.AreEqual(0, blogs.Length); CreateBlog(); } using (var scope = new SessionScope()) { Assert.AreEqual(1, scope.Count<Blog>()); } }
public void OperateTheOtherOne() { using (new SessionScope()) { var hands = Hand.FindAll().ToArray(); Assert.AreEqual(0, hands.Length); CreateHand(); } using (var scope = new SessionScope()) { Assert.AreEqual(1, scope.Count<Hand>()); } }
public void should_get_it_from_session_scope() { //arrange A.CallTo(() => SessionScope.AsQueryable <TestEntity>()).Returns(A.Dummy <IQueryable <TestEntity> >()); //act var result = Repository.AsQueryable(); //assert A.CallTo(() => SessionScope.AsQueryable <TestEntity>()).MustHaveHappened(Repeated.Exactly.Once); result.Should().NotBeNull(); }
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); } }); } }
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 override void OnActionExecuting(ActionExecutingContext context) { base.OnActionExecuting(context); if (context.ActionDescriptor == null) return; if (context.ActionDescriptor.FilterDescriptors == null) return; if (context.IsActionDefined<IgnoreSessionScopedAttribute>()) return; m_Callback = context.Controller as IDataScopedCallback; if (m_Callback == null) return; if (m_Callback.SessionScopeFactory == null) return; m_SessionScope = m_Callback.SessionScopeFactory.CreateScope(); m_Callback.AfterEnter(m_SessionScope); }
public void OperateBoth() { using (var scope = new SessionScope()) { var blogs = scope.FindAll<Blog>().ToArray(); var authors = scope.FindAll<Author>().ToArray(); Assert.AreEqual(0, blogs.Length); Assert.AreEqual(0, authors.Length); CreateBlog(); CreateAuthor(); } using (var scope = new SessionScope()) { Assert.AreEqual(1, scope.Count<Blog>()); Assert.AreEqual(1, scope.Count<Author>()); } }
public void DeleteWithQueryOverExtension() { using (var scope = new SessionScope()) { var blog = new Blog {Name = "hammett's blog", Author = "hamilton verissimo"}; blog.Save(); scope.DeleteAll<Blog>(b => b.Author == "hamilton verissimo"); var blogs = Blog.FindAll(); Assert.IsNotNull(blogs); Assert.AreEqual(10, blogs.Count()); } }
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 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()); } }