/// <summary> /// Search the index. /// </summary> /// <param name="terms">Search terms.</param> /// <param name="indexStart">Index of results from which to begin returning records.</param> /// <param name="maxResults">Maximum number of records to return.</param> /// <param name="filter">Database filters.</param> /// <returns>List of documents.</returns> public List <Document> Search(List <string> terms, int?indexStart, int?maxResults, DbExpression filter) { if (terms == null || terms.Count < 1) { throw new ArgumentNullException(nameof(terms)); } #region Retrieve-Document-GUIDs List <string> guids = GetDocumentGuidsByTerms(terms, indexStart, maxResults, filter); if (guids == null || guids.Count < 1) { Log("no document GUIDs found for the supplied terms"); return(new List <Document>()); } #endregion #region Retrieve-and-Return DbExpression e = new DbExpression(_ORM.GetColumnName <Document>(nameof(Document.GUID)), DbOperators.In, guids); List <Document> ret = _ORM.SelectMany <Document>(indexStart, maxResults, e); Log("returning " + ret.Count + " documents for search query"); return(ret); #endregion }
internal List <User> GetUsers() { DbExpression e = new DbExpression( _ORM.GetColumnName <User>(nameof(User.Id)), DbOperators.GreaterThan, 0); return(_ORM.SelectMany <User>(e)); }
/// <summary> /// List the objects stored in the index. /// </summary> /// <param name="prefix">Prefix upon which to match object keys.</param> /// <param name="indexStart">The index (DedupeObject.Id) from which to begin the enumeration.</param> /// <param name="maxResults">Maximum number of results to retrieve.</param> /// <return>Enumeration result.</return> public override EnumerationResult ListObjects(string prefix, int indexStart, int maxResults) { if (indexStart < 0) { throw new ArgumentException("Starting index must be zero or greater."); } if (maxResults < 1 || maxResults > 100) { throw new ArgumentException("Max results must be greater than zero and less than or equal to 100."); } EnumerationResult ret = new EnumerationResult(prefix, indexStart, indexStart, maxResults, new List <DedupeObject>()); DbExpression e = new DbExpression( _ORM.GetColumnName <DedupeObject>(nameof(DedupeObject.Id)), DbOperators.GreaterThan, indexStart); if (!String.IsNullOrEmpty(prefix)) { e.PrependAnd( _ORM.GetColumnName <DedupeObject>(nameof(DedupeObject.Key)), DbOperators.StartsWith, prefix); } List <DedupeObject> objects = _ORM.SelectMany <DedupeObject>(null, maxResults, e); if (objects != null && objects.Count > 0) { foreach (DedupeObject obj in objects) { obj.Chunks = GetChunks(obj.Key); obj.ObjectMap = GetObjectMap(obj.Key); if (obj.ObjectMap != null && obj.ObjectMap.Count > 0) { obj.ObjectMap = obj.ObjectMap.OrderBy(o => o.ChunkAddress).ToList(); } ret.Objects.Add(obj); } } if (objects != null && objects.Count == maxResults) { ret.NextIndexStart = objects[(objects.Count - 1)].Id; } return(ret); }
internal List <UrlLock> GetReadLocks() { DbExpression e = new DbExpression( _ORM.GetColumnName <UrlLock>(nameof(UrlLock.Id)), DbOperators.GreaterThan, 0); e.PrependAnd(new DbExpression( _ORM.GetColumnName <UrlLock>(nameof(UrlLock.LockType)), DbOperators.Equals, LockType.Read)); return(_ORM.SelectMany <UrlLock>(e)); }
/// <summary> /// Authorize a user's request against a resource by operation type. /// </summary> /// <param name="username">The name of the user.</param> /// <param name="resource">The resource.</param> /// <param name="operation">The type of operation.</param> /// <returns>True if authorized.</returns> public bool Authorize(string username, string resource, string operation) { if (String.IsNullOrEmpty(username)) { throw new ArgumentNullException(nameof(username)); } if (String.IsNullOrEmpty(resource)) { throw new ArgumentNullException(nameof(resource)); } if (String.IsNullOrEmpty(operation)) { throw new ArgumentNullException(nameof(operation)); } DbExpression e1 = new DbExpression(_ORM.GetColumnName <UserRole>(nameof(UserRole.Username)), DbOperators.Equals, username); List <UserRole> u = _ORM.SelectMany <UserRole>(e1); List <string> r = new List <string>(); if (u != null && u.Count > 0) { foreach (UserRole role in u) { r.Add(role.Rolename); } } if (r.Count > 0) { r = r.Distinct().ToList(); DbExpression e2 = new DbExpression(_ORM.GetColumnName <RolePermission>(nameof(RolePermission.Rolename)), DbOperators.In, r); List <RolePermission> p = _ORM.SelectMany <RolePermission>(e2); if (p != null && p.Count > 0) { return(p.Any(rp => rp.Allow)); } } return(DefaultPermit); }
internal void RemoveReadLock(UrlLock urlLock) { if (urlLock == null) { throw new ArgumentNullException(nameof(urlLock)); } DbExpression e = new DbExpression( _ORM.GetColumnName <UrlLock>(nameof(UrlLock.Url)), DbOperators.Equals, urlLock.Url); e.PrependAnd(new DbExpression( _ORM.GetColumnName <UrlLock>(nameof(UrlLock.LockType)), DbOperators.Equals, urlLock.LockType)); List <UrlLock> locks = _ORM.SelectMany <UrlLock>(e); if (locks != null && locks.Count > 0) { foreach (UrlLock curr in locks) { _ORM.Delete <UrlLock>(curr); } } }
internal List <ApiKey> GetApiKeys() { DbExpression e = new DbExpression( _ORM.GetColumnName <ApiKey>(nameof(ApiKey.Id)), DbOperators.GreaterThan, 0); return(_ORM.SelectMany <ApiKey>(e)); }
static void Main(string[] args) { try { #region Setup Console.Write("DB type [sqlserver|mysql|postgresql|sqlite]: "); _DbType = Console.ReadLine(); if (String.IsNullOrEmpty(_DbType)) { return; } _DbType = _DbType.ToLower(); if (_DbType.Equals("sqlserver") || _DbType.Equals("mysql") || _DbType.Equals("postgresql")) { Console.Write("User: "******"Password: "******"sqlserver": _Settings = new DatabaseSettings(DbTypes.SqlServer, "localhost", 1433, _Username, _Password, "test"); break; case "mysql": _Settings = new DatabaseSettings(DbTypes.Mysql, "localhost", 3306, _Username, _Password, "test"); break; case "postgresql": _Settings = new DatabaseSettings(DbTypes.Postgresql, "localhost", 5432, _Username, _Password, "test"); break; default: return; } } else if (_DbType.Equals("sqlite")) { Console.Write("Filename: "); _Filename = Console.ReadLine(); if (String.IsNullOrEmpty(_Filename)) { return; } _Settings = new DatabaseSettings(_Filename); } else { Console.WriteLine("Invalid database type."); return; } _Orm = new WatsonORM(_Settings); _Orm.InitializeDatabase(); DebugSettings debug = new DebugSettings(); debug.DatabaseQueries = true; debug.DatabaseResults = true; _Orm.Logger = Logger; _Orm.Debug = debug; _Orm.InitializeTable(typeof(Person)); _Orm.TruncateTable(typeof(Person)); Console.WriteLine("Using table: " + _Orm.GetTableName(typeof(Person))); #endregion #region Insert-Records Person p1 = new Person("Abraham", "Lincoln", Convert.ToDateTime("1/1/1980"), null, 42, null, "initial notes p1", PersonType.Human, null, false); Person p2 = new Person("Ronald", "Reagan", Convert.ToDateTime("2/2/1981"), Convert.ToDateTime("3/3/1982"), 43, 43, "initial notes p2", PersonType.Cat, PersonType.Cat, true); Person p3 = new Person("George", "Bush", Convert.ToDateTime("3/3/1982"), null, 44, null, "initial notes p3", PersonType.Dog, PersonType.Dog, false); Person p4 = new Person("Barack", "Obama", Convert.ToDateTime("4/4/1983"), Convert.ToDateTime("5/5/1983"), 45, null, "initial notes p4", PersonType.Human, null, true); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Creating p1"); p1 = _Orm.Insert <Person>(p1); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Creating p2"); p2 = _Orm.Insert <Person>(p2); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Creating p3"); p3 = _Orm.Insert <Person>(p3); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Creating p4"); p4 = _Orm.Insert <Person>(p4); #endregion #region Insert-Multiple-Records for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Creating p5 through p8"); Person p5 = new Person("Jason", "Christner", Convert.ToDateTime("4/21/2020"), null, 1, null, "initial notes p5", PersonType.Human, null, false); Person p6 = new Person("Maria", "Sanchez", Convert.ToDateTime("10/10/1982"), Convert.ToDateTime("10/10/1982"), 38, null, "initial notes p6", PersonType.Cat, PersonType.Cat, true); Person p7 = new Person("Eddie", "Van Halen", Convert.ToDateTime("3/3/1982"), null, 44, null, "initial notes p7", PersonType.Dog, PersonType.Dog, false); Person p8 = new Person("Steve", "Vai", Convert.ToDateTime("4/4/1983"), Convert.ToDateTime("5/5/1983"), 45, null, "initial notes p8", PersonType.Human, null, true); List <Person> people = new List <Person> { p5, p6, p7, p8 }; _Orm.InsertMultiple <Person>(people); #endregion #region Exists-Count-Sum for (int i = 0; i < 8; i++) { Console.WriteLine(""); } DbExpression existsExpression = new DbExpression(_Orm.GetColumnName <Person>(nameof(Person.Id)), DbOperators.GreaterThan, 0); Console.WriteLine("| Checking existence of records: " + _Orm.Exists <Person>(existsExpression)); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } DbExpression countExpression = new DbExpression(_Orm.GetColumnName <Person>(nameof(Person.Id)), DbOperators.GreaterThan, 2); Console.WriteLine("| Checking count of records: " + _Orm.Count <Person>(countExpression)); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Checking sum of ages: " + _Orm.Sum <Person>(_Orm.GetColumnName <Person>(nameof(Person.Age)), existsExpression)); #endregion #region Select for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Selecting many by column name"); DbExpression eSelect1 = new DbExpression("id", DbOperators.GreaterThan, 0); List <Person> selectedList1 = _Orm.SelectMany <Person>(null, null, eSelect1); Console.WriteLine("| Retrieved: " + selectedList1.Count + " records"); foreach (Person curr in selectedList1) { Console.WriteLine(" | " + curr.ToString()); } for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Selecting many by property name"); DbExpression eSelect2 = new DbExpression( _Orm.GetColumnName <Person>(nameof(Person.FirstName)), DbOperators.Equals, "Abraham"); List <Person> selectedList2 = _Orm.SelectMany <Person>(null, null, eSelect2); Console.WriteLine("| Retrieved: " + selectedList2.Count + " records"); foreach (Person curr in selectedList2) { Console.WriteLine(" | " + curr.ToString()); } for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Selecting by ID"); Person pSelected = _Orm.SelectByPrimaryKey <Person>(3); Console.WriteLine("| Selected: " + pSelected.ToString()); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Selecting first by column name"); DbExpression eSelect3 = new DbExpression("id", DbOperators.Equals, 4); pSelected = _Orm.SelectFirst <Person>(eSelect3); Console.WriteLine("| Selected: " + pSelected.ToString()); #endregion #region Update-Records for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Updating p1"); p1.Notes = "updated notes p1"; p1 = _Orm.Update <Person>(p1); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Updating p2"); p2.Notes = "updated notes p2"; p2 = _Orm.Update <Person>(p2); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Updating p3"); p3.Notes = "updated notes p3"; p3 = _Orm.Update <Person>(p3); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Updating p4"); p4.Notes = "updated notes p4"; p4 = _Orm.Update <Person>(p4); #endregion #region Update-Many-Records for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Updating many records"); Dictionary <string, object> updateVals = new Dictionary <string, object>(); updateVals.Add(_Orm.GetColumnName <Person>("Notes"), "Updated during update many!"); _Orm.UpdateMany <Person>(eSelect1, updateVals); #endregion #region Select for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Selecting many, test 1"); selectedList1 = _Orm.SelectMany <Person>(null, null, eSelect1); Console.WriteLine("| Retrieved: " + selectedList1.Count + " records"); foreach (Person curr in selectedList1) { Console.WriteLine(" | " + curr.ToString()); } for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Selecting by ID"); pSelected = _Orm.SelectByPrimaryKey <Person>(3); Console.WriteLine("| Selected: " + pSelected.ToString()); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Selecting first"); pSelected = _Orm.SelectFirst <Person>(eSelect2); Console.WriteLine("| Selected: " + pSelected.ToString()); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Selecting between, test 1"); DbExpression eSelect4 = DbExpression.Between("id", new List <object> { 2, 4 }); selectedList1 = _Orm.SelectMany <Person>(null, null, eSelect4); Console.WriteLine("| Retrieved: " + selectedList1.Count + " records"); foreach (Person curr in selectedList1) { Console.WriteLine(" | " + curr.ToString()); } for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Selecting by persontype"); DbExpression eSelect5 = new DbExpression("persontype", DbOperators.Equals, PersonType.Dog); selectedList1 = _Orm.SelectMany <Person>(null, null, eSelect5); Console.WriteLine("| Retrieved: " + selectedList1.Count + " records"); foreach (Person curr in selectedList1) { Console.WriteLine(" | " + curr.ToString()); } for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Selecting handsome people"); DbExpression eSelect6 = new DbExpression("ishandsome", DbOperators.Equals, true); selectedList1 = _Orm.SelectMany <Person>(null, null, eSelect6); Console.WriteLine("| Retrieved: " + selectedList1.Count + " records"); foreach (Person curr in selectedList1) { Console.WriteLine(" | " + curr.ToString()); } for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Selecting by reverse ID order"); DbExpression eSelect7 = new DbExpression("id", DbOperators.GreaterThan, 0); DbResultOrder[] resultOrder = new DbResultOrder[1]; resultOrder[0] = new DbResultOrder("id", DbOrderDirection.Descending); selectedList1 = _Orm.SelectMany <Person>(null, null, eSelect7, resultOrder); Console.WriteLine("| Retrieved: " + selectedList1.Count + " records"); foreach (Person curr in selectedList1) { Console.WriteLine(" | " + curr.ToString()); } #endregion #region Exception for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Catching exception and displaying query"); try { _Orm.Query("SELECT * FROM person ((("); } catch (Exception e) { Console.WriteLine("Exception: " + e.Message); Console.WriteLine("Query : " + e.Data["Query"]); } #endregion #region Delete-Records for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Deleting p1"); _Orm.Delete <Person>(p1); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Deleting p2"); _Orm.DeleteByPrimaryKey <Person>(2); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Deleting p3 and p4"); DbExpression eDelete = new DbExpression("id", DbOperators.GreaterThan, 2); _Orm.DeleteMany <Person>(eDelete); #endregion } catch (Exception e) { // Get stack trace for the exception with source file information var st = new StackTrace(e, true); // Get the top stack frame var frame = st.GetFrame(0); // Get the line number from the stack frame var line = frame.GetFileLineNumber(); Console.WriteLine("Stack trace:" + Environment.NewLine + SerializeJson(st, true)); Console.WriteLine("Stack frame: " + Environment.NewLine + SerializeJson(st, true)); Console.WriteLine("Line number: " + line); Console.WriteLine("Exception: " + Environment.NewLine + SerializeJson(e, true)); } Console.WriteLine(""); Console.WriteLine("Press ENTER to exit"); Console.ReadLine(); }
static void Main(string[] args) { try { #region Setup Console.Write("Filename: "); _Filename = Console.ReadLine(); if (String.IsNullOrEmpty(_Filename)) { return; } _Settings = new DatabaseSettings(_Filename); _Orm = new WatsonORM(_Settings); _Orm.InitializeDatabase(); DebugSettings debug = new DebugSettings(); debug.DatabaseQueries = true; debug.DatabaseResults = true; _Orm.Logger = Logger; _Orm.Debug = debug; _Orm.InitializeTable(typeof(Person)); _Orm.TruncateTable(typeof(Person)); Console.WriteLine("Using table: " + _Orm.GetTableName(typeof(Person))); #endregion #region Create-and-Store-Records DateTimeOffset localTime = new DateTimeOffset(Convert.ToDateTime("1/1/2021")); Person p1 = new Person("Abraham", "Lincoln", Convert.ToDateTime("1/1/1980"), null, localTime, null, 42, null, "initial notes p1", PersonType.Human, null, false); Person p2 = new Person("Ronald", "Reagan", Convert.ToDateTime("2/2/1981"), Convert.ToDateTime("3/3/1982"), localTime, localTime, 43, 43, "initial notes p2", PersonType.Cat, PersonType.Cat, true); Person p3 = new Person("George", "Bush", Convert.ToDateTime("3/3/1982"), null, localTime, null, 44, null, "initial notes p3", PersonType.Dog, PersonType.Dog, false); Person p4 = new Person("Barack", "Obama", Convert.ToDateTime("4/4/1983"), Convert.ToDateTime("5/5/1983"), localTime, localTime, 45, null, "initial notes p4", PersonType.Human, null, true); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Creating p1"); p1 = _Orm.Insert <Person>(p1); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Creating p2"); p2 = _Orm.Insert <Person>(p2); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Creating p3"); p3 = _Orm.Insert <Person>(p3); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Creating p4"); p4 = _Orm.Insert <Person>(p4); #endregion #region Select for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Selecting many by column name"); DbExpression eSelect1 = new DbExpression("id", DbOperators.GreaterThan, 0); List <Person> selectedList1 = _Orm.SelectMany <Person>(null, null, eSelect1); Console.WriteLine("| Retrieved: " + selectedList1.Count + " records"); foreach (Person curr in selectedList1) { Console.WriteLine(" | " + curr.ToString()); } for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Selecting many by property name"); DbExpression eSelect2 = new DbExpression( _Orm.GetColumnName <Person>(nameof(Person.FirstName)), DbOperators.Equals, "Abraham"); List <Person> selectedList2 = _Orm.SelectMany <Person>(null, null, eSelect2); Console.WriteLine("| Retrieved: " + selectedList2.Count + " records"); foreach (Person curr in selectedList2) { Console.WriteLine(" | " + curr.ToString()); } for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Selecting by ID"); Person pSelected = _Orm.SelectByPrimaryKey <Person>(3); Console.WriteLine("| Selected: " + pSelected.ToString()); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Selecting first by column name"); DbExpression eSelect3 = new DbExpression("id", DbOperators.Equals, 4); pSelected = _Orm.SelectFirst <Person>(eSelect3); Console.WriteLine("| Selected: " + pSelected.ToString()); #endregion #region Update-Records for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Updating p1"); p1.Notes = "updated notes p1"; p1.NullableType = null; p1 = _Orm.Update <Person>(p1); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Updating p2"); p2.Notes = "updated notes p2"; p2.NullableType = null; p2 = _Orm.Update <Person>(p2); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Updating p3"); p3.Notes = "updated notes p3"; p3.NullableType = null; p3 = _Orm.Update <Person>(p3); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Updating p4"); p4.Notes = "updated notes p4"; p4.NullableType = null; p4 = _Orm.Update <Person>(p4); #endregion #region Update-Many-Records for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Updating many records"); Dictionary <string, object> updateVals = new Dictionary <string, object>(); updateVals.Add(_Orm.GetColumnName <Person>("Notes"), "Updated during update many!"); _Orm.UpdateMany <Person>(eSelect1, updateVals); #endregion #region Select for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Selecting many, test 1"); selectedList1 = _Orm.SelectMany <Person>(null, null, eSelect1); Console.WriteLine("| Retrieved: " + selectedList1.Count + " records"); foreach (Person curr in selectedList1) { Console.WriteLine(" | " + curr.ToString()); } for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Selecting by ID"); pSelected = _Orm.SelectByPrimaryKey <Person>(3); Console.WriteLine("| Selected: " + pSelected.ToString()); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Selecting first"); pSelected = _Orm.SelectFirst <Person>(eSelect2); Console.WriteLine("| Selected: " + pSelected.ToString()); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Selecting between, test 1"); DbExpression eSelect4 = DbExpression.Between("id", new List <object> { 2, 4 }); selectedList1 = _Orm.SelectMany <Person>(null, null, eSelect4); Console.WriteLine("| Retrieved: " + selectedList1.Count + " records"); foreach (Person curr in selectedList1) { Console.WriteLine(" | " + curr.ToString()); } for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Selecting by persontype"); DbExpression eSelect5 = new DbExpression("persontype", DbOperators.Equals, PersonType.Dog); selectedList1 = _Orm.SelectMany <Person>(null, null, eSelect5); Console.WriteLine("| Retrieved: " + selectedList1.Count + " records"); foreach (Person curr in selectedList1) { Console.WriteLine(" | " + curr.ToString()); } for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Selecting handsome people"); DbExpression eSelect6 = new DbExpression("ishandsome", DbOperators.Equals, true); selectedList1 = _Orm.SelectMany <Person>(null, null, eSelect6); Console.WriteLine("| Retrieved: " + selectedList1.Count + " records"); foreach (Person curr in selectedList1) { Console.WriteLine(" | " + curr.ToString()); } for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Selecting by reverse ID order"); DbExpression eSelect7 = new DbExpression("id", DbOperators.GreaterThan, 0); DbResultOrder[] resultOrder = new DbResultOrder[1]; resultOrder[0] = new DbResultOrder("id", DbOrderDirection.Descending); selectedList1 = _Orm.SelectMany <Person>(null, null, eSelect7, resultOrder); Console.WriteLine("| Retrieved: " + selectedList1.Count + " records"); foreach (Person curr in selectedList1) { Console.WriteLine(" | " + curr.ToString()); } #endregion #region Exception for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Catching exception and displaying query"); try { _Orm.Query("SELECT * FROM person ((("); } catch (Exception e) { Console.WriteLine("Exception: " + e.Message); Console.WriteLine("Query : " + e.Data["Query"]); } #endregion #region Delete-Records for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Deleting p1"); _Orm.Delete <Person>(p1); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Deleting p2"); _Orm.DeleteByPrimaryKey <Person>(2); for (int i = 0; i < 8; i++) { Console.WriteLine(""); } Console.WriteLine("| Deleting p3 and p4"); DbExpression eDelete = new DbExpression("id", DbOperators.GreaterThan, 2); _Orm.DeleteMany <Person>(eDelete); #endregion } catch (Exception e) { // Get stack trace for the exception with source file information var st = new StackTrace(e, true); // Get the top stack frame var frame = st.GetFrame(0); // Get the line number from the stack frame var line = frame.GetFileLineNumber(); Console.WriteLine("Stack trace:" + Environment.NewLine + SerializeJson(st, true)); Console.WriteLine("Stack frame: " + Environment.NewLine + SerializeJson(st, true)); Console.WriteLine("Line number: " + line); Console.WriteLine("Exception: " + Environment.NewLine + SerializeJson(e, true)); } Console.WriteLine(""); Console.WriteLine("Press ENTER to exit"); Console.ReadLine(); }
/// <summary> /// Retrieve all. /// </summary> /// <returns>List.</returns> public List <Role> All() { Expr e = new Expr(_ORM.GetColumnName <Role>(nameof(Role.Id)), OperatorEnum.GreaterThan, 0); return(_ORM.SelectMany <Role>(e)); }
/// <summary> /// Retrieve all. /// </summary> /// <returns>List.</returns> public List <Permission> All() { Expr e = new Expr(_ORM.GetColumnName <Permission>(nameof(Permission.Id)), OperatorEnum.GreaterThan, 0); return(_ORM.SelectMany <Permission>(e)); }
/// <summary> /// Retrieve a list of entries matching the specified conditions. /// </summary> /// <param name="accountGuid">GUID of the account.</param> /// <param name="startTimeUtc">Start time UTC.</param> /// <param name="endTimeUtc">End time UTC.</param> /// <param name="searchTerm">Search term that must appear in the entry description.</param> /// <param name="entryType">The type of entry.</param> /// <param name="amountMin">Minimum amount.</param> /// <param name="amountMax">Maximum amount.</param> /// <returns>List of matching entries.</returns> public List <Entry> GetEntries( string accountGuid, DateTime?startTimeUtc = null, DateTime?endTimeUtc = null, string searchTerm = null, EntryType?entryType = null, decimal?amountMin = null, decimal?amountMax = null) { if (startTimeUtc != null && endTimeUtc != null) { if (DateTime.Compare(Convert.ToDateTime(endTimeUtc), Convert.ToDateTime(startTimeUtc)) < 0) { throw new ArgumentException("Specified end time must be later than the specified start time."); } } if (amountMin != null && amountMin.Value < 0) { throw new ArgumentException("Minimum amount must be zero or greater."); } if (amountMax != null && amountMax.Value < 0) { throw new ArgumentException("Maximum amount must be zero or greater."); } if (String.IsNullOrEmpty(accountGuid)) { throw new ArgumentNullException(nameof(accountGuid)); } Account a = GetAccountByGuidInternal(accountGuid); if (a == null) { throw new KeyNotFoundException("Unable to find account with GUID " + accountGuid + "."); } try { LockAccount(accountGuid); DbExpression e2 = new DbExpression(_ORM.GetColumnName <Entry>(nameof(Entry.AccountGUID)), DbOperators.Equals, accountGuid); if (startTimeUtc != null) { e2.PrependAnd(_ORM.GetColumnName <Entry>(nameof(Entry.CreatedUtc)), DbOperators.GreaterThanOrEqualTo, startTimeUtc.Value); } if (endTimeUtc != null) { e2.PrependAnd(_ORM.GetColumnName <Entry>(nameof(Entry.CreatedUtc)), DbOperators.LessThanOrEqualTo, endTimeUtc.Value); } if (!String.IsNullOrEmpty(searchTerm)) { e2.PrependAnd(_ORM.GetColumnName <Entry>(nameof(Entry.Description)), DbOperators.Contains, searchTerm); } if (amountMin != null) { e2.PrependAnd(_ORM.GetColumnName <Entry>(nameof(Entry.Amount)), DbOperators.GreaterThanOrEqualTo, amountMin.Value); } if (amountMax != null) { e2.PrependAnd(_ORM.GetColumnName <Entry>(nameof(Entry.Amount)), DbOperators.LessThanOrEqualTo, amountMax.Value); } if (entryType != null) { e2.PrependAnd(_ORM.GetColumnName <Entry>(nameof(Entry.Type)), DbOperators.Equals, entryType); } else { e2.PrependAnd(_ORM.GetColumnName <Entry>(nameof(Entry.Type)), DbOperators.NotEquals, EntryType.Balance); } DbResultOrder[] ro = new DbResultOrder[1]; ro[0] = new DbResultOrder(_ORM.GetColumnName <Entry>(nameof(Entry.CreatedUtc)), DbOrderDirection.Descending); return(_ORM.SelectMany <Entry>(null, null, e2, ro)); } finally { UnlockAccount(accountGuid); } }
private void RunSetup() { #region Variables DateTime timestamp = DateTime.UtcNow; Settings settings = new Settings(); #endregion #region Welcome Console.WriteLine( Environment.NewLine + Environment.NewLine + "oooo .o8 " + Environment.NewLine + "`888 888 " + Environment.NewLine + " 888 oooo .ooooo. ooo. .oo. .oo. .ooooo. .oooo888 .ooooo. " + Environment.NewLine + " 888 .8P' d88' `88b `888P'Y88bP'Y88b d88' `88b d88' `888 d88' `88b " + Environment.NewLine + " 888888. 888 888 888 888 888 888 888 888 888 888 888 " + Environment.NewLine + " 888 `88b. 888 888 888 888 888 888 888 888 888 888 888 " + Environment.NewLine + "o888o o888o `Y8bod8P' o888o o888o o888o `Y8bod8P' `Y8bod88P `Y8bod8P' " + Environment.NewLine + Environment.NewLine + Environment.NewLine); // ________________ 1 2 3 4 5 6 7 // ________________12345678901234567890123456789012345678901234567890123456789012345678901234567890 Console.WriteLine("Thank you for using Komodo! We'll put together a basic system configuration"); Console.WriteLine("so you can be up and running quickly."); Console.WriteLine(""); Console.WriteLine(Common.Line(79, "-")); Console.WriteLine(""); #endregion #region Initial-Settings settings.EnableConsole = true; settings.Server = new Settings.ServerSettings(); settings.Server.HeaderApiKey = "x-api-key"; settings.Server.AdminApiKey = "komodoadmin"; settings.Server.ListenerPort = 9090; settings.Server.ListenerHostname = "localhost"; settings.Logging = new Settings.LoggingSettings(); settings.Logging.ConsoleLogging = true; settings.Logging.Header = "komodo"; settings.Logging.SyslogServerIp = "127.0.0.1"; settings.Logging.SyslogServerPort = 514; settings.Logging.MinimumLevel = Severity.Info; settings.Logging.FileLogging = true; settings.Logging.FileDirectory = "./logs/"; settings.Logging.Filename = "Komodo.log"; if (!Directory.Exists("./data/")) { Directory.CreateDirectory("./data/"); } if (!Directory.Exists("./logs/")) { Directory.CreateDirectory("./logs/"); } settings.Database = new DbSettings("./data/komodo.db"); string tempDirectory = "./data/temp/"; settings.TempStorage = new StorageSettings(new DiskSettings(tempDirectory)); if (!Directory.Exists(tempDirectory)) { Directory.CreateDirectory(tempDirectory); } string sourceDirectory = "./data/source/"; settings.SourceDocuments = new StorageSettings(new DiskSettings(sourceDirectory)); if (!Directory.Exists(sourceDirectory)) { Directory.CreateDirectory(sourceDirectory); } string parsedDirectory = "./data/parsed/"; settings.ParsedDocuments = new StorageSettings(new DiskSettings(parsedDirectory)); if (!Directory.Exists(parsedDirectory)) { Directory.CreateDirectory(parsedDirectory); } #endregion #region Initialize-Database-and-Create-Records WatsonORM orm = new WatsonORM(settings.Database.ToDatabaseSettings()); orm.InitializeDatabase(); orm.InitializeTable(typeof(ApiKey)); orm.InitializeTable(typeof(Index)); orm.InitializeTable(typeof(Metadata)); orm.InitializeTable(typeof(MetadataDocument)); orm.InitializeTable(typeof(Node)); orm.InitializeTable(typeof(ParsedDocument)); orm.InitializeTable(typeof(Permission)); orm.InitializeTable(typeof(SourceDocument)); orm.InitializeTable(typeof(TermDoc)); orm.InitializeTable(typeof(TermGuid)); orm.InitializeTable(typeof(User)); DbExpression e = new DbExpression("id", DbOperators.GreaterThan, 0); User user = null; ApiKey apiKey = null; Permission perm = null; Index idx = null; List <User> users = orm.SelectMany <User>(e); if (users == null || users.Count < 1) { Console.WriteLine("| Creating first user 'default'"); user = new User("default", "Default", "*****@*****.**", "default"); user = orm.Insert <User>(user); } else { Console.WriteLine("| Users already exist, not creating default user"); } List <Index> indices = orm.SelectMany <Index>(e); if (indices == null || indices.Count < 1) { Console.WriteLine("| Creating first index 'default'"); idx = new Index(user.GUID, "default"); idx = orm.Insert <Index>(idx); } else { Console.WriteLine("| Indices already exist, not creating default index"); } List <ApiKey> keys = orm.SelectMany <ApiKey>(e); if (keys == null || keys.Count < 1) { Console.WriteLine("| Creating first API key 'default'"); apiKey = new ApiKey("default", user.GUID, true); apiKey = orm.Insert <ApiKey>(apiKey); } else { Console.WriteLine("| API keys already exist, not creating default API key"); } List <Permission> perms = orm.SelectMany <Permission>(e); if (perms == null || perms.Count < 1) { Console.WriteLine("| Creating first permission 'default'"); perm = new Permission(idx.GUID, user.GUID, apiKey.GUID, true, true, true, true, true); perm = orm.Insert <Permission>(perm); } else { Console.WriteLine("| Permissions already exist, not creating default permissions"); } #endregion #region Write-System-JSON File.WriteAllBytes("./system.json", Encoding.UTF8.GetBytes(Common.SerializeJson(settings, true))); #endregion #region Wrap-Up string baseUrl = "http://localhost:" + settings.Server.ListenerPort; // ________________ 1 2 3 4 5 6 7 // ________________12345678901234567890123456789012345678901234567890123456789012345678901234567890 Console.WriteLine(""); Console.WriteLine("All finished!"); Console.WriteLine(""); Console.WriteLine("If you ever want to return to this setup wizard, just re-run the application"); Console.WriteLine("from the terminal with the 'setup' argument."); Console.WriteLine(""); Console.WriteLine("Verify Komodo is running in your browser using the following URL:"); Console.WriteLine(""); Console.WriteLine(" " + baseUrl); Console.WriteLine(""); Console.WriteLine("We've created your first index for you called 'First'. Try POSTing a JSON"); Console.WriteLine("document to the index using the API key 'default' using the URL:"); Console.WriteLine(""); Console.WriteLine(" " + baseUrl + "/default?type=json&name=My+First+Document&x-api-key=default"); Console.WriteLine(""); #endregion }
private async Task MonitorTask() { // look for removed indices and remove them // before looking for new indices to add! // use case: renaming an index or changing its guid // could cause double connection to its database bool firstRun = true; while (true) { #region Delay if (!firstRun) { Task.Delay(_RefreshIntervalSeconds).Wait(); } else { firstRun = false; } #endregion #region Gather-Records List <Index> indicesInDb = new List <Index>(); List <string> removedGuids = new List <string>(); List <string> addedGuids = new List <string>(); List <KomodoIndex> removeQueue = new List <KomodoIndex>(); List <Index> addQueue = new List <Index>(); lock (_IndicesLock) { DbExpression eId = new DbExpression( _ORM.GetColumnName <Index>(nameof(Index.Id)), DbOperators.GreaterThan, 0); indicesInDb = _ORM.SelectMany <Index>(eId); #region Check-for-Removed-Indices foreach (KomodoIndex index in _Indices) { if (!indicesInDb.Any(i => i.GUID.Equals(index.GUID))) { // exists in IndexManager but not in database removedGuids.Add(index.GUID); removeQueue.Add(index); } } #endregion #region Check-for-New-Indices foreach (Index index in indicesInDb) { if (!_Indices.Any(i => i.GUID.Equals(index.GUID))) { // exists in database but not in IndexManager addedGuids.Add(index.GUID); addQueue.Add(index); } } #endregion } #endregion #region Process-Queues foreach (KomodoIndex index in removeQueue) { await Remove(index.Name, false); } foreach (Index index in addQueue) { Add(index); } #endregion } }
internal void Enumerate( string delimiter, string prefix, int startIndex, int maxResults, out List <Obj> objects, out List <string> prefixes, out int nextStartIndex, out bool isTruncated) { objects = new List <Obj>(); prefixes = new List <string>(); nextStartIndex = startIndex; isTruncated = false; while (true) { #region Retrieve-Records DbExpression e = new DbExpression( _ORM.GetColumnName <Obj>(nameof(Obj.BucketGUID)), DbOperators.Equals, _Bucket.GUID); e.PrependAnd( _ORM.GetColumnName <Obj>(nameof(Obj.Id)), DbOperators.GreaterThanOrEqualTo, nextStartIndex); if (!String.IsNullOrEmpty(prefix)) { e.PrependAnd( _ORM.GetColumnName <Obj>(nameof(Obj.Key)), DbOperators.StartsWith, prefix); } List <Obj> tempObjects = _ORM.SelectMany <Obj>(null, maxResults, e); if (tempObjects == null || tempObjects.Count < 1) { break; } #endregion #region Process-Records foreach (Obj obj in tempObjects) { string currPrefix = null; string tempKey = new string(obj.Key); if (!String.IsNullOrEmpty(prefix)) { tempKey = tempKey.Replace(prefix, ""); } if (!String.IsNullOrEmpty(delimiter)) { if (tempKey.Contains(delimiter)) { int delimiterPos = tempKey.IndexOf(delimiter); currPrefix = tempKey.Substring(0, delimiterPos + delimiter.Length); if (!prefixes.Contains(currPrefix)) { prefixes.Add(currPrefix); } } } if (String.IsNullOrEmpty(currPrefix) && objects.Count <= maxResults) { objects.Add(obj); } if (obj.IsFolder && obj.ContentLength == 0) { prefixes.Add(obj.Key); } nextStartIndex = obj.Id + 1; } if (objects.Count >= maxResults) { isTruncated = true; break; } #endregion } return; }