static readonly string systemDir = "RelationsCore"; // appended to SessionBase.BaseDatabasePath static int Main(string[] args) { using (var session = new SessionNoServer(systemDir)) { Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); Console.WriteLine($"Running with databases in directory: {session.SystemDirectory}"); try { session.BeginUpdate(); var user = new User { Name = "Mats", Surame = "Persson" }; var user2 = new User { Name = "Robin", Surame = "Persson" }; session.Persist(user); session.Persist(user2); user.Backup = user2; var customer = new Customer { Name = "Ben", Balance = 0 }; session.Persist(customer); var interaction = new Interaction(customer, user, session); session.Commit(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } using (var session = new SessionNoServer(systemDir)) { session.BeginUpdate(); try { foreach (var user in session.AllObjects <User>()) { user.Backup = null; // remove all backup relations (see what happens if you don't !) } foreach (var user in session.AllObjects <User>()) { user.Unpersist(session); } foreach (var customer in session.AllObjects <Customer>()) { customer.Unpersist(session); } foreach (var customer in session.AllObjects <Interaction>()) { throw new UnexpectedException("should not exist any longer"); } session.Commit(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } return(0); }
private void LoadByDynamicQuery() { using (SessionNoServer session = new SessionNoServer(SystemDir)) { Console.WriteLine("\nDynamic Query"); session.BeginRead(); // Query on the Dynamic Property, Iterates over AllObjects<T> // Note: This will throw an Exception if FirstName and LastName are not both defined on every DynamicDictionary. dynamic dynamicQuery1 = session.AllObjects <DynamicDictionary>() .FirstOrDefault(x => x["FirstName"] == "Ellen" && x["LastName"] == "Adams"); // Avoids Exception but still Iterates over AllObjects<T> dynamic dynamicQuery2 = session.AllObjects <DynamicDictionary>() .FirstOrDefault((x) => { dynamic dynX = x; return(dynX.ContainsProperty("FirstName") && dynX.ContainsProperty("LastName") && dynX.FirstName == "John" && dynX.LastName == "Doe"); }); // Dynamic Query Asserts AssertPerson(dynamicQuery1); AssertPerson2(dynamicQuery2); } }
public void LocalDateTest() { LocalDate d1 = new LocalDate(2016, 1, 10); LocalDate d2 = new LocalDate(2016, 1, 1); LocalDate d1other = new LocalDate(2016, 1, 10); Assert.AreNotEqual(d1, d2); Assert.AreEqual(d1, d1other); using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginUpdate(); LocalDateField test1 = new LocalDateField("def", d1); session.Persist(test1); LocalDateField test = new LocalDateField("abc", d2); session.Persist(test); var result1 = session.AllObjects<LocalDateField>().First(t => t.Field2.Equals(d2)); // this works session.Commit(); } using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginRead(); var result2 = session.AllObjects<LocalDateField>().First(t => { var l = t.Field2; return l.Equals(d2); }); // this should work and doesnt session.Commit(); } }
void DictionaryTestTony() { using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginUpdate(); Test test1 = new Test("def", 1); session.Persist(test1); Test test = new Test("abc", 2); session.Persist(test); var res = test.Field3.Equals(test1.Field3); foreach (var test_value in session.AllObjects <Test>()) // this works { Trace.WriteLine(test_value); } Test2 t2 = new Test2("xxxx"); session.Persist(t2); t2.Dict_Field.Add(test1, 1); t2.Dict_Field.Add(test, 2); session.Commit(); } using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginUpdate(); foreach (var test_value in session.AllObjects <Test2>()) // this fails { Trace.WriteLine(test_value); } session.Commit(); } }
public void VelocityDB_SaveKunde_Test() { using (SessionNoServer session = new SessionNoServer(systemDir)) { try { session.BeginUpdate(); var kunde = new KundeVelocityDB(); kunde.Kto = "4711"; kunde.KtoFoerderer = "4712"; kunde.Periode = 2016006; session.Persist(kunde); session.Commit(); } catch (Exception e) { session.Abort(); } } using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginRead(); var kunden = session.AllObjects <KundeVelocityDB>(); var query = from k in kunden where k.Kto.Contains("4711") select k; Assert.AreEqual("4711", query.First()?.Kto); Assert.AreEqual("4712", query.First()?.KtoFoerderer); Assert.AreEqual(2016006, query.First()?.Periode); } }
public void LocalDateTest() { LocalDate d1 = new LocalDate(2016, 1, 10); LocalDate d2 = new LocalDate(2016, 1, 1); LocalDate d1other = new LocalDate(2016, 1, 10); Assert.AreNotEqual(d1, d2); Assert.AreEqual(d1, d1other); using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginUpdate(); LocalDateField test1 = new LocalDateField("def", d1); session.Persist(test1); LocalDateField test = new LocalDateField("abc", d2); session.Persist(test); var result1 = session.AllObjects <LocalDateField>().First(t => t.Field2.Equals(d2)); // this works session.Commit(); } using (var session = new SessionNoServerShared(systemDir)) { session.BeginRead(); var result2 = session.AllObjects <LocalDateField>().First(t => { var l = t.Field2; return(l.Equals(d2)); }); // this should work and doesnt session.Commit(); } }
public void dSyncDeletePages() { using (SessionBase session = new SessionNoServer(s_sync1)) { using (var trans = session.BeginUpdate()) { foreach (FourPerPage fourPerPage in session.AllObjects <FourPerPage>()) { fourPerPage.Unpersist(session); } session.Commit(); } } using (SessionBase readFromSession = new SessionNoServer(s_sync1)) { using (SessionBase updateSession = new SessionNoServer(s_sync2)) { updateSession.SyncWith(readFromSession); } } using (SessionBase readFromSession = new SessionNoServer(s_sync1)) { readFromSession.BeginRead(); using (SessionBase updateSession = new SessionNoServer(s_sync2)) { using (var trans = updateSession.BeginRead()) { Assert.AreEqual(updateSession.AllObjects <FourPerPage>().Count, readFromSession.AllObjects <FourPerPage>().Count); } } } }
public void cSyncNewPages() { using (SessionBase session = new SessionNoServer(s_sync1)) { using (var trans = session.BeginUpdate()) { for (uint i = 0; i < 100; i++) { FourPerPage fourPerPage = new FourPerPage(i); session.Persist(fourPerPage); } session.Commit(); } } using (SessionBase readFromSession = new SessionNoServer(s_sync1)) { using (var updateSession = new SessionNoServerShared(s_sync2)) { updateSession.SyncWith(readFromSession); } } using (SessionBase readFromSession = new SessionNoServer(s_sync1)) { readFromSession.BeginRead(); using (SessionBase updateSession = new SessionNoServer(s_sync2)) { using (var trans = updateSession.BeginRead()) { Assert.AreEqual(updateSession.AllObjects <FourPerPage>().Count, readFromSession.AllObjects <FourPerPage>().Count); } } } }
public City City(string name) { using (SessionNoServer session = new SessionNoServer(SystemDir)) { session.BeginRead(); return(session.AllObjects <City>().SingleOrDefault(c => c.Name.Equals(name))); } }
public void VerifyOpenIssueTrackerCacheOff() { using (SessionNoServer session = new SessionNoServer(systemDir, 2000, true, false)) { session.BeginUpdate(); IssueTracker issueTracker = session.AllObjects <IssueTracker>(false).FirstOrDefault(); session.Commit(); } }
public IList <MitchellClaimType> FindClaims(DateTime lossDateFrom, DateTime lossDateTo) { using (SessionBase session = new SessionNoServer(s_systemDir)) { session.BeginRead(); var e = (from c in session.AllObjects <MitchellClaimType>() where c.LossDate >= lossDateFrom && c.LossDate <= lossDateTo select c).ToList(); session.Commit(); return(e); } }
public void OneMillionFindSingleRecordInTheMiddle() { using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginRead(); var result = (from ComputerFileData computerFileData in session.AllObjects <ComputerFileData>() where computerFileData.FileID == 500000 select computerFileData).First(); session.Commit(); } }
public void OneMillionFindSingleRecordInTheMiddle() { using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginRead(); var result = (from ComputerFileData computerFileData in session.AllObjects<ComputerFileData>() where computerFileData.FileID == 500000 select computerFileData).First(); session.Commit(); } }
public List <City> Cities(string countryCode) { List <City> cities; using (SessionNoServer session = new SessionNoServer(SystemDir)) { session.BeginRead(); cities = session.AllObjects <City>().Where(x => x.Name.Equals(countryCode)).ToList(); } return(cities); }
public List <City> All() { List <City> cities; using (SessionNoServer session = new SessionNoServer(SystemDir)) { session.BeginRead(); cities = session.AllObjects <City>().ToList(); } return(cities); }
public void UnpersistFileFoldersTest() { using (SessionNoServer session = new SessionNoServer(s_systemDir)) { session.NotifyBeforeCommit = NotifyBeforeCommit; session.BeginUpdate(); Assert.Less(10, session.AllObjects <Folder>().Count); Assert.Less(10, session.AllObjects <FileInDb>().Count); DirectoryInfo dirInfo = new DirectoryInfo(s_sampleFolder); Folder folder = (from f in session.AllObjects <Folder>(false) where f.Name == dirInfo.Name && f.ParentFolder == null select f).FirstOrDefault(); folder.Unpersist(session); session.Commit(); } using (SessionNoServer session = new SessionNoServer(s_systemDir)) { session.BeginRead(); Assert.AreEqual(0, session.AllObjects <Folder>().Count); Assert.AreEqual(0, session.AllObjects <FileInDb>().Count); session.Commit(); } }
public void UnpersistFileFoldersTest() { using (SessionNoServer session = new SessionNoServer(s_systemDir)) { session.NotifyBeforeCommit = NotifyBeforeCommit; session.BeginUpdate(); Assert.Less(10, session.AllObjects<Folder>().Count); Assert.Less(10, session.AllObjects<FileInDb>().Count); DirectoryInfo dirInfo = new DirectoryInfo(s_sampleFolder); Folder folder = (from f in session.AllObjects<Folder>(false) where f.Name == dirInfo.Name && f.ParentFolder == null select f).FirstOrDefault(); folder.Unpersist(session); session.Commit(); } using (SessionNoServer session = new SessionNoServer(s_systemDir)) { session.BeginRead(); Assert.AreEqual(0, session.AllObjects<Folder>().Count); Assert.AreEqual(0, session.AllObjects<FileInDb>().Count); session.Commit(); } }
static void QueryGraph() { using (SessionNoServer session = new SessionNoServer(systemDir)) { // Start a read only transaction session.BeginRead(); Graph g = Graph.Open(session); // Cache SCHEMA VertexType movieType = g.FindVertexType("Movie"); PropertyType movieTitleType = movieType.FindProperty("title"); VertexType actorType = g.FindVertexType("Actor"); PropertyType actorNameType = actorType.FindProperty("name"); // How many vertices do we have? Console.WriteLine("Number of Vertices: " + g.CountVertices()); // Find a movie by name Vertex movie = movieTitleType.GetPropertyVertex("The Matrix"); // Get all actors var actors = actorType.GetVertices(); // Count the actors int actorCount = actors.Count(); Console.WriteLine("Number of Actors: " + actorCount); // Get only the actors whose names end with “s” foreach (Vertex vertex in actors) { string actorName = (string)actorNameType.GetPropertyValue(vertex.VertexId); if (actorName.EndsWith("s")) { Console.WriteLine("Found actor with name ending with \"s\" " + actorName); } } // Get a count of property types var properties = session.AllObjects <PropertyType>(); Console.WriteLine("Number of Property types: " + properties.Count()); // All vertices and their edges var edges = g.GetEdges(); int edgeCount = edges.Count(); g.ExportToGraphJson("c:/QuickStart.json"); string exported; using (MemoryStream ms = new MemoryStream()) { g.ExportToGraphJson(ms); exported = Encoding.UTF8.GetString(ms.ToArray()); } session.Commit(); } }
static void Retrieve() { using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginRead(); // get all companies from database IEnumerable <Company> companies = session.AllObjects <Company>(); // get all employees that FirstName contains "John" IEnumerable <Employee> employees = session.AllObjects <Employee>(); var query = from Employee emp in employees where emp.FirstName.Contains("John") select emp; foreach (Employee emp in query) { //do something with employee emp.ToString(); } // get all Employees that are over 30 years old and are from Berlin: var query2 = from Employee emp in employees where emp.Age > 30 && emp.City == "Berlin" select emp; foreach (Employee emp in query2) { //do something with employee emp.ToString(); } // get all Employees that work at "MyCompany" company: var query3 = from Employee emp in employees where emp.Employer.Name == "MyCompany" select new { emp.FirstName, emp.LastName }; session.Commit(); } }
static void Retrieve() { using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginRead(); // get all companies from database IEnumerable<Company> companies = session.AllObjects<Company>(); // get all employees that FirstName contains "John" IEnumerable<Employee> employees = session.AllObjects<Employee>(); var query = from Employee emp in employees where emp.FirstName.Contains("John") select emp; foreach (Employee emp in query) { //do something with employee emp.ToString(); } // get all Employees that are over 30 years old and are from Berlin: var query2 = from Employee emp in employees where emp.Age > 30 && emp.City == "Berlin" select emp; foreach (Employee emp in query2) { //do something with employee emp.ToString(); } // get all Employees that work at "MyCompany" company: var query3 = from Employee emp in employees where emp.Employer.Name == "MyCompany" select new { emp.FirstName, emp.LastName }; session.Commit(); } }
private void ExecuteDateTimeTests <T>() where T : DynamicDictionary, new() { Console.WriteLine("\n***************Saving...***************"); ulong id = 0; using (var session = new SessionNoServer(SystemDir)) { session.BeginUpdate(); var person = CreateScheduledPerson <T>(); id = session.Persist(person); session.Commit(); } Console.WriteLine("***************Complete***************"); Console.WriteLine("\n***************Loading...***************"); using (var session = new SessionNoServer(SystemDir)) { session.BeginRead(); var person = session.Open(id); AssertScheduledPerson(person); session.Commit(); } using (var session = new SessionNoServer(SystemDir)) { session.BeginRead(); var persons = session.AllObjects <T>().ToList(); Assert.IsNotNull(persons); Assert.IsTrue(persons.Count == 1); AssertScheduledPerson(persons[0]); session.Commit(); } Console.WriteLine("***************Complete***************"); }
private void LoadAll() { using (SessionNoServer session = new SessionNoServer(SystemDir)) { Console.WriteLine("\nAllObjects<DynamicDictionary>().ToList()"); session.BeginRead(); var people = session.AllObjects <DynamicDictionary>().ToList(); session.Commit(); Console.WriteLine($"People.Count: {people.Count}"); } }
public City City(double latitude, double longitute) { using (SessionNoServer session = new SessionNoServer(SystemDir)) { session.BeginRead(); NumberFormatInfo provider = new NumberFormatInfo { NumberGroupSeparator = ".", NumberGroupSizes = new int[] { 2 } }; return(session.AllObjects <City>().SingleOrDefault(c => longitute.Equals(Convert.ToDouble(c.Lng, provider)) && latitude.Equals(Convert.ToDouble(c.Lat, provider)))); } }
public void SortedMapTest() { var client = new SessionNoServer(systemDir); client.BeginUpdate(); var set = new SortedMap <string, object>(); set.Add("test", "Test text for example."); set.Persist(client, set); client.Commit(); client.BeginRead(); var readSet = client.AllObjects <SortedMap <string, object> >(false, false).FirstOrDefault(rec => rec.Id == set.Id); Assert.IsNotNull(readSet); client.Commit(); }
public void OneMillionFindSingleRecordInTheMiddleNoLinq() { using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginRead(); var computerFileDataEnum = session.AllObjects <ComputerFileData>(); foreach (ComputerFileData computerFileData in computerFileDataEnum) { if (computerFileData.FileID == 500000) { break; // found it } } session.Commit(); } }
static readonly string s_systemDir = "UpdateClass"; // appended to SessionBase.BaseDatabasePath static int Main(string[] args) { try { Trace.Listeners.Add(new ConsoleTraceListener()); VelocityDbSchema.Samples.UpdateClass.UpdatedClass updatedClassObject; int ct1 = 0; using (SessionNoServer session = new SessionNoServer(s_systemDir)) { session.SetTraceDbActivity(Schema.SchemaDB); session.BeginUpdate(); session.UpdateClass(typeof(VelocityDbSchema.Samples.UpdateClass.UpdatedClass)); // call this when you have updated the class since first storing instances of this type or since last call to UpdateClass UInt32 dbNum = session.DatabaseNumberOf(typeof(VelocityDbSchema.Samples.UpdateClass.UpdatedClass)); foreach (var obj in session.AllObjects <VelocityDbSchema.Samples.UpdateClass.UpdatedClass>()) { Console.Write(obj.ToString() + " has members: "); foreach (DataMember member in obj.GetDataMembers()) { Console.Write(member.ToString() + " "); } Console.WriteLine(); obj.UpdateTypeVersion(); // comment out if you DO NOT want to migrate this object to the latest version of the class ct1++; } int ct2 = 0; Database db = session.OpenDatabase(dbNum, true, false); if (db != null) { foreach (var obj in db.AllObjects <VelocityDbSchema.Samples.UpdateClass.UpdatedClass>()) { ct2++; } } Debug.Assert(ct1 == ct2); updatedClassObject = new VelocityDbSchema.Samples.UpdateClass.UpdatedClass(); session.Persist(updatedClassObject); session.Commit(); MoveToDifferentFullClassName(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); return(1); } return(0); }
private void Button_Click(object sender, RoutedEventArgs e) { using (SessionNoServer session = new SessionNoServer(systemDir)) { Console.WriteLine("Running with databases in directory: " + session.SystemDirectory); const UInt32 numberOfPersons = 10000; const ushort nodeMaxSize = 5000; const ushort comparisonByteArraySize = sizeof(UInt64); // enough room to hold entire idNumber of a Person const bool comparisonArrayIsCompleteKey = true; const bool addIdCompareIfEqual = false; Person person; session.BeginUpdate(); session.DefaultDatabaseLocation().CompressPages = PageInfo.compressionKind.None; //mySession.SetTraceAllDbActivity(); BTreeSet <string> stringSet = new BTreeSet <string>(null, session); BTreeSetOidShort <string> stringSetShort = new BTreeSetOidShort <string>(null, session); BTreeMap <string, string> stringMap = new BTreeMap <string, string>(null, session); BTreeMapOidShort <string, string> stringMapShort = new BTreeMapOidShort <string, string>(null, session); CompareByField <Person> compareByField = new CompareByField <Person>("idNumber", session, addIdCompareIfEqual); BTreeSet <Person> bTree = new BTreeSet <Person>(compareByField, session, nodeMaxSize, comparisonByteArraySize, comparisonArrayIsCompleteKey); session.Persist(bTree); // Persist the root of the BTree so that we have something persisted that can be flushed to disk if memory available becomes low for (int i = 0; i < numberOfPersons; i++) { person = new Person(); // session.Persist(person); bTree.AddFast(person); } session.Commit(); } using (SessionNoServer session = new SessionNoServer(systemDir)) { session.UseExternalStorageApi = true; session.BeginRead(); BTreeSet <Person> bTree = session.AllObjects <BTreeSet <Person> >().First(); foreach (Person person in (IEnumerable <Person>)bTree) { if (person.IdNumber > 196988888791402) { Console.WriteLine(person); break; } } session.Commit(); } }
private void Button_Click(object sender, RoutedEventArgs e) { using (SessionNoServer session = new SessionNoServer(systemDir)) { Console.WriteLine("Running with databases in directory: " + session.SystemDirectory); const UInt32 numberOfPersons = 10000; const ushort nodeMaxSize = 5000; const ushort comparisonByteArraySize = sizeof(UInt64); // enough room to hold entire idNumber of a Person const bool comparisonArrayIsCompleteKey = true; const bool addIdCompareIfEqual = false; Person person; session.BeginUpdate(); session.DefaultDatabaseLocation().CompressPages = PageInfo.compressionKind.None; //mySession.SetTraceAllDbActivity(); BTreeSet<string> stringSet = new BTreeSet<string>(null, session); BTreeSetOidShort<string> stringSetShort = new BTreeSetOidShort<string>(null, session); BTreeMap<string, string> stringMap = new BTreeMap<string, string>(null, session); BTreeMapOidShort<string, string> stringMapShort = new BTreeMapOidShort<string, string>(null, session); CompareByField<Person> compareByField = new CompareByField<Person>("idNumber", session, addIdCompareIfEqual); BTreeSet<Person> bTree = new BTreeSet<Person>(compareByField, session, nodeMaxSize, comparisonByteArraySize, comparisonArrayIsCompleteKey); session.Persist(bTree); // Persist the root of the BTree so that we have something persisted that can be flushed to disk if memory available becomes low for (int i = 0; i < numberOfPersons; i++) { person = new Person(); // session.Persist(person); bTree.AddFast(person); } session.Commit(); } using (SessionNoServer session = new SessionNoServer(systemDir)) { session.UseExternalStorageApi = true; session.BeginRead(); BTreeSet<Person> bTree = session.AllObjects<BTreeSet<Person>>().First(); foreach (Person person in (IEnumerable<Person>)bTree) { if (person.IdNumber > 196988888791402) { Console.WriteLine(person); break; } } session.Commit(); } }
protected void LoginButton_Click(object sender, EventArgs e) { if (Password.Text.Length == 0) { ErrorMessage.Text = "Enter your password."; return; } try { using (SessionNoServer session = new SessionNoServer(s_dataPath, 2000, true, true)) { session.BeginUpdate(); Root velocityDbroot = session.AllObjects <Root>(false).FirstOrDefault(); if (velocityDbroot == null) { ErrorMessage.Text = "The entered email address is not registered with this website"; session.Abort(); return; } CustomerContact lookup = new CustomerContact(Email.Text, null); if (!velocityDbroot.customersByEmail.TryGetKey(lookup, ref lookup)) { ErrorMessage.Text = "The entered email address is not registered with this website"; session.Abort(); return; } if (lookup.password != Password.Text) { ErrorMessage.Text = "The entered password does not match the registered password"; session.Abort(); return; } session.Commit(); Session["UserName"] = lookup.UserName; Session["Email"] = Email.Text; Session["FirstName"] = lookup.FirstName; Session["LastName"] = lookup.LastName; FormsAuthentication.RedirectFromLoginPage(Email.Text, false); } } catch (System.Exception ex) { ErrorMessage.Text = ex.ToString() + ex.Message; } }
static void Main(string[] args) { try { using (SessionNoServer session = new SessionNoServer(s_systemDir)) { DatabaseLocation localLocation = new DatabaseLocation(Dns.GetHostName(), Path.Combine(session.SystemDirectory, "desEncryptedLocation"), desEncryptedStartDatabaseNumber, UInt32.MaxValue, session, PageInfo.compressionKind.LZ4, PageInfo.encryptionKind.desEncrypted); session.BeginUpdate(); session.NewLocation(localLocation); localLocation.DesKey = SessionBase.TextEncoding.GetBytes("5d9nndwy"); // Des keys are 8 bytes long Person robinHood = new Person("Robin", "Hood", 30); Person billGates = new Person("Bill", "Gates", 56, robinHood); Person steveJobs = new Person("Steve", "Jobs", 56, billGates); robinHood.BestFriend = billGates; session.Persist(steveJobs); steveJobs.Friends.Add(billGates); steveJobs.Friends.Add(robinHood); billGates.Friends.Add(billGates); robinHood.Friends.Add(steveJobs); session.Commit(); } using (SessionNoServer session = new SessionNoServer(s_systemDir)) { // Des keys are not persisted in DatabaseLocation (for safety). Instead they are stored as *.des files // in the users document directory of the user that created the DatabaseLocation. These files can be copied // to other user's document directory when acccess is desired for other users. // Path to user document dir is given by C#: Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); session.BeginRead(); var allPersonsEnum = session.AllObjects <Person>(); foreach (Person obj in allPersonsEnum) { Person person = obj as Person; if (person != null) { Console.WriteLine(person.FirstName); } } session.Commit(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
protected void LoginButton_Click(object sender, EventArgs e) { if (Password.Text.Length == 0) { ErrorMessage.Text = "Enter your password."; return; } try { using (SessionNoServer session = new SessionNoServer(s_dataPath, 2000, true, true)) { session.BeginUpdate(); Root velocityDbroot = session.AllObjects<Root>(false).FirstOrDefault(); if (velocityDbroot == null) { ErrorMessage.Text = "The entered email address is not registered with this website"; session.Abort(); return; } CustomerContact lookup = new CustomerContact(Email.Text, null); if (!velocityDbroot.customersByEmail.TryGetKey(lookup, ref lookup)) { ErrorMessage.Text = "The entered email address is not registered with this website"; session.Abort(); return; } if (lookup.password != Password.Text) { ErrorMessage.Text = "The entered password does not match the registered password"; session.Abort(); return; } session.Commit(); Session["UserName"] = lookup.UserName; Session["Email"] = Email.Text; Session["FirstName"] = lookup.FirstName; Session["LastName"] = lookup.LastName; FormsAuthentication.RedirectFromLoginPage(Email.Text, false); } } catch (System.Exception ex) { ErrorMessage.Text = ex.ToString() + ex.Message; } }
public void Create3Versions(int numberOfVersions) { ProductVersion version = null; ProductVersion priorVersion = null; for (int i = 0; i < numberOfVersions; i++) using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginUpdate(); IssueTracker issueTracker = session.AllObjects<IssueTracker>(false).FirstOrDefault(); User user = issueTracker.UserSet.Keys[rand.Next(issueTracker.UserSet.Keys.Count - 1)]; string v = "version" + i.ToString(); string d = "vdescription" + i.ToString(); version = new ProductVersion(user, v, d, null); session.Persist(version); issueTracker.VersionSet.Add(version); priorVersion = version; session.Commit(); } }
static void Main(string[] args) { try { using (SessionNoServer session = new SessionNoServer(s_systemDir)) { DatabaseLocation localLocation = new DatabaseLocation(Dns.GetHostName(), Path.Combine(session.SystemDirectory, "desEncryptedLocation"), desEncryptedStartDatabaseNumber, UInt32.MaxValue, session, PageInfo.compressionKind.LZ4, PageInfo.encryptionKind.desEncrypted); session.BeginUpdate(); session.NewLocation(localLocation); localLocation.DesKey = SessionBase.TextEncoding.GetBytes("5d9nndwy"); // Des keys are 8 bytes long Person robinHood = new Person("Robin", "Hood", 30); Person billGates = new Person("Bill", "Gates", 56, robinHood); Person steveJobs = new Person("Steve", "Jobs", 56, billGates); robinHood.BestFriend = billGates; session.Persist(steveJobs); steveJobs.Friends.Add(billGates); steveJobs.Friends.Add(robinHood); billGates.Friends.Add(billGates); robinHood.Friends.Add(steveJobs); session.Commit(); } using (SessionNoServer session = new SessionNoServer(s_systemDir)) { // Des keys are not persisted in DatabaseLocation (for safety). Instead they are stored as *.des files // in the users document directory of the user that created the DatabaseLocation. These files can be copied // to other user's document directory when acccess is desired for other users. // Path to user document dir is given by C#: Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); session.BeginRead(); var allPersonsEnum = session.AllObjects<Person>(); foreach (Person obj in allPersonsEnum) { Person person = obj as Person; if (person != null) Console.WriteLine(person.FirstName); } session.Commit(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
public void SortedMapTest2() { const string key = "test"; const string value = "Test text for example."; var client = new SessionNoServer(systemDir); client.BeginUpdate(); var originalRecord = new SortedMap <string, object>(); originalRecord.Add(key, value); originalRecord.Persist(client, originalRecord); client.Commit(); client.BeginRead(); var newRecord = client.AllObjects <SortedMap <string, object> >(false, false).FirstOrDefault(r => r.Id == originalRecord.Id); Assert.IsNotNull(newRecord); Assert.AreEqual(originalRecord[key], newRecord[key]); client.Commit(); client.Dispose(); }
public void Create2Users(int numberOfUsers) { User user = null; User priorUser = null; for (int i = 0; i < numberOfUsers; i++) using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginUpdate(); IssueTracker issueTracker = session.AllObjects<IssueTracker>(false).FirstOrDefault(); string email = i.ToString() + "@gmail.com"; string first = "first" + i.ToString(); string last = "last" + i.ToString(); string userName = "******" + i.ToString(); user = new User(user, email, first, last, userName); session.Persist(user); issueTracker.UserSet.Add(user); priorUser = user; session.Commit(); } }
public void SortedMapStringValueTest() { var client = new SessionNoServer(systemDir); const string key = "test"; const string value = "string value text"; client.BeginUpdate(); var originalRecord = new StringRecord(); originalRecord.Fields.Add(key, value); originalRecord.Persist(client, originalRecord); client.Commit(); client = new SessionNoServer(systemDir); client.BeginUpdate(); var newRecord = client.AllObjects <StringRecord>(false, false).FirstOrDefault(r => r.Id == originalRecord.Id); Assert.IsNotNull(newRecord); Assert.AreEqual(originalRecord.Fields[key], newRecord.Fields[key]); client.Commit(); client.Dispose(); }
static readonly string s_systemDir = "UpdateClass"; // appended to SessionBase.BaseDatabasePath static int Main(string[] args) { try { UpdatedClass updatedClassObject; int ct1 = 0; using (SessionNoServer session = new SessionNoServer(s_systemDir)) { session.BeginUpdate(); session.UpdateClass(typeof(UpdatedClass)); // call this when you have updated the class since first storing instances of this type or since last call to UpdateClass UInt32 dbNum = session.DatabaseNumberOf(typeof(UpdatedClass)); foreach (UpdatedClass obj in session.AllObjects<UpdatedClass>()) { Console.Write(obj.ToString() + " has members: "); foreach (DataMember member in obj.GetDataMembers()) { Console.Write(member.ToString() + " "); } Console.WriteLine(); obj.UpdateTypeVersion(); // comment out if you DO NOT want to migrate this object to the latest version of the class ct1++; } int ct2 = 0; Database db = session.OpenDatabase(dbNum, true, false); if (db != null) foreach (UpdatedClass obj in db.AllObjects<UpdatedClass>()) ct2++; Debug.Assert(ct1 == ct2); updatedClassObject = new UpdatedClass(); session.Persist(updatedClassObject); session.Commit(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); return 1; } return 0; }
public void Create4Projects(int numberOfProjects) { Project project = null; Project priorProject = null; for (int i = 0; i < numberOfProjects; i++) { using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginUpdate(); IssueTracker issueTracker = session.AllObjects <IssueTracker>(false).FirstOrDefault(); User user = issueTracker.UserSet.Keys[rand.Next(issueTracker.UserSet.Keys.Count - 1)]; string p = "project" + i.ToString(); string d = "pdescription" + i.ToString(); project = new Project(user, p, d); session.Persist(project); priorProject = project; issueTracker.ProjectSet.Add(project); session.Commit(); } } }
public void Create3Versions(int numberOfVersions) { ProductVersion version = null; ProductVersion priorVersion = null; for (int i = 0; i < numberOfVersions; i++) { using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginUpdate(); IssueTracker issueTracker = session.AllObjects <IssueTracker>(false).FirstOrDefault(); User user = issueTracker.UserSet.Keys[rand.Next(issueTracker.UserSet.Keys.Count - 1)]; string v = "version" + i.ToString(); string d = "vdescription" + i.ToString(); version = new ProductVersion(user, v, d, null); session.Persist(version); issueTracker.VersionSet.Add(version); priorVersion = version; session.Commit(); } } }
public void CarregarEmpregados() { using (var session = new SessionNoServer("OODBMS_FOLDER")) { try { session.BeginRead(); var empregados = session.AllObjects <Empregado>(); Empregados.Items.Clear(); foreach (var empregado in empregados) { Empregados.Items.Add(empregado); } session.Commit(); } catch (Exception e) { session.Abort(); } } }
protected void ForgotPasswordLinkButton_Click(object sender, EventArgs e) { try { using (SessionNoServer session = new SessionNoServer(s_dataPath, 2000, true, true)) { session.BeginRead(); Root root = session.AllObjects<Root>(false).FirstOrDefault(); if (root == null) { ErrorMessage.Text = "The entered email address is not registered with this website"; session.Abort(); return; } CustomerContact lookup = new CustomerContact(Email.Text, null); if (!root.customersByEmail.TryGetKey(lookup, ref lookup)) { ErrorMessage.Text = "The entered email address is not registered with this website"; session.Abort(); return; } session.Commit(); MailMessage message = new MailMessage("*****@*****.**", Email.Text); message.Subject = "Your password to VelocityWeb"; message.Body = "Password is: " + lookup.password; SmtpClient client = new SmtpClient("smtpout.secureserver.net", 80); System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential("*****@*****.**", "xxxx"); client.Credentials = SMTPUserInfo; client.Send(message); ErrorMessage.Text = "Email with your password was send to: " + Email.Text; } } catch (System.Exception ex) { ErrorMessage.Text = ex.ToString(); } }
public void Create6Issues(int numberOfIssues) { Issue issue = null; Issue priorIssue = null; using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginUpdate(); for (int i = 0; i < numberOfIssues; i++) { IssueTracker issueTracker = session.AllObjects<IssueTracker>(false).FirstOrDefault(); User user = issueTracker.UserSet.Keys[rand.Next(issueTracker.UserSet.Count)]; User assignedTo = issueTracker.UserSet.Keys[rand.Next(issueTracker.UserSet.Count)]; Project project = issueTracker.ProjectSet.Keys[rand.Next(issueTracker.ProjectSet.Count)]; Component component = issueTracker.ComponentSet.Keys[rand.Next(issueTracker.ComponentSet.Count)]; ProductVersion version = issueTracker.VersionSet.Keys[rand.Next(issueTracker.VersionSet.Count)]; Issue.CategoryEnum category = (Issue.CategoryEnum)rand.Next(5); Issue.Resolution resolution = (Issue.Resolution)rand.Next(5); Issue.PriorityEnum priority = (Issue.PriorityEnum)rand.Next(5); Issue.StatusEnum status = (Issue.StatusEnum)rand.Next(5); if (status == Issue.StatusEnum.Open || status == Issue.StatusEnum.InProgress || status == Issue.StatusEnum.Reopened) resolution = Issue.Resolution.Incomplete; // the other states does not make sense DateTime dueDate = new DateTime(rand.Next(), DateTimeKind.Utc); string c = "project" + i.ToString(); string s = "summary" + i.ToString(); string e = "environment" + i.ToString(); string d = "idescription" + i.ToString(); issue = new Issue(user, priority, project, category, component, version, resolution, s, d, e, assignedTo, dueDate, null, status); session.Persist(issue); priorIssue = issue; issueTracker.Add(issue); } session.Commit(); } }
public void Create5Components(int numberOfComponents) { Component component = null; Component priorComponent = null; for (int i = 0; i < numberOfComponents; i++) using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginUpdate(); IssueTracker issueTracker = session.AllObjects<IssueTracker>(false).FirstOrDefault(); User user = issueTracker.UserSet.Keys[rand.Next(issueTracker.UserSet.Keys.Count - 1)]; Project project = issueTracker.ProjectSet.Keys[rand.Next(issueTracker.ProjectSet.Keys.Count - 1)]; string c = "component" + i.ToString(); string d = "cdescription" + i.ToString(); component = new Component(user, c, d, project); session.Persist(component); issueTracker.ComponentSet.Add(component); priorComponent = component; session.Commit(); } }
public void CreateDataAndIterateSession(int numObj) { using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginUpdate(); UInt32 dbNum = session.DatabaseNumberOf(typeof(NotSharingPage)); Database db = session.OpenDatabase(dbNum, true, false); if (db != null) session.DeleteDatabase(db); dbNum = session.DatabaseNumberOf(typeof(SharingPageTypeA)); db = session.OpenDatabase(dbNum, true, false); if (db != null) session.DeleteDatabase(db); dbNum = session.DatabaseNumberOf(typeof(SharingPageTypeB)); db = session.OpenDatabase(dbNum, true, false); if (db != null) session.DeleteDatabase(db); session.Commit(); } using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginUpdate(); UInt32 dbNum = session.DatabaseNumberOf(typeof(SharingPageTypeB)); Placement place = new Placement(dbNum, 100); for (int i = 0; i < numObj; i++) { NotSharingPage ns = new NotSharingPage(); session.Persist(ns); SharingPageTypeA sA = new SharingPageTypeA(); session.Persist(sA); SharingPageTypeB sB = new SharingPageTypeB(); if (i % 5 == 0) sB.Persist(session, place); else if (i % 1001 == 0) sB.Persist(session, sA); else if (i % 3001 == 0) sB.Persist(session, ns); else session.Persist(sB); } session.Commit(); } using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginRead(); UInt32 dbNum = session.DatabaseNumberOf(typeof(NotSharingPage)); Database db = session.OpenDatabase(dbNum); AllObjects<NotSharingPage> all = session.AllObjects<NotSharingPage>(true, false); OfType all2 = session.OfType(typeof(NotSharingPage), true, false); dbNum = session.DatabaseNumberOf(typeof(SharingPageTypeA)); Database dbA = session.OpenDatabase(dbNum); dbNum = session.DatabaseNumberOf(typeof(SharingPageTypeB)); Database dbB = session.OpenDatabase(dbNum); AllObjects<SharingPageTypeA> allA = session.AllObjects<SharingPageTypeA>(true, false); AllObjects<SharingPageTypeB> allB = session.AllObjects<SharingPageTypeB>(true, false); int start = numObj / 2; NotSharingPage ns = all.ElementAt(numObj - 1); // zero based index so deduct one NotSharingPage ns2 = (NotSharingPage)all2.ElementAt(numObj - 1); Assert.AreEqual(ns, ns2); SharingPageTypeA sA = allA.ElementAt(15); SharingPageTypeB sB = allB.ElementAt(10); for (int i = start; i < numObj; i++) ns = all.ElementAt(i); //for (int i = start; i < numObj; i++) // ns = all.Skip(i).T //for (int i = start; i < numObj; i++) // sA = allA.ElementAt(i); all.Skip(100); all2.Skip(100); for (int i = start; i < numObj; i += 5) { ns = all.ElementAt(i); ns2 = (NotSharingPage)all2.ElementAt(i); Assert.AreEqual(ns, ns2); } for (int i = 5; i < 100; i += 5) sB = allB.ElementAt(i); for (int i = 0; i < numObj; i += 45000) ns = all.ElementAt(i); session.Commit(); session.BeginUpdate(); session.DeleteDatabase(db); session.DeleteDatabase(dbA); session.DeleteDatabase(dbB); session.Commit(); } }
public void dSyncDeletePages() { using (SessionBase session = new SessionNoServer(s_sync1)) { using (var trans = session.BeginUpdate()) { foreach (FourPerPage fourPerPage in session.AllObjects<FourPerPage>()) fourPerPage.Unpersist(session); session.Commit(); } } using (SessionBase readFromSession = new SessionNoServer(s_sync1)) { using (SessionBase updateSession = new SessionNoServer(s_sync2)) { updateSession.SyncWith(readFromSession); } } using (SessionBase readFromSession = new SessionNoServer(s_sync1)) { readFromSession.BeginRead(); using (SessionBase updateSession = new SessionNoServer(s_sync2)) { using (var trans = updateSession.BeginRead()) { Assert.AreEqual(updateSession.AllObjects<FourPerPage>().Count, readFromSession.AllObjects<FourPerPage>().Count); } } } }
public void cSyncNewPages() { using (SessionBase session = new SessionNoServer(s_sync1)) { using (var trans = session.BeginUpdate()) { for (uint i = 0; i < 100; i++) { FourPerPage fourPerPage = new FourPerPage(i); session.Persist(fourPerPage); } session.Commit(); } } using (SessionBase readFromSession = new SessionNoServer(s_sync1)) { using (SessionBase updateSession = new SessionNoServer(s_sync2)) { updateSession.SyncWith(readFromSession); } } using (SessionBase readFromSession = new SessionNoServer(s_sync1)) { readFromSession.BeginRead(); using (SessionBase updateSession = new SessionNoServer(s_sync2)) { using (var trans = updateSession.BeginRead()) { Assert.AreEqual(updateSession.AllObjects<FourPerPage>().Count, readFromSession.AllObjects<FourPerPage>().Count); } } } }
static void Main(string[] args) { long triangles = 0; try { using (SessionNoServer session = new SessionNoServer(systemDir)) { int numberOfWorkerThreads = -1; if (args.Length > 0) { if (!int.TryParse(args[0], out numberOfWorkerThreads)) Console.WriteLine("First parameter is numberOfWorkerThreads which must be an Int32"); } bool useLinq = args.Length > 1; session.BeginUpdate(); BTreeMapIterator<int, int[]> edgesItr; int[] edge = null; BTreeMap<int, int[]> edges = session.AllObjects<BTreeMap<int, int[]>>(false).FirstOrDefault(); if (edges != null) { session.Commit(); session.BeginRead(); } else { DatabaseLocation location = session.DatabaseLocations.Default(); edges = new BTreeMap<int, int[]>(null, session, 6000); session.Persist(edges); edgesItr = edges.Iterator(); using (StreamReader stream = new StreamReader(edgesInputFile, true)) { int a; int b; string line; string[] fields; while ((line = stream.ReadLine()) != null) { fields = line.Split(' '); if (!int.TryParse(fields[0], out a)) break; b = int.Parse(fields[1]); if (a != b) { if (edgesItr.CurrentKey() == a || edgesItr.GoTo(a)) { edge = edgesItr.CurrentValue(); Array.Resize(ref edge, edge.Length + 1); edge[edge.Length - 1] = b; edgesItr.ReplaceValue(ref edge); // we need to update the value in the BTreeMap } else { edge = new int[1]; edge[0] = b; edges.Add(a, edge); } } } } edgesItr = edges.Iterator(); while (edgesItr.MoveNext()) { edge = edgesItr.CurrentValue(); Array.Sort(edge); edgesItr.ReplaceValue(ref edge); } session.Commit(); session.BeginRead(); } Console.WriteLine("Number of Nodes found: " + edges.Count); if (useLinq) Console.WriteLine("Query using LINQ"); if (numberOfWorkerThreads > 0) Console.WriteLine("Start of triangle discovery using " + numberOfWorkerThreads + " threads, time is " + DateTime.Now); else if (numberOfWorkerThreads < 0) Console.WriteLine("Start of triangle discovery using system automatically selected number of threads, time is " + DateTime.Now); else Console.WriteLine("Start of triangle discovery using main thread, time is " + DateTime.Now); // Start counting triangles ! if (numberOfWorkerThreads != 0) { if (useLinq) { // Please help, I have not figured out how to properly do the triangle query using LINQ int[] edge2values = null; if (numberOfWorkerThreads > 0) triangles = (from KeyValuePair<int, int[]> edgeFrom in edges from int edgeTo1 in edgeFrom.Value where edgeFrom.Key < edgeTo1 from int edgeTo2 in edgeFrom.Value where edgeFrom.Key < edgeTo2 && edgeTo2 > edgeTo1 && edges.TryGetValue(edgeTo1, out edge2values) && Array.BinarySearch(edge2values, edgeTo2) >= 0 select edge).AsParallel().WithDegreeOfParallelism(numberOfWorkerThreads).Count(); else triangles = (from KeyValuePair<int, int[]> edgeFrom in edges from int edgeTo1 in edgeFrom.Value where edgeFrom.Key < edgeTo1 from int edgeTo2 in edgeFrom.Value where edgeFrom.Key < edgeTo2 && edgeTo2 > edgeTo1 && edges.TryGetValue(edgeTo1, out edge2values) && Array.BinarySearch(edge2values, edgeTo2) >= 0 select edge).AsParallel().Count(); } else { edgesItr = edges.Iterator(); ParallelOptions pOptions = new ParallelOptions(); pOptions.MaxDegreeOfParallelism = numberOfWorkerThreads; // First type parameter is the type of the source elements // Second type parameter is the type of the local data (subtotal) Parallel.ForEach<KeyValuePair<int, int[]>, long>(edges, // source collection pOptions, () => 0, // method to initialize the local variable (pair, loop, subtotal) => // method invoked by the loop on each iteration { int nodeId = pair.Key; int[] nodeTo = pair.Value; int stop = nodeTo.Length - 1; int i = stop; int edgeToStart, edgeTo; int pos; while (i >= 0) { int[] edgeInfo2; edgeToStart = nodeTo[i--]; if (nodeId < edgeToStart) { if (edges.TryGetValue(edgeToStart, out edgeInfo2)) { for (int j = stop; j >= i; j--) { edgeTo = nodeTo[j]; if (edgeToStart < edgeTo) { pos = Array.BinarySearch<int>(edgeInfo2, edgeTo); if (pos >= 0) { // we know this one is connected to edgeInfo.From because it is part of edgeInfo.To subtotal++; } } else break; } } } else break; } return subtotal; }, // Method to be executed when all loops have completed. // finalResult is the final value of subtotal. supplied by the ForEach method. (finalResult) => Interlocked.Add(ref triangles, finalResult)); } } else if (useLinq) triangles = queryUsingLINQ(edges); else triangles = discoverTrianglesSingleCore(edges); session.Commit(); } Console.WriteLine("Number of Triangles found: " + triangles + ", time is " + DateTime.Now); } catch (Exception e) { System.Console.WriteLine(e); } }
public void CreateEdges() { Create1Vertices(true); using (SessionNoServer session = new SessionNoServer(systemDir, 5000, false, true)) { session.BeginUpdate(); Graph g = Graph.Open(session); // it takes a while to open graph fresh from databases VertexType userType = g.FindVertexType("User"); VertexType locationType = g.FindVertexType("Location"); EdgeType friendEdgeType = g.FindEdgeType("Friend"); EdgeType userLocationEdgeType = g.FindEdgeType("UserLocation"); int lineNumber = 0; long fiendsCt = 0; foreach (string line in File.ReadLines(inputData)) { string[] fields = line.Split(' '); Vertex aUser = new Vertex(g, userType, ++lineNumber); int locationCt = 1; foreach (string s in fields) { if (s.Length > 0) { ++fiendsCt; Vertex aFriend = new Vertex(g, userType, int.Parse(s)); Vertex aLocation = new Vertex(g, locationType, locationCt++); friendEdgeType.NewEdge(aUser, aFriend); userLocationEdgeType.NewEdge(aUser, aLocation); } } if (lineNumber >= 5000) break; } Console.WriteLine("Done importing " + lineNumber + " users with " + fiendsCt + " friends"); session.Commit(); session.BeginRead(); foreach (var x in session.AllObjects<BTreeSet<Range<VertexId>>>(false, true)) Assert.True(x.ToDoBatchAddCount == 0); foreach (var x in session.AllObjects<BTreeSet<EdgeType>>(false, true)) Assert.True(x.ToDoBatchAddCount == 0); foreach (var x in session.AllObjects<BTreeSet<EdgeIdVertexId>>(false, true)) Assert.True(x.ToDoBatchAddCount == 0); foreach (var x in session.AllObjects<BTreeMap<EdgeId, VelocityDbList<ElementId>>>(false, true)) Assert.True(x.ToDoBatchAddCount == 0); foreach (var x in session.AllObjects<BTreeMap<string, PropertyType>>(false, true)) Assert.True(x.ToDoBatchAddCount == 0); foreach (var x in session.AllObjects<BTreeMap<string, EdgeType>>(false, true)) Assert.True(x.ToDoBatchAddCount == 0); foreach (var x in session.AllObjects<BTreeMap<string, VertexType>>(false, true)) Assert.True(x.ToDoBatchAddCount == 0); foreach (var x in session.AllObjects<BTreeMap<VertexId, BTreeSet<EdgeIdVertexId>>>(false, true)) Assert.True(x.ToDoBatchAddCount == 0); foreach (var x in session.AllObjects<BTreeMap<VertexType, BTreeMap<VertexId, BTreeSet<EdgeIdVertexId>>>>(false, true)) Assert.True(x.ToDoBatchAddCount == 0); foreach (var x in session.AllObjects<BTreeMap<EdgeType, BTreeMap<VertexType, BTreeMap<VertexId, BTreeSet<EdgeIdVertexId>>>>>(false, true)) Assert.True(x.ToDoBatchAddCount == 0); session.Commit(); Validate(); } }
public void Create1Vertices(bool vertexIdSetPerVertexType) { DataCache.MaximumMemoryUse = 10000000000; // 10 GB bool dirExist = Directory.Exists(systemDir); try { if (Directory.Exists(systemDir)) Directory.Delete(systemDir, true); // remove systemDir from prior runs and all its databases. Directory.CreateDirectory(systemDir); File.Copy(licenseDbFile, Path.Combine(systemDir, "4.odb")); } catch { File.Copy(licenseDbFile, Path.Combine(systemDir, "4.odb")); } using (SessionNoServer session = new SessionNoServer(systemDir, 5000, false, true)) { session.BeginUpdate(); Graph g = new Graph(session, vertexIdSetPerVertexType); session.Persist(g); VertexType userType = g.NewVertexType("User"); VertexType otherType = g.NewVertexType("Other"); PropertyType userNamePropertyType = g.NewVertexProperty(userType, "NAME", DataType.String, PropertyKind.Indexed); VertexType powerUserType = g.NewVertexType("PowerUser", userType); EdgeType userFriendEdgeType = g.NewEdgeType("Friend", true, userType, userType); EdgeType userBestFriendEdgeType = g.NewEdgeType("Best Friend", true, userType, userType, userFriendEdgeType); EdgeType otherEdgeType = g.NewEdgeType("Other", true, userType, userType); PropertyType bestFriendPropertyType = g.NewEdgeProperty(userFriendEdgeType, "START", DataType.DateTime, PropertyKind.Indexed); Vertex kinga = userType.NewVertex(); Vertex robin = userType.NewVertex(); Vertex mats = powerUserType.NewVertex(); Vertex chiran = powerUserType.NewVertex(); Vertex other = otherType.NewVertex(); Edge bestFriend = kinga.AddEdge(userBestFriendEdgeType, robin); Edge otherEdge = kinga.AddEdge(otherEdgeType, robin); DateTime now = DateTime.UtcNow; mats.SetProperty("Address", 1); bestFriend.SetProperty(bestFriendPropertyType, now); kinga.SetProperty(userNamePropertyType, "Kinga"); if (g.VertexIdSetPerType == false) mats.SetProperty(userNamePropertyType, "Mats"); else { try { mats.SetProperty(userNamePropertyType, "Mats"); Assert.Fail("Invalid property for VertexType not handled"); } catch (Exception) { } } try { other.SetProperty(userNamePropertyType, "Mats"); Assert.Fail("Invalid property for VertexType not handled"); } catch (Exception) { } try { otherEdge.SetProperty(bestFriendPropertyType, now); Assert.Fail("Invalid property for VertexType not handled"); } catch (Exception) { } Vertex findMats = userNamePropertyType.GetPropertyVertex("Mats", true); var list = userNamePropertyType.GetPropertyVertices("Mats", true).ToList(); //Edge findWhen = bestFriendPropertyType.GetPropertyEdge(now); //var list2 = bestFriendPropertyType.GetPropertyEdges(now); Console.WriteLine(findMats); // session.Commit(); // session.BeginRead(); PropertyType adressProperty = g.FindVertexProperty(powerUserType, "Address"); Vertex find1 = adressProperty.GetPropertyVertex(1, true); session.Abort(); /*session.BeginUpdate(); g.Unpersist(session); session.Commit(); dirExist = Directory.Exists(systemDir); try { if (Directory.Exists(systemDir)) Directory.Delete(systemDir, true); // remove systemDir from prior runs and all its databases. Directory.CreateDirectory(systemDir); File.Copy(licenseDbFile, Path.Combine(systemDir, "4.odb")); } catch { File.Copy(licenseDbFile, Path.Combine(systemDir, "4.odb")); }*/ } using (SessionNoServer session = new SessionNoServer(systemDir, 5000, false, true)) { session.BeginUpdate(); session.DefaultDatabaseLocation().CompressPages = PageInfo.compressionKind.None; Graph g = new Graph(session, vertexIdSetPerVertexType); session.Persist(g); Graph g2 = new Graph(session); session.Persist(g2); Graph g3 = new Graph(session); session.Persist(g3); UInt32 dbNum = session.DatabaseNumberOf(typeof(Graph)); Graph g4 = (Graph)session.Open(dbNum, 2, 1, true); // g4 == g Graph g5 = (Graph)session.Open(dbNum, 2, 2, true); // g5 == g2 Graph g6 = (Graph)session.Open(dbNum, 2, 3, true); // g6 == g3 for (int i = 4; i < 8; i++) { Graph gt = new Graph(session); session.Persist(gt); } Graph g7 = new Graph(session); Placement place = new Placement(dbNum, 15); session.Persist(place, g7); // SCHEMA VertexType userType = g.NewVertexType("User"); VertexType locationType = g.NewVertexType("Location"); VertexType aVertexType = g.NewVertexType("A"); VertexType bVertexType = g.NewVertexType("B"); VertexType cVertexType = g.NewVertexType("C"); EdgeType uEdge = g.NewEdgeType("unrestricted", true); Vertex aVertex = g.NewVertex(aVertexType); Vertex bVertex = g.NewVertex(bVertexType); Vertex cVertex = g.NewVertex(cVertexType); Edge abEdge = (Edge)aVertex.AddEdge("unrestricted", bVertex); Edge bcEdge = (Edge)aVertex.AddEdge("unrestricted", cVertex); Dictionary<Vertex, HashSet<Edge>> traverse = aVertex.Traverse(uEdge, Direction.Out); abEdge.Remove(); Dictionary<Vertex, HashSet<Edge>> traverse2 = aVertex.Traverse(uEdge, Direction.Out); EdgeType friendEdgeType = g.NewEdgeType("Friend", true, userType, userType); EdgeType userLocationEdgeType = g.NewEdgeType("UserLocation", true, userType, locationType); // DATA Random rand = new Random(5); for (int i = 0; i < numberOfUserVertices / 100; i++) { int vId = rand.Next(numberOfUserVertices); try { if (g.VertexIdSetPerType) userType.GetVertex(vId); else g.GetVertex(vId); try { userType.NewVertex(vId); Assert.Fail(); } catch (VertexAllreadyExistException) { } } catch (VertexDoesNotExistException) { userType.NewVertex(vId); userType.GetVertex(vId); } } for (int i = 0; i < numberOfUserVertices / 10000; i++) { int vId = rand.Next(numberOfUserVertices); try { Vertex v = userType.GetVertex(vId); v.SetProperty("test", 1); } catch (VertexDoesNotExistException) { } } for (int i = 0; i < numberOfUserVertices / 10000; i++) { int vId = rand.Next(numberOfUserVertices); try { Vertex v = userType.GetVertex(vId); userType.RemoveVertex(v); } catch (VertexDoesNotExistException) { } } foreach (Vertex v in userType.GetVertices().ToArray()) userType.RemoveVertex(v); Assert.AreEqual(0, userType.GetVertices().Count()); for (int i = 100000; i < numberOfUserVertices; i++) userType.NewVertex(); for (int i = 1; i < 100000; i++) userType.NewVertex(); for (int i = 1; i < numberOfLocationVertices; i++) locationType.NewVertex(); session.Commit(); session.BeginRead(); foreach (var x in session.AllObjects<BTreeSet<Range<VertexId>>>(false, true)) Assert.True(x.ToDoBatchAddCount == 0); foreach (var x in session.AllObjects<BTreeSet<EdgeType>>(false, true)) Assert.True(x.ToDoBatchAddCount == 0); foreach (var x in session.AllObjects<BTreeSet<EdgeIdVertexId>>(false, true)) Assert.True(x.ToDoBatchAddCount == 0); foreach (var x in session.AllObjects<BTreeMap<EdgeId, VelocityDbList<ElementId>>>(false, true)) Assert.True(x.ToDoBatchAddCount == 0); foreach (var x in session.AllObjects<BTreeMap<string, PropertyType>>(false, true)) Assert.True(x.ToDoBatchAddCount == 0); foreach (var x in session.AllObjects<BTreeMap<string, EdgeType>>(false, true)) Assert.True(x.ToDoBatchAddCount == 0); foreach (var x in session.AllObjects<BTreeMap<string, VertexType>>(false, true)) Assert.True(x.ToDoBatchAddCount == 0); foreach (var x in session.AllObjects<BTreeMap<VertexId, BTreeSet<EdgeIdVertexId>>>(false, true)) Assert.True(x.ToDoBatchAddCount == 0); foreach (var x in session.AllObjects<BTreeMap<VertexType, BTreeMap<VertexId, BTreeSet<EdgeIdVertexId>>>>(false, true)) Assert.True(x.ToDoBatchAddCount == 0); foreach (var x in session.AllObjects<BTreeMap<EdgeType, BTreeMap<VertexType, BTreeMap<VertexId, BTreeSet<EdgeIdVertexId>>>>>(false, true)) Assert.True(x.ToDoBatchAddCount == 0); session.Commit(); Validate(); } }
static readonly string s_systemDir = "Sample4"; // appended to SessionBase.BaseDatabasePath static void Main(string[] args) { try { SessionBase.DefaultCompressPages = PageInfo.compressionKind.LZ4; using (SessionNoServer session = new SessionNoServer(s_systemDir)) { Console.WriteLine("Running with databases in directory: " + session.SystemDirectory); session.BeginUpdate(); // delete (unpersist) all Person objects created in prior run foreach (Person p in session.AllObjects<Person>()) p.Unpersist(session); // delete (unpersist) all VelocityDbList<Person> objects created in prior run foreach (VelocityDbList<Person> l in session.AllObjects<VelocityDbList<Person>>()) l.Unpersist(session); Person robinHood = new Person("Robin", "Hood", 30); Person billGates = new Person("Bill", "Gates", 56, robinHood); Person steveJobs = new Person("Steve", "Jobs", 56, billGates); robinHood.BestFriend = billGates; session.Persist(steveJobs); steveJobs.Friends.Add(billGates); steveJobs.Friends.Add(robinHood); billGates.Friends.Add(billGates); robinHood.Friends.Add(steveJobs); session.Commit(); } using (SessionNoServer session = new SessionNoServer(s_systemDir)) { List<FuzzyStringComparisonOptions> options = new List<FuzzyStringComparisonOptions>(); // Choose which algorithms should weigh in for the comparison options.Add(FuzzyStringComparisonOptions.UseOverlapCoefficient); options.Add(FuzzyStringComparisonOptions.UseLongestCommonSubsequence); options.Add(FuzzyStringComparisonOptions.UseLongestCommonSubstring); options.Add(FuzzyStringComparisonOptions.UseHammingDistance); options.Add(FuzzyStringComparisonOptions.UseJaccardDistance); options.Add(FuzzyStringComparisonOptions.UseJaroDistance); options.Add(FuzzyStringComparisonOptions.UseJaroWinklerDistance); options.Add(FuzzyStringComparisonOptions.UseLevenshteinDistance); options.Add(FuzzyStringComparisonOptions.UseRatcliffObershelpSimilarity); options.Add(FuzzyStringComparisonOptions.UseSorensenDiceDistance); options.Add(FuzzyStringComparisonOptions.UseTanimotoCoefficient); // Choose the relative strength of the comparison - is it almost exactly equal? or is it just close? FuzzyStringComparisonTolerance tolerance = FuzzyStringComparisonTolerance.Normal; session.BeginRead(); foreach (Person p in session.AllObjects<Person>()) { // Get a boolean determination of approximate equality foreach (string firstNameFuzzy in new string[] { "Rob", "Billy", "Mats", "Stevo", "stevo" }) { bool result = firstNameFuzzy.ApproximatelyEquals(p.FirstName, options, tolerance); if (result) Console.WriteLine(firstNameFuzzy + " approximatly equals " + p.FirstName); } } session.Commit(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
public static HashSet<Person> SearchGeoHashIndex(string bootDirectory, double minLat, double minLon, double maxLat, double maxLon) { HashSet<Person> resultSet = new HashSet<Person>(); if (minLat > maxLat) { double t = minLat; minLat = maxLat; maxLat = t; } if (minLon > maxLon) { double t = minLon; minLon = maxLon; maxLon = t; } WGS84Point min = new WGS84Point(minLat, minLon); WGS84Point max = new WGS84Point(maxLat, maxLon); BoundingBox bbox = new BoundingBox(min, max); GeoHashBoundingBoxQuery query = new GeoHashBoundingBoxQuery(bbox); using (SessionNoServer session = new SessionNoServer(bootDirectory)) { session.BeginRead(); BTreeMap<Int64, VelocityDbList<Person>> btreeMap = session.AllObjects<BTreeMap<Int64, VelocityDbList<Person>>>().FirstOrDefault(); foreach (GeoHash hash in query.SearchHashes) { BTreeMapIterator<Int64, VelocityDbList<Person>> itr = btreeMap.Iterator(); itr.GoTo(hash.LongValue); var current = itr.Current(); while (current.Value != null) { GeoHash geoHash = GeoHash.FromLongValue(current.Key); if (geoHash.Within(hash) || (geoHash.SignificantBits > hash.SignificantBits && hash.Within(geoHash))) { foreach (Person person in current.Value) { resultSet.Add(person); } current = itr.Next(); } else break; } } // actual geohash bounding box may be including some that are not within requested bounding box so remove such items if any HashSet<Person> notWithin = new HashSet<Person>(); foreach (Person person in resultSet) { if (person.Lattitude < min.Latitude || person.Lattitude > max.Latitude || person.Longitude < min.Longitude || person.Lattitude > max.Latitude) notWithin.Add(person); } foreach (Person person in notWithin) resultSet.Remove(person); foreach (Person person in resultSet) { Console.WriteLine(person.ToString() + " Lattitude: " + person.Lattitude + " Longitude: " + person.Longitude); } session.Commit(); } return resultSet; }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Session["EmailVerification"] = -1; Session["EmailVerificationEmail"] = "none"; Page.Header.Title = "VelocityDB - Register"; continueUrl = Request.QueryString["ReturnUrl"]; HowFoundRadioButtonList.DataSource = AllHowFound(); HowFoundRadioButtonList.SelectedIndex = 0; HowFoundRadioButtonList.DataBind(); try { using (SessionNoServer session = new SessionNoServer(s_dataPath, 2000, true, true)) { session.BeginUpdate(); Root velocityDbroot = session.AllObjects<Root>(false).FirstOrDefault(); if (velocityDbroot == null) { velocityDbroot = new Root(session, 10000); session.Persist(velocityDbroot); } else { string user = this.User.Identity.Name; if (user != null && user.Length > 0) { CustomerContact lookup = new CustomerContact(user, null); if (velocityDbroot.customersByEmail.TryGetKey(lookup, ref existingCustomer)) { CompanyName.Text = existingCustomer.company; FirstName.Text = existingCustomer.firstName; LastName.Text = existingCustomer.lastName; Email.Text = existingCustomer.email; Address.Text = existingCustomer.address; AddressLine2.Text = existingCustomer.addressLine2; City.Text = existingCustomer.city; ZipCode.Text = existingCustomer.zipCode; State.Text = existingCustomer.state; Country.SelectedValue = existingCustomer.countryCode; Phone.Text = existingCustomer.phone; Fax.Text = existingCustomer.fax; MobilePhone.Text = existingCustomer.mobile; SkypeName.Text = existingCustomer.skypeName; Website.Text = existingCustomer.webSite; UserName.Text = existingCustomer.userName; Password.Text = existingCustomer.password; PasswordConfirm.Text = existingCustomer.password; HowFoundRadioButtonList.SelectedIndex = (int)existingCustomer.howFoundVelocityDb; HowFoundTextBox.Text = existingCustomer.howFoundOther; } } } session.Commit(); } } catch (System.Exception ex) { errors.Text = ex.ToString(); } } }
public void OneMillionFindSingleRecordInTheMiddleNoLinq() { using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginRead(); var computerFileDataEnum = session.AllObjects<ComputerFileData>(); foreach (ComputerFileData computerFileData in computerFileDataEnum) { if (computerFileData.FileID == 500000) break; // found it } session.Commit(); } }
public void VerifyOpenIssueTrackerCacheOff() { using (SessionNoServer session = new SessionNoServer(systemDir, 2000, true, false)) { session.BeginUpdate(); IssueTracker issueTracker = session.AllObjects<IssueTracker>(false).FirstOrDefault(); session.Commit(); } }
public void Create() { using (SessionBase session = new SessionNoServer(systemDir)) { session.BeginUpdate(); WeakReferenceList<BaseClassA> baseClassAList = new WeakReferenceList<BaseClassA>(); session.Persist(baseClassAList); for (int i = 0; i < 5; i++) { var classA = new BaseClassA(); session.Persist(classA); baseClassAList.Add(classA); } WeakReferenceList<ClassB> classBList = new WeakReferenceList<ClassB>(); session.Persist(classBList); for (int i = 0; i < 5; i++) { var classB = new ClassB(); classBList.Add(classB); baseClassAList.Add(classB); } var aList = (from aClass in baseClassAList orderby aClass.RandomOrder select aClass).ToList(); WeakReferenceList < ClassC > classCList = new WeakReferenceList<ClassC>(); session.Persist(classCList); for (int i = 0; i < 5; i++) { var classC = new ClassC(); classCList.Add(classC); } ClassD d = new ClassD(); session.Persist(d); for (int i = 0; i < 5; i++) { var classFromB = new ClassFromB(); session.Persist(classFromB); } session.Commit(); } using (SessionBase session = new SessionNoServer(systemDir)) { session.BeginRead(); Assert.AreEqual(5, session.AllObjects<BaseClassA>(false).Count); int ct = session.AllObjects<BaseClassA>(true).Skip(5).Count(); Assert.Less(5, ct); object obj = session.AllObjects<BaseClassA>(true).Skip(5).First(); Assert.NotNull(obj); obj = session.AllObjects<BaseClassA>(true).Skip(6).First(); Assert.NotNull(obj); Assert.AreEqual(20, session.AllObjects<BaseClassA>().Count); Assert.AreEqual(5, session.AllObjects<ClassB>(false).Count); Assert.AreEqual(10, session.AllObjects<ClassB>().Count); obj = session.AllObjects<ClassB>(true).Skip(5).First(); Assert.NotNull(obj); obj = session.AllObjects<ClassB>(true).Skip(4).First(); Assert.NotNull(obj); obj = session.AllObjects<ClassB>(true).Skip(6).First(); Assert.NotNull(obj); Assert.AreEqual(5, session.AllObjects<ClassC>(false).Count); Assert.AreEqual(5, session.AllObjects<ClassC>().Count); ct = 0; foreach (var o in session.AllObjects<BaseClassA>(false)) ++ct; Assert.AreEqual(5, ct); ct = 0; foreach (var o in session.AllObjects<BaseClassA>()) ++ct; Assert.AreEqual(20, ct); ct = 0; foreach (var o in session.AllObjects<ClassB>()) ++ct; Assert.AreEqual(10, ct); ct = 0; foreach (var o in session.AllObjects<ClassC>()) ++ct; Assert.AreEqual(5, ct); ct = 0; foreach (var o in session.AllObjects<IOptimizedPersistable>()) ++ct; int ct2 = 0; foreach (var o in session.AllObjects<OptimizedPersistable>()) ++ct2; int ct3 = 0; foreach (var o in session.AllObjects<IHasClassName>()) ++ct3; session.Commit(); } using (SessionBase session = new SessionNoServer(systemDir)) { session.BeginUpdate(); foreach (var o in session.AllObjects<WeakReferenceList<BaseClassA>>()) o.Unpersist(session); foreach (var o in session.AllObjects<WeakReferenceList<ClassB>>()) o.Unpersist(session); foreach (var o in session.AllObjects<WeakReferenceList<ClassC>>()) o.ClearAndUnpersistContainedObjects(session); foreach (var o in session.AllObjects<IHasClassName>()) session.Unpersist(o); Assert.AreEqual(0, session.AllObjects<WeakReferenceList<BaseClassA>>().Count); Assert.AreEqual(0, session.AllObjects<BaseClassA>().Count); Assert.AreEqual(0, session.AllObjects<IHasClassName>().Count); session.Commit(); } }
public void UpdateProject(EditedProject newValues) { try { string dataPath = HttpContext.Current.Server.MapPath("~/tracker"); using (SessionNoServer session = new SessionNoServer(dataPath, 2000, true, true)) { session.BeginUpdate(); if (newValues.Id == 0) { if (newValues.Name == null) Console.WriteLine("Project null storeName detected in Update method"); else { IssueTracker issueTracker = session.AllObjects<IssueTracker>(false).FirstOrDefault(); User user = lookupUser(issueTracker, session); Project newProject = new Project(user, newValues.Name, newValues.Description); session.Persist(newProject); issueTracker.ProjectSet.Add(newProject); } } else { Project existingProject = (Project)session.Open(newValues.Id); existingProject.Name = newValues.Name; existingProject.Description = newValues.Description; } session.Commit(); s_sharedReadOnlySession.ForceDatabaseCacheValidation(); } } catch (System.Exception ex) { this.errorLabel.Text = ex.ToString(); } }
public void Create4Projects(int numberOfProjects) { Project project = null; Project priorProject = null; for (int i = 0; i < numberOfProjects; i++) using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginUpdate(); IssueTracker issueTracker = session.AllObjects<IssueTracker>(false).FirstOrDefault(); User user = issueTracker.UserSet.Keys[rand.Next(issueTracker.UserSet.Keys.Count - 1)]; string p = "project" + i.ToString(); string d = "pdescription" + i.ToString(); project = new Project(user, p, d); session.Persist(project); priorProject = project; issueTracker.ProjectSet.Add(project); session.Commit(); } }
User lookupUser(IssueTracker issueTracker, SessionBase session) { string userEmail = this.User.Identity.Name; User user = new User(userEmail); string dataPath = HttpContext.Current.Server.MapPath("~/Database"); if (!issueTracker.UserSet.TryGetValue(user, ref user)) { CustomerContact existingCustomer = null; string firstName = null; string lastName = null; string userName = null; try { using (SessionNoServer session2 = new SessionNoServer(dataPath, 2000, true, true)) { session2.BeginRead(); Root velocityDbroot = session2.AllObjects<Root>(false).FirstOrDefault(); CustomerContact lookup = new CustomerContact(userEmail, null); velocityDbroot.customersByEmail.TryGetKey(lookup, ref existingCustomer); session2.Commit(); firstName = existingCustomer.FirstName; lastName = existingCustomer.LastName; userName = existingCustomer.UserName; } } catch (System.Exception ex) { this.errorLabel.Text = ex.ToString(); } user = new User(null, userEmail, firstName, lastName, userName); session.Persist(user); issueTracker.UserSet.Add(user); } return user; }
static void QueryGraph() { using (SessionNoServer session = new SessionNoServer(systemDir)) { // Start a read only transaction session.BeginRead(); Graph g = Graph.Open(session); // Cache SCHEMA VertexType movieType = g.FindVertexType("Movie"); PropertyType movieTitleType = movieType.FindProperty("title"); VertexType actorType = g.FindVertexType("Actor"); PropertyType actorNameType = actorType.FindProperty("name"); // How many vertices do we have? Console.WriteLine("Number of Vertices: " + g.CountVertices()); // Find a movie by name Vertex movie = movieTitleType.GetPropertyVertex("The Matrix"); // Get all actors var actors = actorType.GetVertices(); // Count the actors int actorCount = actors.Count(); Console.WriteLine("Number of Actors: " + actorCount); // Get only the actors whose names end with “s” foreach (Vertex vertex in actors) { string actorName = (string) actorNameType.GetPropertyValue(vertex.VertexId); if (actorName.EndsWith("s")) Console.WriteLine("Found actor with name ending with \"s\" " + actorName); } // Get a count of property types var properties = session.AllObjects<PropertyType>(); Console.WriteLine("Number of Property types: " + properties.Count()); // All vertices and their edges var edges = g.GetEdges(); int edgeCount = edges.Count(); session.Commit(); } }
protected void RegisterButton_Click(object sender, EventArgs e) { try { using (SessionNoServer session = new SessionNoServer(s_dataPath, 2000, true, true)) { session.BeginUpdate(); CustomerContact customer = new CustomerContact(CompanyName.Text, FirstName.Text, LastName.Text, Email.Text, Address.Text, AddressLine2.Text, City.Text, ZipCode.Text, State.Text, Country.SelectedItem.Text, Country.SelectedItem.Value, Phone.Text, Fax.Text, MobilePhone.Text, SkypeName.Text, Website.Text, UserName.Text, Password.Text, HowFoundTextBox.Text, HowFoundRadioButtonList.SelectedIndex, session); Root root = session.AllObjects<Root>(false).FirstOrDefault(); CustomerContact lookup; string user = this.User.Identity.Name; if (user != null && user.Length > 0) { lookup = new CustomerContact(user, null); root.customersByEmail.TryGetKey(lookup, ref existingCustomer); } else { lookup = new CustomerContact(customer.email, customer.userName); if (!root.customersByEmail.TryGetKey(lookup, ref existingCustomer)) root.customersByUserName.TryGetKey(lookup, ref existingCustomer); } if (existingCustomer != null) { existingCustomer.Update(); if (existingCustomer.email != customer.email) { string verifiedEmail = (string)Session["EmailVerificationEmail"]; int emailVerification = (int)Session["EmailVerification"]; if (Request.IsLocal == false) { if (emailVerification < 0 || verifiedEmail != customer.email) { errors.Text = "Email was not verified for new user registration"; session.Abort(); return; } int enteredVerificationNumber; int.TryParse(EmailVerification.Text, out enteredVerificationNumber); if (emailVerification != enteredVerificationNumber) { errors.Text = "Entered Email Verification number is " + enteredVerificationNumber + " does match the emailed verification number: " + emailVerification; Session["EmailVerification"] = -1; session.Abort(); return; } } if (existingCustomer.password != customer.password && user != existingCustomer.email) { errors.Text = "Entered Email address already registered"; session.Abort(); return; } existingCustomer.priorVerifiedEmailSet.Add(existingCustomer.email); root.customersByEmail.Remove(existingCustomer); existingCustomer.email = customer.email; root.customersByEmail.Add(existingCustomer); } if (existingCustomer.userName != customer.userName) { lookup = new CustomerContact(user, customer.userName); if (root.customersByUserName.TryGetKey(lookup, ref lookup)) { errors.Text = "Entered User Name is already in use"; session.Abort(); return; } // remove and add to get correct sorting order root.customersByUserName.Remove(existingCustomer); existingCustomer.userName = customer.userName; root.customersByUserName.Add(existingCustomer); } existingCustomer.company = customer.company; existingCustomer.firstName = customer.firstName; existingCustomer.lastName = customer.lastName; existingCustomer.address = customer.address; existingCustomer.addressLine2 = customer.addressLine2; existingCustomer.city = customer.city; existingCustomer.zipCode = customer.zipCode; existingCustomer.state = customer.state; existingCustomer.country = Country.SelectedItem.Text; existingCustomer.countryCode = Country.SelectedItem.Value; existingCustomer.phone = customer.phone; existingCustomer.fax = customer.fax; existingCustomer.mobile = customer.mobile; existingCustomer.skypeName = customer.skypeName; existingCustomer.webSite = customer.webSite; existingCustomer.password = customer.password; existingCustomer.howFoundOther = customer.howFoundOther; existingCustomer.howFoundVelocityDb = customer.howFoundVelocityDb; } else { //if (Request.IsLocal == false) //{ // string verifiedEmail = (string)Session["EmailVerificationEmail"]; //int emailVerification = (int)Session["EmailVerification"]; //if (emailVerification < 0 || verifiedEmail != customer.email) //{ // errors.Text = "Email was not verified for new user registration"; // session.Abort(); // return; //} //int enteredVerificationNumber; //int.TryParse(EmailVerification.Text, out enteredVerificationNumber); //if (emailVerification != enteredVerificationNumber) //{ // errors.Text = "Entered Email Verification number is " + enteredVerificationNumber + " does match the emailed verification number: " + emailVerification; // Session["EmailVerification"] = -1; // session.Abort(); // return; //} //} customer.idNumber = root.NewCustomerNumber(); session.Persist(customer); root.customersByEmail.Add(customer); root.customersByUserName.Add(customer); } session.Commit(); string redirectUrl = FormsAuthentication.GetRedirectUrl(Email.Text, false); try { string path; MailMessage message = new MailMessage("*****@*****.**", "*****@*****.**"); if (existingCustomer == null) { path = HttpContext.Current.Server.MapPath("~/Save") + "/new" + DateTime.Now.Ticks + ".txt"; message.Subject = "VelocityWeb new prospect: " + customer.Email; } else { customer = existingCustomer; path = HttpContext.Current.Server.MapPath("~/Save") + "/updated" + DateTime.Now.Ticks + ".txt"; message.Subject = "VelocityWeb updated prospect: " + customer.Email; } using (System.IO.StreamWriter file = new System.IO.StreamWriter(path)) { file.Write("{0}\t", "Email"); file.Write("{0}\t", "FirstName"); file.Write("{0}\t", "LastName"); file.Write("{0}\t", "Address"); file.Write("{0}\t", "Address2"); file.Write("{0}\t", "City"); file.Write("{0}\t", "Company"); file.Write("{0}\t", "Country"); file.Write("{0}\t", "countryCode"); file.Write("{0}\t", "Fax"); file.Write("{0}\t", "HowFoundUs"); file.Write("{0}\t", "HowFoundUsOther"); file.Write("{0}\t", "Mobile"); file.Write("{0}\t", "Password"); file.Write("{0}\t", "Phone"); file.Write("{0}\t", "Skype"); file.Write("{0}\t", "State"); file.Write("{0}\t", "UserName"); file.Write("{0}\t", "WebSite"); file.WriteLine("{0}\t", "ZipCode"); file.Write("{0}\t", customer.Email); file.Write("{0}\t", customer.FirstName); file.Write("{0}\t", customer.LastName); file.Write("{0}\t", customer.Address); file.Write("{0}\t", customer.Address2); file.Write("{0}\t", customer.City); file.Write("{0}\t", customer.Company); file.Write("{0}\t", customer.Country); file.Write("{0}\t", customer.countryCode); file.Write("{0}\t", customer.Fax); file.Write("{0}\t", customer.HowFoundUs); file.Write("{0}\t", customer.HowFoundUsOther); file.Write("{0}\t", customer.Mobile); file.Write("{0}\t", customer.Password); file.Write("{0}\t", customer.Phone); file.Write("{0}\t", customer.Skype); file.Write("{0}\t", customer.State); file.Write("{0}\t", customer.UserName); file.Write("{0}\t", customer.WebSite); file.WriteLine("{0}\t", customer.ZipCode); } Session["UserName"] = customer.UserName; Session["Email"] = Email.Text; Session["FirstName"] = customer.FirstName; Session["LastName"] = customer.LastName; message.Body = path; Attachment data = new Attachment(path); message.Attachments.Add(data); SmtpClient client = new SmtpClient("smtpout.secureserver.net", 80); System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential("*****@*****.**", "xxxx"); // Add credentials if the SMTP server requires them. client.Credentials = SMTPUserInfo; client.Send(message); } catch (System.Exception ex) { string errorPath = HttpContext.Current.Server.MapPath("~/Errors"); using (StreamWriter outfile = new StreamWriter(errorPath + @"\errors.txt", true)) { outfile.Write(ex.ToString()); } } if (redirectUrl == null || redirectUrl.Length == 0) Response.Redirect("~/Secure/Issues.aspx"); FormsAuthentication.RedirectFromLoginPage(Email.Text, false); } } catch (System.Exception ex) { errors.Text = ex.ToString(); } }