public void AllMainRowsInsertTest() { using (var db = new ASP_DBEntities()) using (var trans = db.Database.BeginTransaction(IsolationLevel.ReadUncommitted)) { try { // Local SetUp var before = AllMainRows <TestClass>(db).Count(); var obj = new TestClass { "Hello", "World" }; var session1 = SaveMain(db, obj, null); var session2 = SaveMain(db, obj, null); // Method under test var all = AllMainRows <TestClass>(db); Assert.That(all.Count(), Is.EqualTo(before + 2)); Main found1 = null; Main found2 = null; foreach (var main in all) { if (main.session == session1) { found1 = main; } else if (main.session == session2) { found2 = main; } } Assert.Multiple(() => { Assert.That(found1, Is.Not.Null); Assert.That(found2, Is.Not.Null); Assert.That(found1.GetInstance <TestClass>(), Is.EquivalentTo(obj)); Assert.That(found2.GetInstance <TestClass>(), Is.EquivalentTo(obj)); // serialize & deserialize creates a copy of the object Assert.That(found1.GetInstance <TestClass>(), Is.Not.SameAs(found2.GetInstance <TestClass>())); }); } finally { trans.Rollback(); // trans.Commit(); } } }
public void VerifyFibonacciSums() { CalculatorController inst; using (var db = new ASP_DBEntities()) { var bytes = db.LoadMain(this.config.GetValue <Guid>("asp.Controllers.FibonacciTest")); inst = new CalculatorController(); inst.Deserialize(bytes); inst.Fsm.Owner = inst; // As in ISmcControl.LoadMain<M, F, S>(), see SMC Manual Section 9 } Assert.That(inst.Stack.Count, Is.GreaterThanOrEqualTo(3)); // non-empty sequence Assert.That(inst.State, Is.EqualTo(CalculatorContext.Map1.Calculate)); // Assert the sums backwards on the model objects instead of the GUI while (inst.Stack.Count >= 3) { var initialStackCount = inst.Stack.Count; // Get the head of the sequence to check var sum = inst.Stack.ElementAt(0); var summand1 = inst.Stack.ElementAt(1); var summand2 = inst.Stack.ElementAt(2); // Check the correctness of the Fibonacci sequence in the calculator GUI // Delete the current sum and recalculate it from the sequence inst.Fsm.Clr(inst.Stack); // this.Click("calculate.clrButton"); inst.Fsm.Add(inst.Stack); //this.Click("calculate.addButton"); Assert.That(inst.Stack.ElementAt(0), Is.EqualTo(sum)); // Delete the calculated check sum inst.Fsm.Clr(inst.Stack); // this.Click("calculate.clrButton"); // Put the original summands onto the stack again inst.Fsm.Enter(""); // this.Click("footer.enterButton"); inst.Fsm.Enter(summand2); // this.Write("enter.operandTextBox", summand2); // this.Click("footer.enterButton"); inst.Fsm.Enter(""); // this.Click("footer.enterButton"); inst.Fsm.Enter(summand1); // this.Write("enter.operandTextBox", summand1); // this.Click("footer.enterButton"); // Check that the loop will terminate by continuing with N-1 elements Assert.That(inst.Stack.Count, Is.EqualTo(initialStackCount - 1)); } }
public void InsertSQLExecutabilityTest() { var bytes = new byte[] { 1, 2, 3 }; using (var db = new ASP_DBEntities()) using (var trans = db.Database.BeginTransaction()) { try { var sql = db.InsertSQL(typeof(TestClass), bytes); db.Database.ExecuteSqlRaw(sql); // really just executability without exception } finally { trans.Rollback(); } } }
/// <summary> /// Delete the Main row with the given session guid with a custom "Del" command /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void gridView_RowCommand(object sender, GridViewCommandEventArgs e) { switch (e.CommandName) { case "Del": var session = Guid.Parse(e.CommandArgument.ToString()); using (var db = new ASP_DBEntities()) { var sql = @" DELETE FROM Main WHERE session = @session "; var param = new SqlParameter("session", session); db.Database.ExecuteSqlCommand(sql, param); } break; default: throw new NotImplementedException(String.Format("e.CommandName='{0}'", e.CommandName)); } }
public void LoadSaveMainTest() { var bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7 }; using (var db = new ASP_DBEntities()) using (var trans = db.Database.BeginTransaction()) { try { // Local SetUp var session = db.SaveMain(typeof(TestClass), bytes, null); // Method under test var copy = db.LoadMain(session); Assert.That(copy, Is.EquivalentTo(bytes)); } finally { trans.Rollback(); } } }
public void LoadSaveMainTest() { using (var db = new ASP_DBEntities()) using (var trans = db.Database.BeginTransaction(IsolationLevel.ReadUncommitted)) { try { // Local SetUp var obj = new TestClass { "Hello", "World" }; var session = SaveMain(db, obj, null); // Method under test var copy = LoadMain <TestClass>(db, session); Assert.That(copy, Is.EquivalentTo(obj)); } finally { trans.Rollback(); } } }
public void InsertSQLExecutabilityTest() { var obj = new TestClass { "Hello", "World" }; this.SetInstance(obj); var sql = this.InsertSQL(); using (var db = new ASP_DBEntities()) using (var trans = db.Database.BeginTransaction(IsolationLevel.ReadUncommitted)) { try { var session = db.Database.SqlQuery <Guid>(sql).FirstOrDefault(); var copy = LoadMain <TestClass>(db, session); Assert.That(copy, Is.EquivalentTo(obj)); } finally { trans.Rollback(); } } }
public void SaveUpdateTest() { const int DB_ROUNDTRIP_MILLISECONDS = 500; using (var db = new ASP_DBEntities()) using (var trans = db.Database.BeginTransaction(IsolationLevel.ReadUncommitted)) { try { var main = new Main(); db.Main.Add(main); // add incomplete object, possible unlike with Strongly Typed Datasets main.main = new byte[3] { 1, 2, 3 }; // INSERT: read back inserted and computed values db.SaveChanges(); var insertedAt = DateTime.Now; Assert.Multiple(() => // direct assertions on the model object { Assert.That(main.main, Is.EqualTo(new byte[3] { 1, 2, 3 })); Assert.That(main.created, Is.EqualTo(main.changed)); // exact time from the db Assert.That(main.changed, Is.EqualTo(insertedAt).Within(DB_ROUNDTRIP_MILLISECONDS).Milliseconds); // db rounttrip time }); // UDPATE: read back updated and computed values Thread.Sleep(500); // greater than db roundtrip time main.main = new byte[3] { 4, 5, 6 }; db.SaveChanges(); var createdAt = main.created; // exact time from the db var changedAt = DateTime.Now; Assert.Multiple(() => // direct assertions on the model object { Assert.That(main.main, Is.EqualTo(new byte[3] { 4, 5, 6 })); Assert.That(main.created, Is.EqualTo(createdAt)); Assert.That(main.changed, Is.GreaterThan(main.created)); Assert.That(main.changed, Is.EqualTo(changedAt).Within(DB_ROUNDTRIP_MILLISECONDS).Milliseconds); }); // DELETE: delete with initially detached object var session = main.session; var detached = new Main { session = session }; db.Main.Attach(main); // must exist, otherwise SaveChanges() throws an exception db.Main.Remove(main); db.SaveChanges(); this.TestReadInexistent(db, session); } finally { trans.Rollback(); } } }
/// <summary> /// Custom Controller factory method returning a serialized object if available. /// </summary> /// <param name="actionContext"></param> /// <returns></returns> public object Create(ControllerContext actionContext) { object controller = null; var controllerTypeInfo = actionContext.ActionDescriptor.ControllerTypeInfo; var controllerType = controllerTypeInfo.AsType(); var storageID = StorageImplementation.GetStorageID(controllerTypeInfo.Name); var sessionStorageID = StorageImplementation.GetSessionStorageID(controllerTypeInfo.Name); var storage = StorageImplementation.GetStorage(this.Configuration, this.HttpContext, sessionStorageID); StorageImplementation.ClearIfRequested(this.HttpContext, storage, storageID); Guid sessionOverride; Guid session; byte[] bytes; Func <byte[], byte[]> filter = null; // ---------- Direct GET request ?session= from the Database ---------- if (this.HttpContext.Request.Method == WebRequestMethods.Http.Get && Guid.TryParse(this.HttpContext.Request.Query["session"], out sessionOverride)) { using (var db = new ASP_DBEntities()) { (bytes, filter) = StorageImplementation.DatabaseBytes(Configuration, HttpContext, storageID, sessionOverride); controller = DeserializeController(actionContext, controllerTypeInfo, controllerType, bytes, filter); } } else { // ---------- Load from ViewState ---------- if (storage == Storage.ViewState && this.HttpContext.Request.Method == WebRequestMethods.Http.Post && this.HttpContext.Request.Form.ContainsKey(storageID)) { // input type=hidden from <input viewstate="@ViewBag.ViewState" /> var controllerString = this.HttpContext.Request.Form[storageID]; if (!String.IsNullOrEmpty(controllerString)) { (bytes, filter) = StorageImplementation.ViewStateBytes(this.Configuration, controllerString); controller = DeserializeController(actionContext, controllerTypeInfo, controllerType, bytes, filter); } } // ---------- Load from Session ---------- else if (storage == Storage.Session && this.HttpContext.Session.TryGetValue(storageID, out bytes)) { controller = DeserializeController(actionContext, controllerTypeInfo, controllerType, bytes); } // ---------- Load from Database ---------- else if (storage == Storage.Database && Guid.TryParse(this.HttpContext.Request.Cookies[storageID].FromCookieString()["session"], out session)) { (bytes, filter) = StorageImplementation.DatabaseBytes(Configuration, HttpContext, storageID, session); controller = DeserializeController(actionContext, controllerTypeInfo, controllerType, bytes, filter); ((IPersistentController)controller).Session = session; } // ---------- Load from X-ViewState Header ---------- else if (storage == Storage.Header && this.HttpContext.Request.Headers.ContainsKey(StorageImplementation.HeaderName)) { // input type=hidden from <input viewstate="@ViewBag.ViewState" /> var controllerString = this.HttpContext.Request.Headers[StorageImplementation.HeaderName]; if (!String.IsNullOrEmpty(controllerString)) { (bytes, filter) = StorageImplementation.ViewStateBytes(this.Configuration, controllerString); controller = DeserializeController(actionContext, controllerTypeInfo, controllerType, bytes, filter); } } if (controller == null) { // ASP.NET Core implementation, no persistence, just return the new controller controller = actionContext.HttpContext.RequestServices.GetService(controllerType); } } return(controller); }
public void TestReadInexistent(ASP_DBEntities db, Guid session) { var read = db.LoadMain(session); Assert.That(read, Is.Null); }
/// <summary> /// Hook to clear the storage for that control with ?clear=true /// ViewState is reset anyway on GET requests, therefore NOP in that casefa /// GET-arguments: /// clear=[true|false] triggers clearing the storage /// endresponse=[true|false] whether the page at the given URL /// storage=[Session|Database] clears the selected storage type regardless of config /// </summary> /// <typeparam name="M"></typeparam> /// <param name="controlStorage"></param> /// <returns></returns> internal static void ClearIfRequested <M>(this IStorageControl <M> controlStorage) where M : new() { if (!controlStorage.IsPostBack) { bool clear = false; bool.TryParse(controlStorage.Request.QueryString["clear"], out clear); if (clear) { Storage storage; Enum.TryParse <Storage>(controlStorage.Request.QueryString["storage"], true, out storage); if (storage == Storage.ViewState) // no meaningful override given { storage = controlStorage.GetStorage(); } bool endresponse = false; bool.TryParse(controlStorage.Request.QueryString["endresponse"], out endresponse); switch (storage) { case Storage.ViewState: break; case Storage.Session: controlStorage.Session.Remove(controlStorage.StorageID()); break; case Storage.Database: // delete from the database and expire the cookie var cookie = controlStorage.Request.Cookies[controlStorage.StorageID()]; if (cookie != null) { Guid session; Guid.TryParse(controlStorage.Request.Cookies[controlStorage.StorageID()]["session"], out session); using (var db = new ASP_DBEntities()) { var sql = @" DELETE FROM Main WHERE session = @session "; var param = new SqlParameter("session", session); db.Database.ExecuteSqlCommand(sql, param); } controlStorage.Request.Cookies[controlStorage.StorageID()].Expires = DateTime.Now.AddDays(-1); } break; default: throw new NotImplementedException(String.Format( "Storage {0}", storage)); } if (endresponse) { controlStorage.Response.Clear(); controlStorage.Response.End(); } } } }