public void IOptimizedPersistableField(bool useServerSession) { using (SessionBase session = useServerSession ? (SessionBase) new ServerClientSession(systemDir) : (SessionBase) new SessionNoServer(systemDir)) { session.BeginUpdate(); for (int i = 0; i < 10; i++) { var dict = new PersistableDynamicDictionary(); session.Persist(dict); } session.Commit(); } using (SessionBase session = useServerSession ? (SessionBase) new ServerClientSession(systemDir) : (SessionBase) new SessionNoServer(systemDir)) { session.BeginRead(); session.TraceIndexUsage = true; DateTime now = DateTime.UtcNow; var q = from dict in session.Index <PersistableDynamicDictionary>("m_creationTime") where dict.CreationTime < now && dict.CreationTime >= now.AddYears(-1) select dict; Assert.GreaterOrEqual(q.Count(), 10); q = from dict in session.Index <PersistableDynamicDictionary>("m_creationTime") where dict.CreationTime > DateTime.UtcNow.AddYears(-1) select dict; Assert.GreaterOrEqual(q.Count(), 10); session.Commit(); } }
void LockConflict(SessionBase sharedReadSession) { string host = null; Random r = new Random(5); SessionPool sessionPool = new SessionPool(3, () => new ServerClientSession(systemDir, host, 2000, false)); try { int iCounter = 0; int sessionId1 = -1; SessionBase session1 = null; for (int i = 0; i < 50; i++) { try { session1 = sessionPool.GetSession(out sessionId1); session1.BeginUpdate(); Dokument Doc_A = new Dokument(); Doc_A.Name = "Test A"; session1.Persist(Doc_A); Console.WriteLine(Doc_A.ToString()); int sessionId2 = -1; SessionBase session2 = null; try { session2 = sessionPool.GetSession(out sessionId2); session2.BeginUpdate(); Dokument Doc_B = new Dokument(); Doc_B.Name = "Test_B"; session2.Persist(Doc_B); Console.WriteLine(Doc_B.ToString()); session2.Commit(); } finally { sessionPool.FreeSession(sessionId2, session2); } session1.Commit(); sharedReadSession.ForceDatabaseCacheValidation(); session1.BeginRead(); ulong ct = session1.AllObjects <Dokument>(false).Count; Console.WriteLine("Number of Dokument found by normal session: " + ct); session1.Commit(); ct = sharedReadSession.AllObjects <Dokument>(false).Count; Console.WriteLine("Number of Dokument found by shared read session: " + ct); } finally { sessionPool.FreeSession(sessionId1, session1); } iCounter++; Console.WriteLine(" -> " + iCounter.ToString()); } } catch (Exception ex) { Console.WriteLine(ex.Message); throw; } }
/// <summary> /// Gets the security stamp. /// </summary> /// <param name="user">The user.</param> /// <returns></returns> public Task <string> GetSecurityStampAsync(T user) { SessionBase session = Session; if (session.InTransaction == false) { session.BeginRead(); } return(Task.FromResult(user.SecurityStamp)); }
/// <summary> /// Determines whether the user has a role. /// </summary> /// <param name="user">The user.</param> /// <param name="roleName">Name of the role.</param> /// <returns></returns> public Task <bool> IsInRoleAsync(T user, string roleName) { SessionBase session = Session; if (session.InTransaction == false) { session.BeginRead(); } return(Task.FromResult(user.Roles.Any(x => x.Name.Equals(roleName)))); }
public object Get([BindRequired, FromQuery] string path, [BindRequired, FromQuery] string id) { if (path == null) { return("Path no set"); } if (id == null) { return("object Id not specified (as string)"); } try { var pool = GetSessionPool(path); int sessionId = -1; SessionBase session = null; try { session = pool.GetSession(out sessionId); UInt64 Id; if (id.Contains('-')) { Id = Oid.IdFromString(id); } else { UInt64.TryParse(id, out Id); } if (Id != 0) { session.BeginRead(); var obj = session.Open <IOptimizedPersistable>(Id); session.Commit(); if (obj == null) { return($"object with id {id} does not exist"); } return(new TypePlusObj(obj)); } return(null); } finally { if (session != null) { pool.FreeSession(sessionId, session); } } } catch (Exception ex) { return(ex.Message); } }
public void verifyDatabaseLocations(SessionBase session) { session.BeginRead(); foreach (Person person in session.AllObjects<Person>()) { Console.WriteLine(person.ToString()); Assert.AreEqual(person.FirstName, "Mats"); } session.Commit(); session.Verify(); }
public void verifyDatabaseLocations(SessionBase session) { session.BeginRead(); foreach (Person person in session.AllObjects <Person>()) { Console.WriteLine(person.ToString()); Assert.AreEqual(person.FirstName, "Mats"); } session.Commit(); session.Verify(); }
/// <summary> /// Finds the role by it's name. /// </summary> /// <param name="roleName">Name of the role.</param> /// <returns>An <see cref="IdentityRole"/> matching the name property.</returns> /// <exception cref="VelocityDBAspNetIdentityException"></exception> /// <remarks>Finds and returns the first valid match. If no match is found, will throw a <see cref="CouchbaseException"/>.</remarks> public async Task <T> FindByNameAsync(string roleName) { SessionBase session = Session; if (session.InTransaction == false) { session.BeginRead(); } var roles = m_aspNetIdentity.Session.AllObjects <IdentityRole>(); return((T)await Task.FromResult((from role in roles where role.Name == roleName select role).FirstOrDefault())); }
public FederationViewModel(FederationInfo federationInfo) : base(null, true) { m_federationInfo = federationInfo; if (m_federationInfo.UsesServerClient || (m_federationInfo.HostName.Length > 0 && m_federationInfo.HostName != Dns.GetHostName())) { m_session = new ServerClientSession(m_federationInfo.SystemDbsPath, m_federationInfo.HostName); } else { m_session = new SessionNoServer(m_federationInfo.SystemDbsPath); } m_session.BeginRead(); }
public FederationSchemaViewModel(FederationInfo federationInfo) : base(null, true) { m_federationInfo = federationInfo; if (m_federationInfo.UsesServerClient || (SessionBase.IsSameHost(m_federationInfo.HostName, SessionBase.LocalHost) == false)) { m_session = new ServerClientSession(m_federationInfo.SystemDbsPath, m_federationInfo.HostName, m_federationInfo.WaitForMilliSeconds, m_federationInfo.UsePessimisticLocking == false); } else { m_session = new SessionNoServer(m_federationInfo.SystemDbsPath, m_federationInfo.WaitForMilliSeconds, m_federationInfo.UsePessimisticLocking == false); } m_session.BeginRead(); }
public DirectoryInfo Initialize(string dbFilePath) { if (dbFilePath != null && dbFilePath.Length > 0) { m_session.BeginRead(); FileInfo dbFile = new FileInfo(dbFilePath); if (dbFile.Exists) { UInt32 dbNum = 0; UInt32.TryParse(dbFile.Name.Substring(0, dbFile.Name.IndexOf('.')), out dbNum); DirectoryInfo directory = dbFile.Directory; if (directory.GetFiles("0.odb").Length > 0) { bool foundIt = false; foreach (var info in m_federationViews) { if (SessionBase.IsSameHost(info.Federationinfo.HostName, SessionBase.LocalHost) && info.Federationinfo.SystemDbsPath.ToLower() == directory.FullName.ToLower()) { foundIt = true; info.IsExpanded = true; foreach (var child in info.Children) { if (child.GetType() == typeof(DatabaseLocationViewModel)) { child.IsExpanded = true; foreach (var dbView in child.Children) { DatabaseViewModel dbViewModel = dbView as DatabaseViewModel; if (dbViewModel != null && dbViewModel.DatabaseNumber == dbNum) { dbView.IsExpanded = true; } } } } } } if (foundIt == false) { return(directory); } } } if (m_session.InTransaction) { m_session.Commit(); } } return(null); }
public void BTreeMap2Iterate() { int sessionId = 0; SessionBase session = null; try { session = SessionManager.SessionPool.GetSession(out sessionId); session.BeginRead(); var bTreeMap = session.Open <BTreeMapOwner>(_id); int zipCodeCt = 0; foreach (var p in bTreeMap.LocationByZipCode) { session.Commit(); session.BeginUpdate(); var v = p.Value; foreach (var l in v) { l.Address1 = "2034 Cordoba PL"; } var k = p.Key; zipCodeCt++; session.Commit(); session.BeginRead(); } Assert.AreEqual(numberOfZipCodes, zipCodeCt); session.Commit(); } catch (Exception ex) { Console.WriteLine(ex.Message); throw; } finally { SessionManager.SessionPool.FreeSession(sessionId, session); } }
/// <inheritdoc /> public override void BeginSession(SyncProviderPosition position, SyncSessionContext syncSessionContext) { if (!syncSessionContext.IsCanceled()) { if (position == SyncProviderPosition.Local) { m_session.BeginUpdate(); } else { m_session.BeginRead(); } } }
/// <summary> /// Finds the role by it's unique identifier (key). /// </summary> /// <param name="roleId">The key for the role.</param> /// <returns></returns> /// <exception cref="VelocityDBAspNetIdentityException"></exception> public async Task <T> FindByIdAsync(UInt64 roleId) { SessionBase session = Session; if (session.InTransaction == false) { session.BeginRead(); } IdentityRole role = new IdentityRole(roleId); if (m_aspNetIdentity.RoleSet.TryGetKey(role, ref role)) { return((T)await Task.FromResult(role)); } return(null); }
/// <summary> /// Finds the user by it's id (key). /// </summary> /// <param name="userId">The user identifier.</param> /// <returns></returns> /// <exception cref="KeyNotFoundException">All server responses other than Success.</exception> /// <exception cref="Exception">Any client error condition.</exception> public async Task <T> FindByIdAsync(UInt64 userId) { SessionBase session = Session; if (session.InTransaction == false) { session.BeginRead(); } IdentityUser user = new IdentityUser(userId); if (m_aspNetIdentity.UserSet.TryGetKey(user, ref user)) { return((T)await Task.FromResult(user)); } return(null); }
/// <summary> /// Finds the login. /// </summary> /// <param name="login">The login.</param> /// <returns></returns> public async Task <T> FindAsync(UserLoginInfo login) { SessionBase session = Session; if (session.InTransaction == false) { session.BeginRead(); } var key = KeyFormats.GetKey(login.LoginProvider, login.ProviderKey); var adapter = m_aspNetIdentity.AdapterMap[key]; IdentityUser user = new IdentityUser(adapter.UserId); if (m_aspNetIdentity.UserSet.TryGetKey(user, ref user)) { return((T)await Task.FromResult(user)); } return(null); }
protected override void LoadChildren() { if (!_session.InTransaction) { _session.BeginRead(); } var types = _session.OpenSchema(false).TypesByName.ToList(); using (System.Windows.Application.Current.Dispatcher.DisableProcessing()) { foreach (var type in types) { if (_internalTypes == _session.OpenSchema(false).IsExpandedInternalType(type.SlotNumber)) { base.Children.Add(new TypeViewModel(this, type)); } } } }
/// <summary> /// Finds the user by email. /// </summary> /// <param name="email">The email.</param> /// <returns></returns> /// <exception cref="KeyNotFoundException">If email isn't a valid key.</exception> /// <exception cref="Exception">Any client error condition.</exception> public async Task <T> FindByEmailAsync(string email) { SessionBase session = Session; if (session.InTransaction == false) { session.BeginRead(); } UInt64 userId; if (m_aspNetIdentity.EmailToId.TryGetValue(email, out userId)) { IdentityUser user = new IdentityUser(userId); if (m_aspNetIdentity.UserSet.TryGetKey(user, ref user)) { return((T)await Task.FromResult(user)); } } return(null); }
private void browseButton_Click(object sender, RoutedEventArgs e) { errorMessage.Content = null; try { SessionBase.DoWindowsAuthentication = (bool)UseWindowsAuthentication.IsChecked; if (this.noServerButton.IsChecked == true) { session = new SessionNoServer(systemDatabaseDirectory.Text, 2000, (bool)OptimisticLocking.IsChecked); } else { session = new ServerClientSession(systemDatabaseDirectory.Text, systemDatabaseServer.Text, 2000, (bool)OptimisticLocking.IsChecked); } session.BeginRead(); List <Database> dbList = session.OpenAllDatabases(); // keep a reference to each db so they don't get garbage collected FederationViewModel viewModel = new FederationViewModel(session.Databases, session); base.DataContext = viewModel; } catch (Exception ex) { errorMessage.Content = ex.Message == null?ex.ToString() : ex.Message; } }
string DisplayData(bool useServerSession) { using (SessionBase session = useServerSession ? (SessionBase) new ServerClientSession(systemDir) : (SessionBase) new SessionNoServer(systemDir)) { StringBuilder sb = new StringBuilder(); session.BeginRead(); try { BTreeBase <RDerby1, RDerby1> index = null; try { session.Index <RDerby1>(); } catch (IndexDatabaseNotSpecifiedException) { UInt32 dbId = session.DatabaseNumberOf(typeof(RDerby1)); Database db = session.OpenDatabase(dbId); index = session.Index <RDerby1>(db); } // for testing //var index = session.Index<Test1_0_0Class>("name2"); // create variable so that can examine in Locals if (index != null) // should not be null? { // get all var testEntries = from t in index select t; int count = testEntries.ToList <RDerby1>().Count; int i = 0; sb.AppendLine("Session Details:"); sb.AppendLine(index.ToStringDetails(session)); sb.AppendLine("Results:"); foreach (RDerby1 test in testEntries) { try { string values = test.Name + ", " + test.Name2 + ", " + test.Added; sb.AppendLine(string.Format("{0, -5:00000}: {1}", i++, values)); } catch (Exception ex) { return("Exception thrown in for each loop: " + ex.Message); } } } else { return("Index was null"); // why is the index null? } } catch (Exception ex) { return("Exception occured prior to loop: " + ex.Message); // examine problem using breakpoint. } finally { session.Commit(); } return(sb.ToString()); } }
public void sessionPoolTest() { const int numberOfSessions = 5; using (SessionPool pool = new SessionPool(numberOfSessions, () => new SessionNoServer(systemDir))) { { int sessionId = -1; SessionBase session = null; try { session = pool.GetSession(out sessionId); using (SessionBase.Transaction transaction = session.BeginUpdate()) { for (int i = 0; i < 1000; i++) { Man man = new Man(); session.Persist(man); } session.Commit(); } } catch (Exception e) { Console.WriteLine(e.Message); throw e; } finally { pool.FreeSession(sessionId, session); } } Parallel.ForEach(Enumerable.Range(0, numberOfSessions * 5), x => { int sessionId = -1; SessionBase session = null; try { session = pool.GetSession(out sessionId); if (session.InTransaction == false) { session.BeginRead(); } var allMen = session.AllObjects <Man>(); ulong allMenCt = allMen.Count(); foreach (Man man in allMen) { double lat = man.Latitude; } Console.WriteLine("Man Count is: " + allMenCt + " Session Id is: " + sessionId + " Current task id is: " + (Task.CurrentId.HasValue ? Task.CurrentId.Value.ToString() : "unknown")); } catch (Exception e) { session?.Abort(); Console.WriteLine(e.Message); throw e; } finally { pool.FreeSession(sessionId, session); } }); } }
public void IndexSample(bool useServerSession) { string brandName = "Toyota"; string color = "Blue"; int maxPassengers = 5; int fuelCapacity = 40; double litresPer100Kilometers = 5; DateTime modelYear = new DateTime(2003, 1, 1); string modelName = "Highlander"; int maxSpeed = 200; int odometer = 100000; string registrationState = "Texas"; string registrationPlate = "TX343434"; string insurancePolicy = "CAA7878787"; DriversLicense license = new DriversLicense("California", "B7788888", DateTime.Now + new TimeSpan(1825, 0, 0, 0)); Person person = new Person("Mats Persson", license); InsuranceCompany insuranceCompany = new InsuranceCompany("Allstate", "858727878"); Car car = new Car(color, maxPassengers, fuelCapacity, litresPer100Kilometers, modelYear, brandName, modelName, maxSpeed, odometer, registrationState, registrationPlate, insuranceCompany, insurancePolicy); using (SessionBase session = useServerSession ? (SessionBase) new ServerClientSession(systemDir) : (SessionBase) new SessionNoServer(systemDir)) { session.BeginUpdate(); foreach (Database db in session.OpenAllDatabases(true)) { if (db.DatabaseNumber >= 10 || db.DatabaseNumber == SessionBase.IndexDescriptorDatabaseNumber) { session.DeleteDatabase(db); } } session.Commit(); session.BeginUpdate(); DatabaseLocation defaultLocation = session.DatabaseLocations.Default(); List <Database> dbList = session.OpenLocationDatabases(defaultLocation, true); foreach (Database db in dbList) { if (db.DatabaseNumber > Database.InitialReservedDatabaseNumbers) { session.DeleteDatabase(db); } } session.DeleteLocation(defaultLocation); session.Commit(); CreateDirectoryAndCopyLicenseDb(); } using (SessionBase session = useServerSession ? (SessionBase) new ServerClientSession(systemDir) : (SessionBase) new SessionNoServer(systemDir)) { session.BeginUpdate(); session.Commit(); } using (SessionBase session = useServerSession ? (SessionBase) new ServerClientSession(systemDir) : (SessionBase) new SessionNoServer(systemDir)) { session.BeginRead(); int ct = 0; var mIndex = session.Index <Motorcycle>(); if (mIndex != null) { foreach (Motorcycle mc in session.Index <Motorcycle>()) { Assert.NotNull(mc); ++ct; } } Assert.AreEqual(ct, 0); session.Commit(); } using (SessionBase session = useServerSession ? (SessionBase) new ServerClientSession(systemDir) : (SessionBase) new SessionNoServer(systemDir)) { session.BeginUpdate(); for (int i = 0; i < 10000; i++) { Motorcycle mc = new Motorcycle(); session.Persist(mc); } session.Commit(); session.BeginUpdate(); int ct = 0; var mIndex = session.Index <Car>(); if (mIndex != null) { foreach (Car c in mIndex) { Assert.NotNull(c); ++ct; } } Assert.AreEqual(ct, 0); ct = 0; session.RegisterClass(typeof(Person)); foreach (Person p in session.AllObjects <Person>(true, false)) { Assert.NotNull(p); ++ct; } session.Commit(); session.BeginRead(); ct = 0; foreach (Motorcycle mc in session.AllObjects <Motorcycle>(false, true)) { Assert.NotNull(mc); ++ct; } Assert.AreEqual(ct, 10000); session.Commit(); session.BeginRead(); ct = 0; foreach (Motorcycle mc in session.AllObjects <Motorcycle>(false, true)) { Assert.NotNull(mc); ++ct; } Assert.AreEqual(ct, 10000); session.Abort(); session.BeginRead(); ct = 0; foreach (Motorcycle mc in session.AllObjects <Motorcycle>(false, true)) { Assert.NotNull(mc); ++ct; } Assert.AreEqual(ct, 10000); session.Commit(); session.BeginRead(); ct = 0; foreach (Motorcycle mc in session.Index <Motorcycle>()) { Assert.NotNull(mc); ++ct; } Assert.AreEqual(ct, 10000); session.Abort(); session.BeginRead(); ct = 0; foreach (Motorcycle mc in session.Index <Motorcycle>()) { Assert.NotNull(mc); ++ct; } Assert.AreEqual(ct, 10000); session.Commit(); try { ct = 0; foreach (Motorcycle mc in session.Index <Motorcycle>()) { Assert.NotNull(mc); ++ct; } Assert.AreEqual(ct, 10000); } catch (NotInTransactionException ex) { Console.WriteLine(ex.Message); } session.BeginUpdate(); ct = 0; foreach (Motorcycle mc in session.AllObjects <Motorcycle>(false, true)) { if (++ct % 2 == 0) { mc.Unpersist(session); } } ct = 0; foreach (Motorcycle mc in session.Index <Motorcycle>()) { ++ct; } Assert.AreEqual(ct, 5000); session.Abort(); session.BeginUpdate(); ct = 0; foreach (Motorcycle mc in session.AllObjects <Motorcycle>(false, true)) { if (++ct % 2 == 0) { mc.Unpersist(session); } } ct = 0; foreach (Motorcycle mc in session.Index <Motorcycle>()) { Assert.NotNull(mc); ++ct; } Assert.AreEqual(ct, 5000); ct = 0; foreach (Motorcycle mc in session.Index <Motorcycle>("cc")) { Assert.NotNull(mc); ++ct; } Assert.AreEqual(ct, 5000); ct = 0; try { foreach (Motorcycle mc in session.Index <Motorcycle>("ccx")) { Assert.NotNull(mc); ++ct; } Assert.AreEqual(ct, 5000); } catch (FieldDoesNotExistException) { } session.Commit(); session.BeginUpdate(); ct = 0; double prior = -44.0; foreach (Motorcycle mc in session.Index <Motorcycle>("cc")) { Assert.NotNull(mc); mc.CC = mc.CC - prior; prior = mc.CC; ++ct; } Assert.AreEqual(ct, 2500); for (int i = 0; i < 95000; i++) { Motorcycle mc = new Motorcycle(); session.Persist(mc); } session.FlushUpdates(); ct = 0; foreach (Motorcycle mc in session.Index <Motorcycle>()) { Assert.NotNull(mc); ++ct; } Assert.AreEqual(ct, 100000); session.Abort(); session.BeginUpdate(); ct = 0; prior = double.MinValue; foreach (Motorcycle mc in session.Index <Motorcycle>("cc")) { Assert.NotNull(mc); Assert.GreaterOrEqual(mc.CC, prior); prior = mc.CC; ++ct; if (ct < 25) { Console.Write(prior.ToString() + " "); } } ct = 0; prior = -44.0; foreach (Motorcycle mc in session.Index <Motorcycle>("cc")) { Assert.NotNull(mc); mc.CC = mc.CC - prior; prior = mc.CC; ++ct; } Assert.AreEqual(ct, 2500); session.Commit(); session.BeginUpdate(); ct = 0; prior = double.MinValue; foreach (Motorcycle mc in session.Index <Motorcycle>("cc")) { Assert.NotNull(mc); Assert.GreaterOrEqual(mc.CC, prior); prior = mc.CC; ++ct; } for (int i = 0; i < 95000; i++) { Motorcycle mc = new Motorcycle(); session.Persist(mc); DataBaseFileEntry dbEntry = new DataBaseFileEntry { Something = "Something" }; session.Persist(dbEntry); mc.AddChild(dbEntry); mc.AddChild(dbEntry); } session.FlushUpdates(); ct = 0; foreach (Motorcycle mc in session.Index <Motorcycle>()) { Assert.NotNull(mc); ++ct; } Assert.AreEqual(ct, 100000); session.Commit(); session.BeginRead(); session.Abort(); session.BeginUpdate(); foreach (Motorcycle mc in session.Index <Motorcycle>()) { Assert.NotNull(mc); VelocityDbList <DataBaseFileEntry> children = mc.Children; if (children != null && children.Count > 0) { mc.RemoveChild(children[0]); } ++ct; } session.Commit(); session.BeginRead(); ct = 0; prior = double.MinValue; foreach (Motorcycle mc in session.Index <Motorcycle>("cc")) { Assert.NotNull(mc); Assert.GreaterOrEqual(mc.CC, prior); prior = mc.CC; ++ct; } Assert.AreEqual(ct, 100000); session.Commit(); Console.WriteLine("Motorcycle index Test OK"); } using (SessionBase session = useServerSession ? (SessionBase) new ServerClientSession(systemDir) : (SessionBase) new SessionNoServer(systemDir)) { session.BeginUpdate(); session.Persist(car); registrationState = "Maine"; car = new Car(color, maxPassengers, fuelCapacity, litresPer100Kilometers, modelYear, brandName, modelName, maxSpeed, odometer, registrationState, registrationPlate, insuranceCompany, insurancePolicy); session.Persist(car); color = "Red"; maxPassengers = 5; fuelCapacity = 50; litresPer100Kilometers = 8; modelYear = new DateTime(2006, 1, 1); brandName = "Toyota"; modelName = "Tacoma"; maxSpeed = 210; odometer = 50000; registrationState = "Texas"; registrationPlate = "TX343433"; insurancePolicy = "CAA7878777"; car = new Car(color, maxPassengers, fuelCapacity, litresPer100Kilometers, modelYear, brandName, modelName, maxSpeed, odometer, registrationState, registrationPlate, insuranceCompany, insurancePolicy); session.Persist(car); color = "Black"; maxPassengers = 5; fuelCapacity = 60; litresPer100Kilometers = 3; modelYear = new DateTime(2001, 1, 1); brandName = "Lincoln"; modelName = "Town Car"; maxSpeed = 220; odometer = 250000; registrationState = "Texas"; registrationPlate = "TX543433"; insurancePolicy = "CAA7878775"; for (int i = 0; i < 1; i++) { registrationState = RandomString(2); registrationPlate = RandomString(12); car = new Car(color, maxPassengers, fuelCapacity, litresPer100Kilometers, modelYear, brandName, modelName, maxSpeed, odometer, registrationState, registrationPlate, insuranceCompany, insurancePolicy); session.Persist(car); color = null; maxPassengers = i; fuelCapacity = 60; litresPer100Kilometers = 3; modelYear = new DateTime(2001, 1, 1); brandName = "Null Car"; modelName = null; maxSpeed = 220; odometer = 250000; insurancePolicy = null; } session.Commit(); } using (SessionBase session = useServerSession ? (SessionBase) new ServerClientSession(systemDir) : (SessionBase) new SessionNoServer(systemDir)) { session.BeginRead(); Console.WriteLine("Blue Cars"); BTreeSet <Car> bTree = session.Index <Car>("color"); foreach (Car c in (from aCar in bTree where aCar.Color == "Blue" select aCar)) { Console.WriteLine(c.ToStringDetails(session)); } Console.WriteLine("Cars in fuel efficierncy order"); foreach (Car c in session.Index <Car>("litresPer100Kilometers")) { Console.WriteLine(c.ToStringDetails(session)); } Console.WriteLine("Vehicles ordered modelYear, brandName, modelName, color"); foreach (Vehicle v in session.Index <Vehicle>()) { Console.WriteLine(v.ToStringDetails(session)); } session.Commit(); } using (SessionBase session = useServerSession ? (SessionBase) new ServerClientSession(systemDir) : (SessionBase) new SessionNoServer(systemDir)) { session.BeginUpdate(); // these LINQ statements will trigger a binary search lookup (not a linear serach) of the matching Car objects in the BTreeSet Car c = (from aCar in session.Index <Car>("color") where aCar.Color == "Blue" select aCar).First(); c.Color = "Green"; session.Commit(); } using (SessionBase session = useServerSession ? (SessionBase) new ServerClientSession(systemDir) : (SessionBase) new SessionNoServer(systemDir)) { session.BeginUpdate(); // these LINQ statements will trigger a binary search lookup (not a linear serach) of the matching Car objects in the BTreeSet Car c = (from aCar in session.Index <Car>("color") where aCar.Color == "Green" select aCar).First(); UInt64 id = c.Id; session.DeleteObject(id); session.Abort(); session.BeginUpdate(); session.DeleteObject(id); session.Commit(); } using (SessionBase session = useServerSession ? (SessionBase) new ServerClientSession(systemDir) : (SessionBase) new SessionNoServer(systemDir)) { Stopwatch sw = new Stopwatch(); sw.Start(); session.BeginRead(); // these LINQ statements will trigger a binary search lookup (not a linear serach) of the matching Car objects in the BTreeSet Console.WriteLine("Blue Cars"); foreach (Car c in (from aCar in session.Index <Car>("color") where aCar.Color == "Blue" select aCar)) { Console.WriteLine(c.ToStringDetails(session)); } session.Commit(); sw.Stop(); Console.WriteLine(sw.Elapsed); } using (SessionBase session = useServerSession ? (SessionBase) new ServerClientSession(systemDir) : (SessionBase) new SessionNoServer(systemDir)) { session.BeginUpdate(); for (int i = 0; i < 10000; i++) { // add some junk to make search harder car = new Car(color, maxPassengers, fuelCapacity, litresPer100Kilometers, modelYear, brandName, modelName, i, odometer, registrationState, registrationPlate + i, insuranceCompany, insurancePolicy); session.Persist(car); } session.Commit(); } using (SessionBase session = useServerSession ? (SessionBase) new ServerClientSession(systemDir) : (SessionBase) new SessionNoServer(systemDir)) { session.BeginRead(); // these LINQ statements will trigger a binary search lookup (not a linear serach) of the matching Car objects in the BTreeSet Console.WriteLine("Blue Cars"); foreach (Car c in (from aCar in session.Index <Car>("color") where aCar.Color == "Blue" select aCar)) { Console.WriteLine(c.ToStringDetails(session)); } session.Commit(); } using (SessionBase session = useServerSession ? (SessionBase) new ServerClientSession(systemDir) : (SessionBase) new SessionNoServer(systemDir)) { session.BeginUpdate(); Car c = (from aCar in session.Index <Car>("color") where aCar.Color == "Blue" select aCar).First(); c.Unpersist(session); session.Commit(); } using (SessionBase session = useServerSession ? (SessionBase) new ServerClientSession(systemDir) : (SessionBase) new SessionNoServer(systemDir)) { session.BeginRead(); foreach (Car c in session.Index <Car>()) { Console.WriteLine(c.ToStringDetails(session)); } Console.WriteLine("Blue Cars"); foreach (Car c in (from aCar in session.Index <Car>() where aCar.Color == "Blue" select aCar)) { Console.WriteLine(c.ToStringDetails(session)); } session.Commit(); } using (SessionBase session = useServerSession ? (SessionBase) new ServerClientSession(systemDir) : (SessionBase) new SessionNoServer(systemDir)) { session.BeginUpdate(); InsuranceCompany prior = insuranceCompany; try { for (int i = 0; i < 100000; i++) { insuranceCompany = new InsuranceCompany("AAA", "858787878"); insuranceCompany.Persist(session, prior); prior = insuranceCompany; } Assert.IsTrue(false); // should not get here } catch (UniqueConstraintException) { } session.Commit(); } using (SessionBase session = useServerSession ? (SessionBase) new ServerClientSession(systemDir) : (SessionBase) new SessionNoServer(systemDir)) { session.BeginRead(); Database db = session.OpenDatabase(session.DatabaseNumberOf(typeof(InsuranceCompany))); var q = from company in session.Index <InsuranceCompany>("name", db) where company.Name == "AAA" select company; foreach (InsuranceCompany company in q) { Console.WriteLine(company.ToStringDetails(session)); // only one will match } session.Commit(); } using (SessionBase session = useServerSession ? (SessionBase) new ServerClientSession(systemDir) : (SessionBase) new SessionNoServer(systemDir)) { session.BeginUpdate(); InsuranceCompany prior = insuranceCompany; try { for (int i = 0; i < 100000; i++) { insuranceCompany = new InsuranceCompany("AAA", "858787878"); session.Persist(insuranceCompany); } Assert.IsTrue(false); // should not get here } catch (UniqueConstraintException) { } session.Commit(); } using (SessionBase session = useServerSession ? (SessionBase) new ServerClientSession(systemDir) : (SessionBase) new SessionNoServer(systemDir)) { session.BeginRead(); Database db = session.OpenDatabase(session.DatabaseNumberOf(typeof(InsuranceCompany))); var q = from company in session.Index <InsuranceCompany>("name", db) where company.Name == "AAA" select company; foreach (InsuranceCompany company in q) { Console.WriteLine(company.ToStringDetails(session)); // only one will match } bool exists = (from anEntry in session.Index <InsuranceCompany>("name", db) where anEntry.Name == "AAA" select 0).Any(); Assert.IsTrue(exists); session.Commit(); } using (SessionBase session = useServerSession ? (SessionBase) new ServerClientSession(systemDir) : (SessionBase) new SessionNoServer(systemDir)) { session.BeginUpdate(); try { for (int i = 0; i < 100000; i++) { insuranceCompany = new InsuranceCompanySpecial("AAA", "858787878"); session.Persist(insuranceCompany); } Assert.IsTrue(false); // should not get here } catch (UniqueConstraintException) { } session.Commit(); } using (SessionBase session = useServerSession ? (SessionBase) new ServerClientSession(systemDir) : (SessionBase) new SessionNoServer(systemDir)) { session.BeginUpdate(); try { for (int i = 0; i < 100000; i++) { insuranceCompany = new InsuranceCompanySpecial2("AAA", "858787878"); session.Persist(insuranceCompany); } Assert.IsTrue(false); // should not get here } catch (UniqueConstraintException) { } session.Commit(); } using (SessionBase session = useServerSession ? (SessionBase) new ServerClientSession(systemDir) : (SessionBase) new SessionNoServer(systemDir)) { session.BeginRead(); Database db = session.OpenDatabase(session.DatabaseNumberOf(typeof(InsuranceCompanySpecial))); var q = from company in session.Index <InsuranceCompany>("name", db) where company.Name == "AAA" select company; foreach (InsuranceCompany company in q) { Console.WriteLine(company.ToStringDetails(session)); // only one will match } bool exists = (from anEntry in session.Index <InsuranceCompanySpecial>("name", db) where anEntry.Name == "AAA" select 0).Any(); Assert.IsTrue(exists); session.Commit(); } }
static public void SyncWith(this SessionBase sessionToUpdate, SessionBase sessionToRead, Func<SessionBase, UInt64, Change, bool> doUpdate) { UInt64 currentVersion; UInt64 pageToReadVersion; bool conflictFound = false; using (var reader = sessionToRead.BeginRead()) { Changes changes = (Changes)sessionToRead.Open(5, 1, 1, false); if (changes != null) { using (var updater = sessionToUpdate.BeginUpdate()) { var dbs = sessionToUpdate.OpenAllDatabases(); ReplicaSync matchingReplicaSync = null; foreach (ReplicaSync sync in sessionToUpdate.AllObjects<ReplicaSync>()) { if (sync.SyncFromHost == sessionToRead.SystemHostName && sync.SyncFromPath == sessionToRead.SystemDirectory) { matchingReplicaSync = sync; break; } } if (changes.ChangeList.Count > 0) { foreach (TransactionChanges transactionChanges in changes.ChangeList) { if (matchingReplicaSync == null || matchingReplicaSync.TransactionNumber < transactionChanges.TransactionNumber) { foreach (Change change in transactionChanges.ChangeList) { Database dbToUpdate = sessionToUpdate.OpenDatabase(change.DatabaseId, false, false); Database dbToRead = sessionToRead.OpenDatabase(change.DatabaseId, false, false); string dbName = dbToRead != null ? dbToRead.Name : null; if (change.Deleted) { if (dbToUpdate == null) // does not exist continue; if (change.PageId == 0) // Database delete { currentVersion = dbToUpdate.Page.PageInfo.VersionNumber; if (currentVersion < change.Version) sessionToUpdate.DeleteDatabase(dbToUpdate); else { conflictFound = true; if (doUpdate(sessionToUpdate, currentVersion, change)) sessionToUpdate.DeleteDatabase(dbToUpdate); } } else { Page page = sessionToUpdate.OpenPage(dbToUpdate, change.PageId); if (page == null) // page does not exist continue; currentVersion = page.PageInfo.VersionNumber; if (currentVersion < change.Version) sessionToUpdate.DeletePage(dbToUpdate, page); else { conflictFound = true; if (doUpdate(sessionToUpdate, currentVersion, change)) sessionToUpdate.DeleteDatabase(dbToUpdate); } } } else { if (dbToUpdate == null) // does not exist dbToUpdate = sessionToUpdate.NewDatabase(change.DatabaseId, 0, dbName); if (change.PageId > 0) { Page pageToUpdate = sessionToUpdate.OpenPage(dbToUpdate, change.PageId); Page pageToRead = sessionToRead.OpenPage(dbToRead, change.PageId); if (pageToRead == null) // upcoming (not yet processed) changes must have deleted this page continue; currentVersion = pageToUpdate == null ? 0 : pageToUpdate.PageInfo.VersionNumber; pageToReadVersion = pageToRead.PageInfo.VersionNumber; if (currentVersion < pageToReadVersion || dbToUpdate.IsNew) sessionToUpdate.ReplacePage(dbToUpdate, pageToUpdate, pageToRead); else { conflictFound = true; if (doUpdate(sessionToUpdate, currentVersion, change)) sessionToUpdate.ReplacePage(dbToUpdate, pageToUpdate, pageToRead); } } } } } } UInt64 lastTransactionNumber = changes.ChangeList.Last().TransactionNumber; if (matchingReplicaSync != null) matchingReplicaSync.TransactionNumber = lastTransactionNumber; if (conflictFound) { sessionToUpdate.Verify(); } sessionToUpdate.Commit(); if (matchingReplicaSync == null) { sessionToUpdate.BeginUpdate(); // separate transaction or else gets confused with databases added by sync matchingReplicaSync = new ReplicaSync(sessionToRead, lastTransactionNumber); sessionToUpdate.Persist(matchingReplicaSync); sessionToUpdate.Commit(); } } } } } }
static public void SyncWith(this SessionBase sessionToUpdate, SessionBase sessionToRead, Func <SessionBase, UInt64, Change, bool> doUpdate) { UInt64 currentVersion; UInt64 pageToReadVersion; bool conflictFound = false; using (var reader = sessionToRead.BeginRead()) { Changes changes = (Changes)sessionToRead.Open(5, 1, 1, false); if (changes != null) { using (var updater = sessionToUpdate.BeginUpdate()) { var dbs = sessionToUpdate.OpenAllDatabases(); ReplicaSync matchingReplicaSync = null; foreach (ReplicaSync sync in sessionToUpdate.AllObjects <ReplicaSync>()) { if (sync.SyncFromHost == sessionToRead.SystemHostName && sync.SyncFromPath == sessionToRead.SystemDirectory) { matchingReplicaSync = sync; break; } } if (changes.ChangeList.Count > 0) { foreach (TransactionChanges transactionChanges in changes.ChangeList) { if (matchingReplicaSync == null || matchingReplicaSync.TransactionNumber < transactionChanges.TransactionNumber) { foreach (Change change in transactionChanges.ChangeList) { Database dbToUpdate = sessionToUpdate.OpenDatabase(change.DatabaseId, false, false); Database dbToRead = sessionToRead.OpenDatabase(change.DatabaseId, false, false); string dbName = dbToRead != null ? dbToRead.Name : null; if (change.Deleted) { if (dbToUpdate == null) // does not exist { continue; } if (change.PageId == 0) // Database delete { currentVersion = dbToUpdate.Page.PageInfo.VersionNumber; if (currentVersion < change.Version) { sessionToUpdate.DeleteDatabase(dbToUpdate); } else { conflictFound = true; if (doUpdate(sessionToUpdate, currentVersion, change)) { sessionToUpdate.DeleteDatabase(dbToUpdate); } } } else { Page page = sessionToUpdate.OpenPage(dbToUpdate, change.PageId); if (page == null) // page does not exist { continue; } currentVersion = page.PageInfo.VersionNumber; if (currentVersion < change.Version) { sessionToUpdate.DeletePage(dbToUpdate, page); } else { conflictFound = true; if (doUpdate(sessionToUpdate, currentVersion, change)) { sessionToUpdate.DeleteDatabase(dbToUpdate); } } } } else { if (dbToUpdate == null) // does not exist { dbToUpdate = sessionToUpdate.NewDatabase(change.DatabaseId, 0, dbName); } if (change.PageId > 0) { Page pageToUpdate = sessionToUpdate.OpenPage(dbToUpdate, change.PageId); Page pageToRead = sessionToRead.OpenPage(dbToRead, change.PageId); if (pageToRead == null) // upcoming (not yet processed) changes must have deleted this page { continue; } currentVersion = pageToUpdate == null ? 0 : pageToUpdate.PageInfo.VersionNumber; pageToReadVersion = pageToRead.PageInfo.VersionNumber; if (currentVersion < pageToReadVersion || dbToUpdate.IsNew) { sessionToUpdate.ReplacePage(dbToUpdate, pageToUpdate, pageToRead); } else { conflictFound = true; if (doUpdate(sessionToUpdate, currentVersion, change)) { sessionToUpdate.ReplacePage(dbToUpdate, pageToUpdate, pageToRead); } } } } } } } UInt64 lastTransactionNumber = changes.ChangeList.Last().TransactionNumber; if (matchingReplicaSync != null) { matchingReplicaSync.TransactionNumber = lastTransactionNumber; } if (conflictFound) { sessionToUpdate.Verify(); } sessionToUpdate.Commit(); if (matchingReplicaSync == null) { sessionToUpdate.BeginUpdate(); // separate transaction or else gets confused with databases added by sync matchingReplicaSync = new ReplicaSync(sessionToRead, lastTransactionNumber); sessionToUpdate.Persist(matchingReplicaSync); sessionToUpdate.Commit(); } } } } } }