/* Defining a query using lambda function to search specific key */ public void key_value_search(DBEngine<int, DBElement<int, string>> db, IQuery<int, DBElement<int, string>> i_query, QueryEngine<int, DBElement<int, string>> qe ) { "Query for value with specified key (key = 2):".title(); WriteLine(); int key_to_search = 2; Func<int, string, bool> keyValueSearch = (int key, string search) => //lambda function { if (!db.Keys().Contains(key)) return false; else { if (key == int.Parse(search)) { DBElement<int, string> ele = new DBElement<int, string>(); db.getValue(key, out ele); return true; } else { return false; } } }; // pass query to query engine and call simpleQuery to make query on DBEngine qe.simpleQuery(keyValueSearch, key_to_search.ToString(), out i_query); WriteLine(); foreach (var key in i_query.Keys()) { DBElement<int, string> temp = new DBElement<int, string>(); i_query.getValue(key, out temp); WriteLine("key : {0}", key); temp.showElement(); WriteLine(); } }
public QueryRunner(QueryParser queryParser, QueryPlanBuilder queryPlanBuilder, QueryEngine queryEngine, IQueryResultFactory queryResultFactory) { _queryParser = queryParser; _queryPlanBuilder = queryPlanBuilder; _queryEngine = queryEngine; _queryResultFactory = queryResultFactory; }
public RequestHandler() { sb = new StringBuilder(); db = new DBEngine<int, DBElement<int, string>>(); query = new QueryEngine<int, DBElement<int, string>>(); dbString = new DBEngine<string, DBElement<string, List<string>>>(); strElem = new DBElement<string, List<string>>(); }
/// <summary> /// Ctor /// </summary> /// <param name="analyzer"></param> /// <param name="sequences"></param> public QueryProvider(ITokenAnalyzer<ModelTokenType> analyzer, IQueryable<TokenSequence> sequences) { if (analyzer == null) { throw new ArgumentNullException("analyzer"); } if (sequences == null) { throw new ArgumentNullException("sequences"); } this.Engine = new QueryEngine(analyzer, sequences); }
/* Defining a query using lambda function to search children of specific element */ public void key_children_search(DBEngine<int, DBElement<int, string>> db, IQuery<int, DBElement<int, string>> i_query, QueryEngine<int, DBElement<int, string>> qe) { int specific_key = 2; "Query for children of specified key (key = 2):".title(); WriteLine(); Func<int, string, bool> childrenQuery = (int key, string search) => //lambda function { if (!db.Keys().Contains(key)) return false; if (key == int.Parse(search)) { DBElement<int, string> ele = new DBElement<int, string>(); db.getValue(key, out ele); return true; } else return false; }; // pass query to query engine and call simpleQuery to make query on DBEngine qe.simpleQuery(childrenQuery, specific_key.ToString(), out i_query); WriteLine(); foreach (var key in i_query.Keys()) { DBElement<int, string> temp = new DBElement<int, string>(); i_query.getValue(key, out temp); WriteLine("children of element with key {0} :", key); WriteLine(); if (temp.children != null) { int i = 0; foreach (int child in temp.children) { WriteLine("Children {0}", i++); DBElement<int, string> temp_child = new DBElement<int, string>(); if (db.Keys().Contains(child)) { db.getValue(child, out temp_child); WriteLine("key : {0}", child); temp_child.showElement(); WriteLine(); } else { WriteLine("no value with key {0} is present in database", child); WriteLine(); } } } } }
/* Defining a query using lambda function to search specific key */ public bool key_value_search(DBEngine<string, DBElement<string, List<string>>> db, out IQuery<string, DBElement<string, List<string>>> i_query, QueryEngine<string, DBElement<string, List<string>>> qe, string key_to_search = "12345") { "Query for value with specified key (key = element2):".title(); WriteLine(); Func<string, string, bool> keyValueSearch = (string key, string search) => //lambda function { if (!db.Keys().Contains(key)) return false; else { if (key == (search)) { DBElement<string, List<string>> ele = new DBElement<string, List<string>>(); db.getValue(key, out ele); return true; } else { return false; } } }; // pass query to query engine and call simpleQuery to make query on DBEngine if (qe.simpleQuery(keyValueSearch, key_to_search.ToString(), out i_query)) { WriteLine(); foreach (var key in i_query.Keys()) { DBElement<string, List<string>> temp = new DBElement<string, List<string>>(); i_query.getValue(key, out temp); WriteLine("key : {0}", key); temp.showEnumerableElement(); WriteLine(); } return true; } else { return false; } }
/// <summary> /// See if a ClickFunction command & process if so /// </summary> /// <param name="command"></param> /// <param name="qm"></param> /// <param name="cInf"></param> public static void Process( string command, QueryManager qm, CellInfo cInf = null) { QueryTable rootQt, qt; QueryColumn qc; MetaTable mt; MetaColumn mc; Query q2; string dbName = "", mtName = "", mcName = ""; List <string> args0, args; string funcName, arg1, arg2, arg3, arg4, arg5; string value = "", keyValue = ""; int ai; try { // Parse click function arguments stripping all single quotes. // Arguments may be defined in the clickfunction definition including col values // indicated by field.Value in the metacolumn clickfunction definition. // If no args are defined in the clickfunction definition then a field value // argument will be added by default or the keyValue if [keyvalue] appears in the // ClickFunction definition CurrentClickQueryManager = qm; args0 = Lex.ParseAllExcludingDelimiters(command, "( , )", false); args = new List <string>(); for (ai = 0; ai < args0.Count; ai++) // strip all single quotes { string arg = args0[ai]; if (arg.StartsWith("'")) { arg = Lex.RemoveSingleQuotes(arg); } //if (Lex.Eq(arg, "[rowcol]") && cInf!= null) //{ // pass grid row & col // args.Add(cInf.GridRowHandle.ToString()); // args.Add(cInf.GridColAbsoluteIndex.ToString()); //} //else args.Add(arg); } funcName = args[0]; arg1 = (args.Count >= 2 ? args[1] : ""); // get other args arg2 = (args.Count >= 3 ? args[2] : ""); arg3 = (args.Count >= 4 ? args[3] : ""); arg4 = (args.Count >= 5 ? args[4] : ""); arg5 = (args.Count >= 6 ? args[5] : ""); if (Lex.Eq(funcName, "DisplayAllData")) { // do all data display for supplied root table and key, i.e. DisplayAllData(TableName, KeyColName, KeyValue) ParseMetaTableMetaColumn(arg1, out mt, arg2, out mc); string extKey = arg3; string intKey = CompoundId.Normalize(extKey, mt); Progress.Show("Building Query..."); _query = QueryEngine.GetSelectAllDataQuery(mt.Name, intKey); Progress.Show("Retrieving data..."); // put up progress dialog since this may take a while QbUtil.RunPopupQuery(_query, mt.KeyMetaColumn.Name + " " + extKey); Progress.Hide(); return; } else if (Lex.Eq(funcName, "DisplayAllDataUsingDbName")) { // display all data for supplied database synonym & key value, i.e. DisplayAllData2(DataBaseSynonym, KeyValue) mtName = null; dbName = arg1; RootTable rti = RootTable.GetFromTableLabel(dbName); if (rti != null) { mtName = rti.MetaTableName; } else // try synonyms { DictionaryMx dict = DictionaryMx.Get("Database_Synonyms"); if (dict != null) { mtName = dict.LookupDefinition(dbName); } } if (String.IsNullOrEmpty(mtName)) { MessageBoxMx.ShowError("Unrecognized database: " + dbName); return; } mt = MetaTableCollection.Get(mtName); if (mt == null) { MessageBoxMx.ShowError("Can't find key metatable " + mtName + " for database " + dbName); return; } string extKey = arg2; string intKey = CompoundId.Normalize(extKey, mt); Progress.Show("Building Query..."); _query = QueryEngine.GetSelectAllDataQuery(mt.Name, intKey); Progress.Show("Retrieving data..."); // put up progress dialog since this may take a while QbUtil.RunPopupQuery(_query, mt.KeyMetaColumn.Name + " " + extKey); return; } // Run a query displaying results to a grid or web page and substituting a parameter value else if (Lex.Eq(funcName, "RunHtmlQuery") || Lex.Eq(funcName, "RunGridQuery")) { // command to display to grid or html if (arg1.StartsWith("MetaTreeNode=", StringComparison.OrdinalIgnoreCase)) { // query based on metatables under a tree node string nodeName = arg1.Substring("MetaTreeNode=".Length).Trim(); _cid = arg2; MetaTreeNode mtn = MetaTree.GetNode(nodeName); if (mtn == null) { MessageBoxMx.ShowError("Can't find tree node referenced in ClickFunction: " + nodeName); return; } _query = new Query(); MetaTable rootMt = null; foreach (MetaTreeNode mtn_ in mtn.Nodes) { if (!mtn_.IsDataTableType) { continue; } mt = MetaTableCollection.Get(mtn_.Target); if (mt == null) { continue; } if (rootMt == null) { rootMt = mt.Root; rootQt = new QueryTable(_query, rootMt); } if (mt == rootMt) { continue; } qt = new QueryTable(_query, mt); } if (_query.Tables.Count == 0) { MessageBoxMx.ShowError("No valid data tables found: " + nodeName); return; } _query.KeyCriteria = "= " + _cid; _title = mtn.Label + " for " + _query.Tables[0].MetaTable.MetaColumns[0].Label + " " + CompoundId.Format(_cid); } else if (arg1.StartsWith("Query=", StringComparison.OrdinalIgnoreCase)) { // query based on saved query string qIdString = arg1.Substring("Query=".Length).Trim(); if (qIdString.StartsWith("Query_", StringComparison.OrdinalIgnoreCase)) { qIdString = qIdString.Substring("Query_".Length).Trim(); } int qId = int.Parse(qIdString); _query = QbUtil.ReadQuery(qId); _cid = arg2; _query.KeyCriteria = "= " + _cid; _title = _query.UserObject.Name + " for " + _query.Tables[0].MetaTable.MetaColumns[0].Label + " " + CompoundId.Format(_cid); } else // explicit mql string to execute { _mql = arg1; // mql to execute if (Lex.IsUndefined(_mql)) { throw new Exception("Expected MQL query not found: " + command); } mt = null; mc = null; if (Lex.IsDefined(arg2) && Lex.IsDefined(arg3)) { mtName = arg2; mcName = arg3; value = arg4; // value to plug in to mql keyValue = value; ParseMetaTableMetaColumn(arg2, out mt, arg3, out mc); } else if (cInf != null) { mt = cInf.Mt; mc = cInf.Mc; value = cInf?.DataValue?.ToString(); keyValue = qm?.DataTableManager?.GetRowKey(cInf.DataRowIndex); } if (mt == null || mc == null) { throw new Exception("Invalid MetaTable or MetaColumn name(s): " + command); } if (!mc.IsNumeric) { value = Lex.AddSingleQuotes(value); // quote if not numeric } int i1 = _mql.ToLower().IndexOf("[value]"); // see if a value parameter if (i1 >= 0) { string value2 = value; _mql = _mql.Replace(_mql.Substring(i1, 7), value); _title = mc.Label + " " + value; } i1 = _mql.ToLower().IndexOf("[keyvalue]"); // see if a key value parameter if (i1 >= 0) { _mql = _mql.Replace(_mql.Substring(i1, 10), keyValue); _title = mt.KeyMetaColumn.Label + " " + keyValue; } try { _query = MqlUtil.ConvertMqlToQuery(_mql); } catch (Exception ex) { MessageBoxMx.ShowError("Error converting Mql to query: " + ex.Message); return; } } if (Lex.Eq(funcName, "RunHtmlQuery")) { QbUtil.RunPopupQuery(_query, _title, OutputDest.Html); } else // output to grid { QbUtil.RunPopupQuery(_query, _title, OutputDest.WinForms); } //else // create new grid query & run (will lose results for current query) //{ // QbUtil.NewQuery(_title); // show in query builder // QbUtil.SetCurrentQueryInstance(_query); // QbUtil.RenderQuery(); // string nextCommand = QueryExec.RunQuery(_query, OutputDest.Grid); //} return; } // Open a URL, normally substituting parameter value else if (Lex.Eq(funcName, "OpenUrl")) { string url = arg1; // url to execute value = arg2; // value to plug in to url int i1 = Lex.IndexOf(url, "[value]"); // fill in one of the value place holders if (i1 >= 0) { string value2 = value; url = url.Replace(url.Substring(i1, 7), value); } else // check to see if we are matching on key { i1 = Lex.IndexOf(url, "[keyvalue]"); if (i1 >= 0) { url = url.Replace(url.Substring(i1, 10), value); } } SystemUtil.StartProcess(url); return; } else if (Lex.Eq(funcName, "OpenUrlFromSmallWorldCid")) { SmallWorldDepictions.OpenUrlFromSmallWorldCid(arg1); return; } else if (Lex.Eq(funcName, "ShowProjectDescription")) { string projName = arg1; QbUtil.ShowProjectDescription(projName); return; } else if (Lex.Eq(funcName, "ShowTableDescription")) { mtName = arg1; QbUtil.ShowTableDescription(mtName); return; } else if (Lex.Eq(funcName, "DisplayDrilldownDetail")) { // drill down into a result value mtName = arg1; // table mcName = arg2; // column int level = Int32.Parse(arg3); string resultId = arg4; // quoted resultId to get q2 = QueryEngine.GetSummarizationDetailQuery(mtName, mcName, level, resultId); if (q2 == null) { throw new Exception("Unable to build drill-down query for: " + mtName + "." + mcName); } bool success = QbUtil.RunPopupQuery(q2, "Result Detail", OutputDest.WinForms); return; } //else if (Lex.Eq(funcName, "PopupSmilesStructure")) // display structure for a Smiles string (still needs some work...) //{ // string molString = arg1.ToString(); // ChemicalStructure cs = new ChemicalStructure(StructureFormat.Smiles, molString); // ToolHelper.DisplayStructureInPopupGrid("Title...", "Smiles", "Structure", cs); //} //else if (Lex.Eq(funcName, "PopupChimeStructure")) // display structure for a Chime string //{ // string molString = arg1.ToString(); // ChemicalStructure cs = new ChemicalStructure(StructureFormat.Smiles, molString); // ToolHelper.DisplayStructureInPopupGrid("Title...", "Smiles", "Structure", cs); //} else if (Lex.Eq(funcName, "DisplayWebPage")) { // substitute a field value into a url & display associated web page string url = arg1; ParseMetaTableMetaColumn(arg2, out mt, arg3, out mc); value = arg4; // value to plug in to mql // value = "{6E9C28EF-407E-44A0-9007-5FFB735A5C6C}"; // debug // value = "{0AC17903-E551-445E-BFAA-860023D2884F}"; // debug // value = "{63EE71F9-15BA-42FB-AFDC-C399103707B1}"; // debug // value = "{80591183-B7BA-4669-8C5F-7E7F53D981CE}"; //lex.OpenString(mc.ClickFunction); // reparse url to get proper case //funcName = lex.GetNonDelimiter(); //url = Lex.RemoveAllQuotes(lex.GetNonDelimiter()); _title = mc.Label + " " + value; int i1 = url.ToLower().IndexOf("[value]"); // fill in one of the value place holders if (i1 >= 0) { url = url.Replace(url.Substring(i1, 7), value); } else // check to see if we are matching on key { i1 = url.ToLower().IndexOf("[keyvalue]"); if (i1 >= 0) { url = url.Replace(url.Substring(i1, 10), value); _title = mt.KeyMetaColumn.Label + " " + value; } } UIMisc.ShowHtmlPopupFormDocument(url, _title); return; } else if (Lex.Eq(funcName, "DisplayOracleBlobDocument")) // display a document contained in an Oracle blob column { // Syntax: DisplayOracleBlobDocument(<table-to-lookup>, <value_match_column>, <file-name-or-type-col>, <content-column>) string table = arg1; string matchCol = arg2; string typeCol = arg3; string contentCol = arg4; string matchVal = arg5; // value to match try { string typeName; byte[] ba; UalUtil.SelectOracleBlob(table, matchCol, typeCol, contentCol, matchVal, out typeName, out ba); if (ba == null || ba.Length == 0) { return; } UIMisc.SaveAndOpenBinaryDocument(typeName, ba); } catch (Exception ex) { MessageBoxMx.ShowError("Error retrieving document: " + ex.Message); return; } return; } else if (Lex.Eq(funcName, "DisplayOracleClobDocument")) // display a document contained in an Oracle clob column { // Syntax: DisplayOracleBlobDocument(<table-to-lookup>, <value_match_column>, <file-name-or-type-col>, <content-column>) string table = arg1; string matchCol = arg2; string typeCol = arg3; string contentCol = arg4; string matchVal = arg5; // value to match try { string typeName, clobString; UalUtil.SelectOracleClob(table, matchCol, typeCol, contentCol, matchVal, out typeName, out clobString); if (Lex.IsUndefined(clobString)) { return; } UIMisc.SaveAndOpenBase64BinaryStringDocument(typeName, clobString); // assume clob string is a Base64Binary string } catch (Exception ex) { MessageBoxMx.ShowError("Error retrieving document: " + ex.Message); return; } return; } else if (Plugins.IsMethodExtensionPoint(funcName)) { List <object> objArgs = new List <object>(); for (ai = 1; ai < args.Count; ai++) // build list of object arguments { objArgs.Add(args[ai]); } Plugins.CallStringExtensionPointMethod(funcName, objArgs); } else if (Lex.Eq(funcName, "None")) // dummy click function { return; } else { MessageBoxMx.ShowError("Unrecogized click function: " + funcName); return; } } catch (Exception ex) { Exception ex2 = ex; if (ex.InnerException != null) { ex2 = ex.InnerException; } string msg = "Error executing ClickFunction: " + command + "\r\n" + DebugLog.FormatExceptionMessage(ex); MessageBoxMx.ShowError(msg); ServicesLog.Message(msg); } }
void TestR7() { //Demonstrating queries "Demonstrating Requirement #7".title(); WriteLine(); QueryEngine queryv = new QueryEngine(); DBElement<int, string> displayresc = new DBElement<int, string>(); DBElement<int, string> displayres = new DBElement<int, string>(); //demonstrating query 1 Console.WriteLine("\n \n getting value for key 1"); displayres = queryv.queryvalue<int, DBElement<int, string>, string>(db, 1); if (displayres != null) displayres.showElement(); DBElement<string, List<string>> valuestring = new DBElement<string, List<string>>(); Console.WriteLine("\n \n getting value for key 2"); valuestring = queryv.queryvalue<string, DBElement<string, List<string>>, string>(db2, "2"); if (valuestring != null) valuestring.showEnumerableElement(); // demonstrating query 2 Console.WriteLine("\n \n getting children for key 1"); List<int> tchildlist = new List<int>(); tchildlist = queryv.querychildren<int, DBElement<int, string>, string>(db, 1); if (tchildlist != null) { foreach (int i in tchildlist) Console.WriteLine(i); } }
/// <summary> /// Run the query /// </summary> /// <param name="browseExistingResults">If true browse existing results</param> /// <returns></returns> public string RunQuery3( ResultsFormat rf, bool saveHitlist, bool browseExistingResults) { Query modifiedQuery; QueryTable qt; QueryColumn qc; ResultsTable rt; ResultsField rfld; MetaTable mt; MetaColumn mc; string txt, msg; DialogResult dr; bool success; CellGraphic cg; Lex lex = new Lex(); string tempfile, tok, command, unrecognizedCommand, response; int ti, gi, rc, i1, i2; // Begin execution if (rf == null) { throw new Exception("QueryExec.Run - Null ResultsFormat"); } if (ResultsFormatter == null) { throw new Exception("QueryExec.Run - Null ResultsFormatter"); } if (rf.Segments == null) { throw new Exception("QueryExec.Run - Null ResultsFormat.Segments"); } if (Query == null) { throw new Exception("QueryExec.Run - Null Rf.Query"); } if (Query.Tables == null || Query.Tables.Count <= 0) { throw new QueryException("QueryExec.Run - No Query Tables"); } QueryManager qm = QueryManager; ReturnMsg = ""; //bool useExistingQueryEngine = Rf.ParentQe != null; //bool useExistingDataTable = Query.BrowseExistingResultsWhenOpened && Query.SerializeResults && // qm.DataTable != null && qm.DataTable.Rows.Count > 0; try { //if (Math.Sqrt(4) == 2) throw new Exception("test"); // debug if (!browseExistingResults) // normal open of search { Progress.Show("Analyzing query..."); // put up a status message to the user as soon as possible to let them know something is happening... dr = ValidateQuery(Query); if (dr == DialogResult.Cancel) { return(""); } WriteCurrentListToServerIfNeeded(Query); if (rf.OutputDestination == OutputDest.WinForms) // update access stats if grid { UpdateTableUsageStatistics(Query); } Query.ResultsDataTable = null; // be sure to get new results qm = BuildQueryManager(Query, rf); Query.ResetViewStates(); // reset state of views for proper operation if (Rf.ParentQe == null) // open search unless using existing query engine { if (!ExecuteSearch(saveHitlist)) // returns false if cancelled by user { Progress.Hide(); return(""); } } if ((ResultsKeys == null || ResultsKeys.Count == 0) && // nothing for search !Query.Preview && !MqlUtil.SingleStepExecution(Query) && qm.DataTable.Rows.Count == 0 && Query.RetrievesDataFromQueryEngine) { // if (!Rf.PopupDisplay) Progress.Hide(); if (qm.StatusBarManager != null) { qm.StatusBarManager.DisplayStatusMessage(""); } // if (QueryEngine.Cancelled) return ""; // cancelled by user msg = "No data have been found that matches your query."; if (ResultsFormat.PopupOutputFormContext && !ResultsFormat.SuppressNoDataMessage) { MessageBoxMx.Show(msg, "Search Result", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return("Command EditQuery"); // return to edit query menu } else { return(msg); } } //if (ResultsFormat.PopupDisplay) // SessionManager.DisplayStatusMessage("Retrieving data..."); //else Progress.Show("Retrieving data...", UmlautMobius.Value, true, "Cancelling Retrieval..."); //Progress.Show("Retrieving data...", UmlautMobius.String, true, "Cancelling Retrieval..."); Progress.Hide(); // hide progress - "Retrieving data..." message now appears as bottom line of grid if (ResultsFormat.Grid) { if (ResultsFormat.SessionOutputFormContext) // if normal main session form grid display, set browse mode & view state { Query.ResetViewStates(); // reset view state for all views QbUtil.SetMode(QueryMode.Browse, Query); if (ResultsFormat.Query.LogicType == QueryLogicType.And) // log grid query by logic type { UsageDao.LogEvent("QueryGridAnd", ""); } else if (ResultsFormat.Query.LogicType == QueryLogicType.Or) { UsageDao.LogEvent("QueryGridOr", ""); } else if (ResultsFormat.Query.LogicType == QueryLogicType.Complex) { UsageDao.LogEvent("QueryGridComplex", ""); } } else if (ResultsFormat.PopupOutputFormContext) // create popup window & configure { PopupResults.Show(qm); //MoleculeGridPanel.ConfigureAndShow(qm, null); } else if (ResultsFormat.ToolOutputFormContext) { ContainerControl cc; QueryResultsControl qrc = ResultsFormat.OutputContainerControl as QueryResultsControl; AssertMx.IsTrue(qrc != null, "ResultsFormat.OutputContainerControl must be a QueryResultsControl"); if (!WindowsHelper.FindContainerControl(qrc, typeof(ToolResultsContainer), out cc)) { throw new Exception("ToolResultsContainer not found"); } ToolResultsContainer trc = cc as ToolResultsContainer; trc.SetupQueryResultsControlForResultsDisplay(qm); } else { throw new Exception("Invalid OutputformContext: " + ResultsFormat.OutputFormContext); } } } else // reentering display switch to browse tab { QbUtil.SetMode(QueryMode.Browse, Query); } response = ResultsFormatter.BeginFormatting(browseExistingResults); // format the data if (ResultsFormat.SessionOutputFormContext) // normal display { if (MqlUtil.SingleStepExecution(Query)) { // be sure hit count display is up to date if (ResultsKeys != null) { if (qm.StatusBarManager != null) { qm.StatusBarManager.DisplayCurrentCount(); } } } if (saveHitlist) { CidList hitList = new CidList(ResultsKeys); rc = CidListCommand.WriteCurrentList(hitList); SessionManager.DisplayCurrentCount(); } } return(response); } // end of surrounding try catch (Exception ex) { Progress.Hide(); if (ex is UserQueryException) // exception that can occur from user error { throw new UserQueryException(ex.Message, ex); } else { msg = DebugLog.FormatExceptionMessage(ex); if (!Lex.Contains(msg, "QueryLogged:")) // exception & query { QueryEngine.LogExceptionAndSerializedQuery(msg, Query); } else { ServicesLog.Message(msg); // just log exception } throw new Exception(ex.Message, ex); // pass it up } } }
public void Setup() { QueryEngineUnderTest = new QueryEngine(); QueryEngineUnderTest.ConnectToServer(); }
//function to getvalue public XElement getvalue(XElement dbe, DBEngine<int, DBElement<int, string>> db, QueryEngine QE) { Console.WriteLine("\n value of the particular key is returned "); DBElement<int, string> dbelem = new DBElement<int, string>(); QE.queryvalue<int, DBElement<int, string>, string>(db, 2); if (QE.Equals(null)) { XElement f = new XElement("result", "\n no key present "); return f; } else { XElement s = new XElement("result", "\n Value obtained "); return s; } }
/* Defining a query using lambda function to search specific elements belonging in specific * time-interval with end of time interval equal to present */ public void date_time_specific(DBEngine<string, DBElement<string, List<string>>> db, out IQuery<string, DBElement<string, List<string>>> i_query, QueryEngine<string, DBElement<string, List<string>>> qe, DateTime start, DateTime end = new DateTime()) { "Query for keys with specified date time interval: start=10/4/2015 end=10/5/2015".title(); WriteLine(); Func<string, DateTime, DateTime, bool> TimeDateQuery = (string key, DateTime query_start, DateTime query_end) => //lambda function { if (!db.Keys().Contains(key)) return false; else { DBElement<string, List<string>> ele = new DBElement<string, List<string>>(); db.getValue(key, out ele); int start_result = DateTime.Compare(query_start, ele.timeStamp); int end_result = DateTime.Compare(query_end, ele.timeStamp); if ((start_result <= 0) && (end_result >= 0)) { return true; } else return false; } }; // pass query to query engine and call simpleQuery to make query on DBEngine qe.simpleQueryDate(TimeDateQuery, out i_query, start, end); WriteLine(); foreach (var key in i_query.Keys()) { DBElement<string, List<string>> temp = new DBElement<string, List<string>>(); i_query.getValue(key, out temp); WriteLine("key : {0}", key); temp.showEnumerableElement(); WriteLine(); } }
public void performOperations(DBEngine<string, DBElement<string, List<string>>> testDict, DBElement<string, List<string>> value) { /*----------Perform operations as per the input given in the XML document--------------*/ if (value.operation == "addition") { testDict.insert(value.key, value); //insert the key/value pairs to the main database string s = "Database after inserting key " + value.key + " is"; printDatabase(testDict, s); } if (value.operation == "edit") { testDict.saveValue(value.key, value); //edit the value for the given key string s = "Database after editing key " + value.key + " is"; printDatabase(testDict, s); } if (value.operation == "delete") { testDict.delete(value.key); //delete the key/value pair string s = "Database after deleting key " + value.key + " is"; printDatabase(testDict, s); } if (value.operation == "persist database") { PersistEngine<string, DBElement<string, List<string>>> persist = new PersistEngine<string, DBElement<string, List<string>>>(testDict); var keys = testDict.Keys(); persist.persistToXMLListPayload(keys); printDatabase(testDict, "Persisted database is:"); } if (value.operation == "Query value") { DBElement<string, List<string>> valueOfKey = testDict.getValueOfKey(value.key); printQuery("Querying the database for value of key " + value.key + " is"); Console.WriteLine("\n\nThe value of the Key {0} is:\n", value.key); valueOfKey.showEnumerableElement(); } if (value.operation == "Query children") { QueryEngine<string, DBElement<string, List<string>>> qEngine = new QueryEngine<string, DBElement<string, List<string>>>(testDict); printQuery("Querying the database for value of key " + value.key + " is"); List<string> children = qEngine.getChildrenOfKey(value.key); Console.WriteLine("\nThe children of the Key {0} are:\n", value.key); displayChildren(children); } if (value.operation == "Augment database") { PersistEngine<string, DBElement<string, List<string>>> persist = new PersistEngine<string, DBElement<string, List<string>>>(testDict); string fileName = "C:\\Users\\rakeshh91\\Documents\\Rakesh Documents\\Class Materials\\SMA\\Assignments\\Assignment 4 - Implementation\\CommPrototype\\augmentDatabase.xml"; persist.augmentDatabaseFromXMLStringList(testDict, fileName); printDatabase(testDict, "Database after augmenting is:"); } }
private void string_metadata(out string str, ref IEnumerator<string> msg_enumerator, DBEngine<string, DBElement<string, List<string>>> db) { IQuery<string, DBElement<string, List<string>>> i_query = new DBEngine<string, DBElement<string, List<string>>>(); QueryEngine<string, DBElement<string, List<string>>> qe = new QueryEngine<string, DBElement<string, List<string>>>(db); QueryPredicate qp = new QueryPredicate(); string search = ""; str = ""; msg_enumerator.MoveNext(); msg_enumerator.MoveNext(); search = msg_enumerator.Current.ToString(); DBElement<string, List<string>> ele = new DBElement<string, List<string>>(); if (qp.metadata_string(db, out i_query, qe, search)) { foreach (var key in i_query.Keys()) { if (i_query.getValue(key, out ele)) { str += " Element with string:" + search + " found in Database.\n Key: "+ key +"\nValue at given key: " + ele.showElement<string, List<string>, string>(); } } } else { str = "Element with string: " + search + " in metadata Not found in Database.\n"; } }
private void search_key_value(out string str, ref IEnumerator<string> msg_enumerator, DBEngine<string, DBElement<string, List<string>>> db) { IQuery<string, DBElement<string, List<string>>> i_query = new DBEngine<string, DBElement<string, List<string>>>(); QueryEngine<string, DBElement<string, List<string>>> qe = new QueryEngine<string, DBElement<string, List<string>>>(db); QueryPredicate qp = new QueryPredicate(); string search = ""; msg_enumerator.MoveNext(); msg_enumerator.MoveNext(); search = msg_enumerator.Current.ToString(); DBElement<string, List<string>> ele = new DBElement<string, List<string>>(); if (qp.key_value_search(db, out i_query, qe, search)) { i_query.getValue(search, out ele); str = " Key: " + search + " found in Database.\n Value at given key: " + ele.showElement<string, List<string>, string>(); } else { str = "Key: " + search + " Not found in Database.\n"; } }
public virtual bool Any(Type structureType) { //OK, to not be wrapped in Try, since QueryEngine does this return(QueryEngine.Any(structureType)); }
public virtual bool Exists(Type structureType, object id) { //OK, to not be wrapped in Try, since QueryEngine does this return(QueryEngine.Exists(structureType, id)); }
public virtual bool Exists <T>(object id) where T : class { //OK, to not be wrapped in Try, since QueryEngine does this return(QueryEngine.Exists <T>(id)); }
static void Main(string[] args) { "Testing DBFactory Package".title('='); WriteLine(); DBFactoryTest dbft = new DBFactoryTest(); "\nCreation of immutable database".title(); WriteLine(); "\nOriginal database".title(); DBEngine<int, DBElement<int, string>> db = new DBEngine<int, DBElement<int, string>>(); dbft.insertData(db); "\n Fetch all the keys which are even from the above database".title(); try { QueryEngine<int, DBElement<int, string>> qEngine = new QueryEngine<int, DBElement<int, string>>(db); Dictionary<int, DBElement<int, string>> dictFactory = new Dictionary<int, DBElement<int, string>>(); DBFactory<int, DBElement<int, string>> dbFactory; var keys = qEngine.getListKeyPattern(); if (keys != null) { foreach (var key in keys) { var val = db.getValueOfKey(key); dictFactory.Add(key, val); //add keys and values to the dictionary } dbFactory = new DBFactory<int, DBElement<int, string>>(dictFactory); //store the dictionary in the WriteLine("\nThe below key/value pairs with even keys pattern are saved as an immutable database\n"); dbFactory.showDB(); //display the immutable database WriteLine(); WriteLine(); } else { WriteLine("\nNo keys are obtained from a query for creation of immutable database\n"); } WriteLine(); WriteLine(); } catch (Exception e) { Console.WriteLine("\n" + e.Message + "\n"); } }
public void Setup() { EngineUnderTest = new QueryEngine(); //this is typically done in the middleware, must do here EngineUnderTest.ConnectToServer(); }
private void time_date_inerval(out string str, ref IEnumerator<string> msg_enumerator, DBEngine<string, DBElement<string, List<string>>> db) { IQuery<string, DBElement<string, List<string>>> i_query = new DBEngine<string, DBElement<string, List<string>>>(); QueryEngine<string, DBElement<string, List<string>>> qe = new QueryEngine<string, DBElement<string, List<string>>>(db); QueryPredicate qp = new QueryPredicate(); DateTime start = new DateTime(); DateTime end = new DateTime(); str = ""; bool flag = false; while (msg_enumerator.MoveNext()) { switch(msg_enumerator.Current.ToString()) { case "sdate-time": msg_enumerator.MoveNext(); DateTime.TryParse(msg_enumerator.Current.ToString(), out start); break; case "edate-time": msg_enumerator.MoveNext(); if (msg_enumerator.Current.ToString() != "" && DateTime.TryParse(msg_enumerator.Current.ToString(), out end)) ; else flag = true; break; } } DBElement<string, List<string>> ele = new DBElement<string, List<string>>(); if (flag && qp.default_date_time_specific(db, out i_query, qe, start)) { foreach (var key in i_query.Keys()) if (i_query.getValue(key, out ele)) str += " Element within timespan starting:" + start + " and ending: " + DateTime.Now + " found in Database.\n Key: " + key + "\nValue at given key: " + ele.showElement<string, List<string>, string>(); } else if (qp.default_date_time_specific(db, out i_query, qe, start, end)) { foreach (var key in i_query.Keys()) { if (i_query.getValue(key, out ele)) { str += " Element within timespan starting:" + start + " and ending: " + end + " found in Database.\n Key: " + key + "\nValue at given key: " + ele.showElement<string, List<string>, string>(); } } } else { str = "Element within timespan: " + start + " and ending: " + end + " Not found in Database.\n"; } }
/* Defining a query using lambda function to search specific key matching default pattern */ public void default_pattern_matching(DBEngine<string, DBElement<string, List<string>>> db, out IQuery<string, DBElement<string, List<string>>> i_query, QueryEngine<string, DBElement<string, List<string>>> qe) { string pattern = ""; "Query for keys matching with specified pattern (pattern = none -> default case):".title(); WriteLine(); Func<string, string, bool> keysMatchingPattern = (string key, string search) => //lambda function { if (!db.Keys().Contains(key)) return false; else { if (key.ToString().Contains(search)) { DBElement<string, List<string>> ele = new DBElement<string, List<string>>(); db.getValue(key, out ele); return true; } else return false; } }; // pass query to query engine and call simpleQuery to make query on DBEngine qe.simpleQuery(keysMatchingPattern, pattern, out i_query); WriteLine(); foreach (var key in i_query.Keys()) { DBElement<string, List<string>> temp = new DBElement<string, List<string>>(); i_query.getValue(key, out temp); WriteLine("key : {0}", key); temp.showEnumerableElement(); WriteLine(); } }
public MainWindow(string busId) { queryEngine = new QueryEngine(); InitializeComponent(); columnChart(busId); }
public virtual int Count(Type structureType) { //OK, to not be wrapped in Try, since QueryEngine does this return(QueryEngine.Count(structureType)); }
/// <summary> /// Write a table to Kusto /// </summary> /// <param name="tableSchema">The table to write</param> /// <param name="kustoQueryEngine">An initialized query engine for issuing the Kusto command</param> public static void WriteToKusto(this TableSchema tableSchema, QueryEngine kustoQueryEngine) { kustoQueryEngine.CreateOrAlterTableAsync(CslCommandGenerator.GenerateTableCreateCommand(tableSchema, false), tableSchema.Name).Wait(); }
static QueryEngineTest() { engine = new QueryEngine(GetMockedInvertedIndex()); }
/// <summary> /// Delete a table from Kusto /// </summary> /// <param name="tableSchema">The table to remove</param> /// <param name="kustoQueryEngine">An initialized query engine for issuing the Kusto command</param> public static void DeleteFromKusto(this TableSchema tableSchema, QueryEngine kustoQueryEngine) { kustoQueryEngine.DropTable(tableSchema.Name); }
/// <summary> /// (Obsolete) /// Examine query & expand any tables marked for remapping /// Existing remap place holder tables are removed & expansion tables /// are added at the end of the query in alphabetical order sorted across /// all added tables. /// </summary> /// <returns></returns> /// <param name="qm">QueryManager</param> /// <param name="q">Original Query</param> /// <param name="qe">Original QueryEngine</param> /// <param name="resultsKeys">Search-step results keys to consider</param> /// <returns>Modified Query</returns> public static Query RemapTablesForRetrieval(QueryManager qm, Query q, QueryEngine qe, List <string> resultsKeys) { throw new NotImplementedException(); }
/// <summary> /// Write a function to Kusto /// </summary> /// <param name="functionSchema">The function to write</param> /// <param name="kustoQueryEngine">An initialized query engine for issuing the Kusto command</param> public static void WriteToKusto(this FunctionSchema functionSchema, QueryEngine kustoQueryEngine) { kustoQueryEngine.CreateOrAlterFunctionAsync(CslCommandGenerator.GenerateCreateOrAlterFunctionCommand(functionSchema, true), functionSchema.Name).Wait(); }
/// <summary> /// Execute search & get hit list /// </summary> /// <param name="saveHitlist"></param> /// <returns></returns> public bool ExecuteSearch(bool saveHitlist) { int voi, ti, fi; ResultsTable rt; ResultsField rfld; MetaTable mt; MetaColumn mc, mc2; if (saveHitlist) // clear current list { SessionManager.CurrentResultKeys = new List <string>(); if (QueryManager.StatusBarManager != null) { QueryManager.StatusBarManager.DisplayCurrentCount(); } } // Start thread running the query QueryResultsAvailable = false; QueryEngineException = null; ThreadStart ts = new ThreadStart(ExecuteQueryThreadMethod); Thread executeQueryThread = new Thread(ts); executeQueryThread.Name = "ExecuteSearch"; executeQueryThread.IsBackground = true; executeQueryThread.SetApartmentState(ApartmentState.STA); executeQueryThread.Start(); // Put up message for user if (((Query.ResultKeys != null && Query.UseResultKeys) || // already have list ResultsFormat.SessionOutputFormContext) && !QueryEngineStatsForm.ShowStats) { Progress.Show("Retrieving data...", UmlautMobius.String, true, "Cancelling retrieval..."); } else // normal type search { Progress.Show("Searching database - 0:00", UmlautMobius.String, true, "Cancelling search..."); if (QueryEngineStatsForm.ShowStats) { QueryEngineStatsForm.StartNewQueryExecution(Query); QueryEngineStatsForm.StartingSearch(); } } // Wait until results available or the query is cancelled by the user while (true) { Thread.Sleep(100); Application.DoEvents(); if (QueryResultsAvailable) // completed normally { ResultsKeys = QueryEngine.GetKeys(); if (saveHitlist) // store for session manager also (may differ but probably shouldn't) { SessionManager.CurrentResultKeys = ResultsKeys; } //Progress.Hide(); break; } else if (QueryEngineException != null) { Progress.Hide(); if (QueryEngineException is QueryException || QueryEngineException is UserQueryException) { throw QueryEngineException; } else { throw new Exception(QueryEngineException.Message, QueryEngineException); } } else if (Progress.CancelRequested) { if (QueryEngine != null) { QueryEngine.Cancel(false); // start the cancel } Thread.Sleep(250); Application.DoEvents(); if (executeQueryThread != null) { executeQueryThread.Abort(); // kill the local thread executing the query } Progress.Hide(); return(false); } } // If the query contains tables marked for remapping then build new expanded query & use going forward // modifiedQuery = QueryEngine.DoPresearchChecksAndTransforms(Query); // do any presearch transforms OriginalQuery = Query; if (TransformedQuery != null) { //ResultsPages qrp = query.ResultsPages; //ResultsPages mqrp = modifiedQuery.ResultsPages; // use same set of results pages so view changes propagate back to original query Query.PresearchDerivedQuery = TransformedQuery; // link original query to the transformed query Query = TransformedQuery; // replace original query with this query } else { Query.PresearchDerivedQuery = null; } InitializeQueryManager(QueryManager, Query, QueryManager.ResultsFormat, QueryEngine, ResultsKeys); // Save the hit list as needed if (saveHitlist) { CidList currentList = new CidList(ResultsKeys); CidListCommand.WriteCurrentList(currentList); SessionManager.DisplayCurrentCount(); } return(true); }
/// <summary> /// Delete a function from Kusto /// </summary> /// <param name="functionSchema">The function to remove</param> /// <param name="kustoQueryEngine">An initialized query engine for issuing the Kusto command</param> public static void DeleteFromKusto(this FunctionSchema functionSchema, QueryEngine kustoQueryEngine) { kustoQueryEngine.DropFunction(functionSchema); }
public TestTdsServer(QueryEngine engine, TDSServerArguments args) : base(args) { this.Engine = engine; }
/// <summary> /// Формирует запрос из формы /// </summary> /// <param name="form">Форма на основе которого будет формироваться структура запроса</param> /// <returns>Запрос на выборку данных из БД</returns> public QueryDef QueryFromForm(BizForm form) { using (var engine = new QueryEngine(DataContext)) return(engine.QueryFromForm(form)); }
void TestR7() { "\n1) Fetch Value for key 3".title(); var val = db.getValueOfKey(3); val.showElement(); WriteLine(); qEngine = new QueryEngine<int, DBElement<int, string>>(db); "\n2) Fetch the children of key 1".title(); var children = qEngine.getChildrenOfKey(1); displayChildren(children); "\n3) Fetch the keys which starts with r in the below database with key/value pairs".title(); //Taking new database with string keys DBElement<string, List<string>> elem = new DBElement<string, List<string>>(); elem.name = "Christ college"; elem.descr = "College where the person studied"; elem.timeStamp = DateTime.Now; elem.children.AddRange(new List<string> { "rakesh" }); elem.payload = new List<string> { "One", "Two", "Three", "Four" }; dbString.insert("saahith", elem); DBElement<string, List<string>> elem1 = new DBElement<string, List<string>>(); elem1.name = "PESIT college"; elem1.descr = "College where the person pursued undergraduation"; elem1.timeStamp = DateTime.Now.AddDays(-2); elem1.children.AddRange(new List<string> { "saahith" }); elem1.payload = new List<string> { "Five", "Six", "Seven", "Eight" }; dbString.insert("rakesh", elem1); dbString.showEnumerableDB(); WriteLine(); qEngine2 = new QueryEngine<string, DBElement<string, List<string>>>(dbString); string pattern1 = @"(^r)"; var spKeys = qEngine2.getListStringKeyPattern(pattern1); displayStringKeys(spKeys); "\n4) Fetch keys with metadata pattern 'Name'".title(); string pattern = "Name"; var mdKeys = qEngine.getListMetaDataPattern(pattern); displayKeys(mdKeys); "\n5) Fetch keys which are created between two dates 29th sept 2015 and 15th oct 2015".title(); DateTime time1 = new DateTime(2015, 9, 29); DateTime time2 = new DateTime(2015, 10, 15); var tpKeys = qEngine.getListTimePattern(time1, time2); displayKeys(tpKeys); }
/// <summary> /// Test out the settings before saving them. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnOk_Click(object sender, EventArgs e) { Cursor lastCursor = Cursor.Current; Cursor.Current = Cursors.WaitCursor; // Allow for multiple ways of specifying a cluster name if (string.IsNullOrEmpty(txtKustoCluster.Text)) { MessageBox.Show($"No Kusto cluster was specified.", "Missing Info", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } string clusterName = QueryEngine.NormalizeClusterName(txtKustoCluster.Text); string databaseName = txtKustoDatabase.Text; if (string.IsNullOrEmpty(databaseName)) { MessageBox.Show($"No Kusto database was specified.", "Missing Info", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // If the required info is present, update the cluster textbox with the modified cluster url txtKustoCluster.Text = clusterName; // Verify connection and permissions by creating and removing a function try { var connString = new KustoConnectionStringBuilder(clusterName) { FederatedSecurity = true, InitialCatalog = databaseName, Authority = txtAuthority.Text }; var adminClient = KustoClientFactory.CreateCslAdminProvider(connString); string functionName = "SyncKustoPermissionsTest"; adminClient.ExecuteControlCommand( CslCommandGenerator.GenerateCreateOrAlterFunctionCommand( functionName, "", "", new Dictionary <string, string>(), "{print now()}")); adminClient.ExecuteControlCommand(CslCommandGenerator.GenerateFunctionDropCommand(functionName)); // Store the settings now that we know they work SettingsWrapper.KustoClusterForTempDatabases = clusterName; SettingsWrapper.TemporaryKustoDatabase = databaseName; SettingsWrapper.AADAuthority = txtAuthority.Text; this.Close(); } catch (Exception ex) { if (ex.Message.Contains("403-Forbidden")) { MessageBox.Show($"The current user does not have permission to create a function on cluster('{clusterName}').database('{databaseName}')", "Error Validating Permissions", MessageBoxButtons.OK, MessageBoxIcon.Error); } else if (ex.Message.Contains("failed to resolve the service name")) { MessageBox.Show($"Cluster {clusterName} could not be found.", "Error Validating Permissions", MessageBoxButtons.OK, MessageBoxIcon.Error); } else if (ex.Message.Contains("Kusto client failed to perform authentication")) { MessageBox.Show($"Could not authenticate with AAD. Please verify that the AAD Authority is specified correctly.", "Error Authenticating", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { MessageBox.Show($"Unknown error: {ex.Message}", "Error Validating Permissions", MessageBoxButtons.OK, MessageBoxIcon.Error); } } Cursor.Current = lastCursor; }
private Tree GetProcesses() { var model = new Tree(); if (_serverInfo != null) { try { var server = _serverInfo.Server; var rootId = server; model.AddNode(rootId, string.Empty, server, server, server); var taskList = new Dictionary <byte[], int>(); _processes = QueryEngine.GetSessions(_serverInfo); var rows = _processes.AsEnumerable().DistinctBy(r => r.Field <short>("session_id")); var schedulers = rows.GroupBy(r => r.Field <byte[]>("scheduler_address")); var schedulerList = new List <string>(); var workerId = 0; var taskId = 0; var blockColor = Color.Salmon; schedulers.ForEach(s => { //http://msdn.microsoft.com/en-us/library/ms177526.aspx var scheduler = s.First(); var schedulerId = scheduler.Field <int>("scheduler_id").ToString(); string description; var schedulerRoot = KeyScheduler + schedulerId; if (!schedulerList.Contains(schedulerId)) { schedulerList.Add(schedulerId); var isIdle = scheduler.Field <bool>("is_idle"); description = string.Format("is idle: {0}\r\ncurrent workers: {1}\r\nactive workers: {2}", isIdle.ToString(), scheduler.Field <int>("current_workers_count").ToString(), scheduler.Field <int>("active_workers_count")); model.AddNode(schedulerRoot, rootId, schedulerRoot, "Scheduler " + schedulerId, description, isIdle ? Color.LightGray : Color.White); } var workers = s.GroupBy(w => w.Field <byte[]>("worker_address")); workers.ForEach(w => { //http://msdn.microsoft.com/en-us/library/ms178626.aspx var workerRoot = KeyWorker + workerId; var worker = w.First(); var workerState = worker.Field <string>("worker_state"); var workerStateName = string.Empty; var workerColor = Color.White; switch (workerState.ToUpper()) { case "INIT": workerStateName = "initializing"; workerColor = Color.LightGreen; break; case "RUNNING": workerStateName = "running"; workerColor = Color.LightBlue; break; case "RUNNABLE": workerStateName = "runnable"; workerColor = Color.Green; break; case "SUSPENDED": workerStateName = "suspended"; workerColor = Color.LightGray; break; default: workerStateName = "unkown"; break; } var workerIsSick = worker.Field <bool>("is_sick"); var workerIsFatalException = worker.Field <bool>("is_fatal_exception"); var workerExceptionCount = worker.Field <int>("exception_num"); var workerTasksProcessedCount = worker.Field <int>("tasks_processed_count"); var workerLastResult = worker.Field <int>("return_code"); var workerLastResultName = string.Empty; switch (workerLastResult) { case 0: workerLastResultName = "success"; break; case 3: workerLastResultName = "dead lock"; break; case 4: workerLastResultName = "premature wakeup"; break; case 258: workerLastResultName = "time out"; break; default: workerLastResultName = string.Format("(unkown:{0})", workerLastResult); break; } description = string.Format("processed tasks: {0}\r\nstate: {1}\r\nis sick: {2}\r\nis fatal exception:{3}\r\nexception number:{4}\r\nlast result:{5}", workerTasksProcessedCount, workerStateName, workerIsSick.ToString(), workerIsFatalException.ToString(), workerExceptionCount, workerLastResultName); model.AddNode(workerRoot, schedulerRoot, workerRoot, "Worker " + workerId, description, workerColor); var tasks = w.GroupBy(t => t.Field <byte[]>("task_address")); tasks.ForEach(t => { //http://msdn.microsoft.com/en-us/library/ms174963.aspx var taskRoot = KeyTask + taskId; var task = t.First(); var taskAddress = task.Field <byte[]>("task_address"); if (!taskList.ContainsKey(taskAddress)) { taskList.Add(taskAddress, taskId); } var taskState = task.Field <string>("task_state"); var taskStateName = string.Empty; var taskColor = Color.White; switch (taskState.ToUpper()) { case "PENDING": taskStateName = "pending"; taskColor = Color.LightGreen; break; case "RUNNING": taskStateName = "running"; taskColor = Color.LightBlue; break; case "RUNNABLE": taskStateName = "runnable"; taskColor = Color.Green; break; case "SUSPENDED": taskStateName = "suspended"; taskColor = Color.LightGray; break; case "DONE": taskStateName = "done"; taskColor = Color.White; break; case "SPINLOOP": taskStateName = "spin loop"; taskColor = Color.LightSalmon; break; default: taskStateName = "unknown"; break; } description = string.Format("state:" + taskStateName); model.AddNode(taskRoot, workerRoot, taskRoot, "Task " + taskId, description, taskColor); taskId++; }); workerId++; }); }); var addedProcesses = new List <short>(); var lockedProcesses = QueryEngine.GetLockedProcesses(_serverInfo); lockedProcesses.AsEnumerable().ForEach(p => { var spid = p.Field <short>("SPID"); var task = rows.FirstOrDefault(r => r.Field <short>("session_id") == spid); if (task != null) { var taskAddress = task.Field <byte[]>("task_address"); int parent; if (taskList.TryGetValue(taskAddress, out parent)) { var taskRoot = KeyTask + parent; var requstId = KeyRequest + spid; var description = GetProcessDescription(task); var blockingId = p.Field <short?>("BlockingSPID"); Color backColor; if (blockingId != null && blockingId != 0) { taskRoot = KeyRequest + blockingId; backColor = blockColor; } else { backColor = Color.Red; description = "!blocking root, kill it!\r\n\r\n" + description; } var currentServer = _serverInfo.Clone(); currentServer.Database = task.Field <string>("database_name"); var lockedObjects = QueryEngine.GetLockedObjects(spid, currentServer); var lockedObjectList = new StringBuilder(); if (lockedObjects.Rows.Count > 0) { var sessionLockedObjects = lockedObjects.AsEnumerable(); if (sessionLockedObjects.Any()) { lockedObjectList.AppendLine("locked objects:"); sessionLockedObjects.ForEach(r => { lockedObjectList.AppendFormat(" {0}.{1}.{2}\r\n", r.Field <string>("DatabaseName"), r.Field <string>("SchemaName"), r.Field <string>("ObjectName")); }); } } description = lockedObjectList.ToString() + description; addedProcesses.Add(spid); model.AddNode(requstId, taskRoot, requstId, "Process " + spid, description, backColor); } } }); rows.ForEach(p => { var sessionId = p.Field <short>("session_id"); if (!addedProcesses.Contains(sessionId)) { var session = KeyRequest + sessionId; var taskAddress = p.Field <byte[]>("task_address"); var task = taskList[taskAddress]; var taskRoot = KeyTask + task; var description = GetProcessDescription(p); Color backColor; var sessionStatus = p.Field <string>("session_status"); switch (sessionStatus.ToUpper()) { case "RUNNING": backColor = Color.LightBlue; break; case "SLEEPING": backColor = Color.LightGray; break; case "DORMANT": backColor = Color.Gray; break; case "PRECONNECT": backColor = Color.Gray; break; default: backColor = Color.White; break; } model.AddNode(session, taskRoot, session, "Process " + sessionId, description, backColor); } }); var title = "Process Visualizer ({0})"; if (lockedProcesses.Rows.Count > 0) { title += ", found {1} dead lock processes!"; } this.Text = string.Format(title, _serverInfo.Server, lockedProcesses.Rows.Count); } catch (Exception ex) { MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); } } return(model); }
public void GetQueryResults_OnlyExcTerms_ThrowsException() { var queryBuilder = new QueryBuilder("-first -third"); Assert.Throws <ArgumentException>(() => QueryEngine.GetQueryResults(queryBuilder, mockedInvertedIndex.Object)); }
//Main function parses and sends the messages to server// static void Main(string[] args) { Util.verbose = false; Server srvr = new Server(); srvr.ProcessCommandLine(args); Console.Title = "Server"; Console.Write(String.Format("\n Starting CommService server listening on port {0}", srvr.port)); Console.Write("\n ====================================================\n"); Sender sndr = new Sender(Util.makeUrl(srvr.address, srvr.port)); Receiver rcvr = new Receiver(srvr.port, srvr.address); Action serviceAction = () => { Message msg = null; DBEngine<int, DBElement<int, string>> dbserver = new DBEngine<int, DBElement<int, string>>(); //new DBEngine QueryEngine QE = new QueryEngine(); HiResTimer timer = new HiResTimer(); //new object for timer while (true) { msg = rcvr.getMessage(); // note use of non-service method to deQ messages Console.Write("\n Received message:"); Console.Write("\n sender is {0}", msg.fromUrl); Console.Write("\n content is {0}\n", msg.content); if (msg.content == "connection start message") continue; // don't send back start message if (msg.content == "done") { Console.Write("\n client has finished\n");continue; } if (msg.content == "closeServer") { Console.Write("received closeServer"); break; } timer.Start(); //start timer XElement insertelem = XElement.Parse(msg.content); XElement res = new XElement("result", "not found"); processor rdbserver = new processor(); Console.WriteLine("\n----------write client operations----------"); Console.WriteLine("\n"); //----------select the required method to perform operations------------// if (insertelem.Element("Type").Value.Equals("Insert")) res = rdbserver.insert(insertelem, dbserver); else if (insertelem.Element("Type").Value.Equals("Delete")) res = rdbserver.Delete(insertelem, dbserver); else if (insertelem.Element("Type").Value.Equals("EditName")) res = rdbserver.EditName(insertelem, dbserver); else if (insertelem.Element("Type").Value.Equals("getvalue")) res = rdbserver.getvalue(insertelem, dbserver, QE); else if (insertelem.Element("Type").Value.Equals("EditDescr")) res = rdbserver.editdescr(insertelem, dbserver); else if (insertelem.Element("Type").Value.Equals("getchildren")) res = rdbserver.getchildren(insertelem, dbserver, QE); else if (insertelem.Element("Type").Value.Equals("Persist")) res = rdbserver.persistdb(insertelem, dbserver); else Console.Write(" operation failed "); Console.WriteLine("\n-------------server response----------"); XElement response = new XElement("resonse"); response.Add(res); timer.Stop(); //stop timer Console.WriteLine("the time taken for operation is {0}", timer.ElapsedMicroseconds + " MicroSeconds "); srvr.send_wpf_msg(timer.ElapsedMicroseconds, sndr); Util.swapUrls(ref msg); msg.content = response.ToString(); sndr.sendMessage(msg); //sending message } }; if (rcvr.StartService()) rcvr.doService(serviceAction); // This serviceAction is asynchronous so the call doesn't block. Util.waitForUser(); } }
void TestR7() { "Demonstrating Requirement #7".title('='); WriteLine(); "Adding elements to db".title(); WriteLine(); for (int i = 0; i < 3; i++) { DBElement<int, string> elem = new DBElement<int, string>(); elem.name = "element"; elem.descr = "test element"; elem.timeStamp = new DateTime(2015,10,(2+i)); elem.children.AddRange(new List<int> { 1, 2, 3 }); elem.payload = "elem's payload"; elem.showElement(); WriteLine(); db.insert(12345+i, elem); } "current DB status:".title(); db.showDB(); IQuery<int, DBElement<int, string>> i_query = new DBEngine<int, DBElement<int, string>>(); QueryEngine<int, DBElement<int, string>> qe = new QueryEngine<int, DBElement<int, string>>(db); QueryPredicate qp = new QueryPredicate(); qp.key_value_search(db, i_query, qe); WriteLine(); qp.key_children_search(db, i_query, qe); WriteLine(); qp.pattern_matching(db, i_query, qe); WriteLine(); qp.default_pattern_matching(db, i_query, qe); WriteLine(); qp.metadata_string(db, i_query, qe); WriteLine(); qp.date_time_specific(db, i_query, qe); WriteLine(); qp.default_date_time_specific(db,i_query, qe); WriteLine(); }
static void Main(string[] args) { "Testing ItemEditor Package".title('='); Console.WriteLine(); DBEngine<int, DBElement<int, string>> db = new DBEngine<int, DBElement<int, string>>(); DBElement<int, string> elem1 = new DBElement<int, string>(); elem1.name = "India"; elem1.descr = "Country"; elem1.timeStamp = DateTime.Now; elem1.children.AddRange(new List<int> { 2, 3 }); elem1.payload = "Famous cricket player"; db.insert(1, elem1); DBElement<int, string> elem2 = new DBElement<int, string>(); //Add new key/value pairs to the database elem2.name = "Roger federer"; elem2.descr = "Tennis player"; elem2.timeStamp = DateTime.Now.AddDays(-15); elem2.children.AddRange(new List<int> { 3 }); elem2.payload = "Famous tennis player"; db.insert(2, elem2); DBElement<int, string> elem3 = new DBElement<int, string>(); elem3.name = "Usain Bolt"; elem3.descr = "Athelte"; elem3.timeStamp = DateTime.Now; elem3.children.AddRange(new List<int> { 1 }); elem3.payload = "Fastest in the world"; db.insert(3, elem3); Console.WriteLine(); db.showDB(); "\n1) Fetch Value for key 3".title(); var val = db.getValueOfKey(3); val.showElement(); Console.WriteLine(); QueryEngine<int,DBElement<int,string>> qEngine = new QueryEngine<int, DBElement<int, string>>(db); "\n2) Fetch the children of key 1".title(); var children = qEngine.getChildrenOfKey(1); displayChildren(children); DBEngine<string, DBElement<string, List<string>>> db2 = new DBEngine<string, DBElement<string, List<string>>>(); "\n 3) Fetch the keys which starts with r in the below database with key/value pairs".title(); //Taking new database with string keys DBElement<string, List<string>> elem4 = new DBElement<string, List<string>>(); elem4.name = "Christ college"; elem4.descr = "College where the person studied"; elem4.timeStamp = DateTime.Now; elem4.children.AddRange(new List<string> { "rakesh" }); elem4.payload = new List<string> { "One", "Two", "Three", "Four" }; db2.insert("saahith", elem4); DBElement<string, List<string>> elem5 = new DBElement<string, List<string>>(); elem5.name = "PESIT college"; elem5.descr = "College where the person pursued undergraduation"; elem5.timeStamp = DateTime.Now.AddDays(-2); elem5.children.AddRange(new List<string> { "saahith" }); elem5.payload = new List<string> { "Five", "Six", "Seven", "Eight" }; db2.insert("rakesh", elem5); db2.showEnumerableDB(); WriteLine(); QueryEngine<string, DBElement<string, List<string>>> qEngine2 = new QueryEngine<string, DBElement<string, List<string>>>(db2); string pattern1 = @"(^r)"; var spKeys = qEngine2.getListStringKeyPattern(pattern1); displayStringKeys(spKeys); "\n4) Fetch keys with metadata pattern 'Country'".title(); string pattern = "Country"; var mdKeys = qEngine.getListMetaDataPattern(pattern); displayKeys(mdKeys); "\n5) Fetch keys which are created between two dates 29th sept 2015 and 15th oct 2015".title(); DateTime time1 = new DateTime(2015, 9, 29); DateTime time2 = new DateTime(2015, 10, 15); var tpKeys = qEngine.getListTimePattern(time1, time2); displayKeys(tpKeys); }
public virtual bool Any <T>() where T : class { //OK, to not be wrapped in Try, since QueryEngine does this return(QueryEngine.Any <T>()); }
/* Defining a query using lambda function to search specific string in metadata */ public bool metadata_string(DBEngine<string, DBElement<string, List<string>>> db, out IQuery<string, DBElement<string, List<string>>> i_query, QueryEngine<string, DBElement<string, List<string>>> qe, string metadata_str = "ele") { "Query for specified string in metadata: String = 'ele' ".title(); WriteLine(); Func<string, string, bool> stringMetadata = (string key, string search) => //lambda function { if (!db.Keys().Contains(key)) return false; else { DBElement<string, List<string>> ele = new DBElement<string, List<string>>(); db.getValue(key, out ele); if (ele.name.Contains(search) || ele.descr.Contains(search)) return true; else return false; } }; // pass query to query engine and call simpleQuery to make query on DBEngine if (qe.simpleQuery(stringMetadata, metadata_str, out i_query)) { WriteLine(); foreach (var key in i_query.Keys()) { DBElement<string, List<string>> temp = new DBElement<string, List<string>>(); i_query.getValue(key, out temp); WriteLine("key : {0}", key); temp.showEnumerableElement(); WriteLine(); } return true; } else { return false; } }
public void TestR7() { "Demonstrating Requirement #7".title('='); WriteLine(); "Adding elements to db".title(); WriteLine(); for (int i = 0; i < 3; i++) { DBElement<string, List<string>> elem = new DBElement<string, List<string>>(); elem.name = "element"; elem.descr = "test element"; elem.timeStamp = new DateTime(2015,10,(2+i)); elem.children.AddRange(new List<string> { "one", "two", "three" }); elem.payload = new List<string>{ "elem's payload1","payload2","payload 3"}; elem.showEnumerableElement(); WriteLine(); enum_db.insert((12345+i).ToString(), elem); } "current DB status:".title(); enum_db.showEnumerableDB(); IQuery<string, DBElement<string, List<string>>> i_query = new DBEngine<string, DBElement<string, List<string>>>(); QueryEngine<string, DBElement<string, List<string>>> qe = new QueryEngine<string, DBElement<string, List<string>>>(enum_db); QueryPredicate qp = new QueryPredicate(); qp.key_value_search(enum_db, out i_query, qe); WriteLine(); qp.key_children_search(enum_db, out i_query, qe); WriteLine(); qp.pattern_matching(enum_db, out i_query, qe, "12345"); WriteLine(); qp.pattern_matching(enum_db, out i_query, qe); WriteLine(); qp.metadata_string(enum_db, out i_query, qe); WriteLine(); DateTime start = new DateTime(2015, 10, 4); DateTime end = new DateTime(2015, 10, 5); qp.date_time_specific(enum_db, out i_query, qe, start, end); WriteLine(); qp.default_date_time_specific(enum_db, out i_query, qe, start); WriteLine(); }
static void Main(string[] args) { DBEngine<string, DBElement<string, List<string>>> db = new DBEngine<string, DBElement<string, List<string>>>(); for (int i = 0; i < 3; i++) { DBElement<string, List<string>> elem = new DBElement<string, List<string>>(); elem.name = "element"; elem.descr = "test element"; elem.timeStamp = new DateTime(2015, 10, (2 + i)); elem.children.AddRange(new List<string> { "element1", "element2", "element3" }); elem.payload = new List<string> { "elem's payload1", "elem's payload2" }; elem.showEnumerableElement(); WriteLine(); db.insert("element"+(12345 + i).ToString(), elem); } for (int i = 0; i < 3; i++) { DBElement <string, List<string>> elem = new DBElement<string, List<string>>(); elem.name = "db data"; elem.descr = "db data description"; elem.timeStamp = DateTime.Now; elem.children.AddRange(new List<string> { "element12345", "element12346", "element12347" }); elem.payload = new List<string> { "elem's payload1", "elem's payload2" }; elem.showEnumerableElement(); WriteLine(); db.insert("element"+(i+1).ToString(), elem); } IQuery<string, DBElement<string, List<string>>> i_query = new DBEngine<string, DBElement<string, List<string>>>(); QueryEngine<string, DBElement<string, List<string>>> qe = new QueryEngine<string, DBElement<string, List<string>>>(db); //<---- creating a query predicate object and calling each query on given test database ---> QueryPredicate qp = new QueryPredicate(); qp.key_value_search(db, i_query, qe); WriteLine(); qp.key_children_search(db, i_query, qe); WriteLine(); qp.pattern_matching(db, i_query, qe); WriteLine(); qp.default_pattern_matching(db, i_query, qe); WriteLine(); qp.metadata_string(db, i_query, qe); WriteLine(); qp.date_time_specific(db, i_query, qe); WriteLine(); qp.default_date_time_specific(db, i_query, qe); WriteLine(); }
public virtual int Count <T>() where T : class { //OK, to not be wrapped in Try, since QueryEngine does this return(QueryEngine.Count <T>()); }
/* Defining a query using lambda function to search children of specific element */ public bool key_children_search(DBEngine<string, DBElement<string, List<string>>> db, out IQuery<string, DBElement<string, List<string>>> i_query, QueryEngine<string, DBElement<string, List<string>>> qe, string specific_key = "element2") { "Query for children of specified key (key = element2):".title(); WriteLine(); Func<string, string, bool> childrenQuery = (string key, string search) => //lambda function { if (!db.Keys().Contains(key)) return false; if (key == (search)) { DBElement<string, List<string>> ele = new DBElement<string, List<string>>(); db.getValue(key, out ele); return true; } else return false; }; // pass query to query engine and call simpleQuery to make query on DBEngine if (qe.simpleQuery(childrenQuery, specific_key.ToString(), out i_query)) { WriteLine(); display_children(i_query, db); return true; } else { return false; } }
public static void Main() { "Testing QueryEngine Package".title('='); Console.WriteLine(); QueryEngine queryv = new QueryEngine(); DBEngine <int, DBElement <int, string> > newdbq = new DBEngine <int, DBElement <int, string> >(); DBEngine <string, DBElement <string, List <string> > > newdbqs = new DBEngine <string, DBElement <string, List <string> > >(); DBElement <int, string> newqelem1 = new DBElement <int, string>(); DBElement <int, string> newqelem2 = new DBElement <int, string>(); DBElement <int, string> newqelem3 = new DBElement <int, string>(); newqelem1.name = "query elemnt 1"; newqelem1.descr = "testing qurey get value for 1"; newqelem1.payload = "new query element payload 1"; newqelem1.children.AddRange(new List <int> { 1, 22, 333 }); newqelem2.name = "query elemnt 2"; newqelem2.descr = "testing query get value for 2"; newqelem2.payload = "new query element payload 2"; newqelem2.children.AddRange(new List <int> { 010, 020, 030 }); newqelem3.name = "query elemnt 3"; newqelem3.descr = "testing quey get value for 3"; newqelem3.payload = "new query element payload 3"; newqelem3.children.AddRange(new List <int> { 777, 222, 333 }); newdbq.insert(1, newqelem1); newdbq.insert(2, newqelem2); newdbq.insert(3, newqelem3); newdbq.showDB(); DBElement <int, string> displayres = new DBElement <int, string>(); Console.WriteLine("\n \n getting value for key 2"); displayres = queryv.queryvalue <int, DBElement <int, string>, string>(newdbq, 2); if (displayres != null) { displayres.showElement(); } Console.WriteLine("\n \n getting children for key 3"); List <int> childlist = new List <int>(); childlist = queryv.querychildren <int, DBElement <int, string>, string>(newdbq, 3); if (childlist != null) { foreach (int i in childlist) { Console.WriteLine(i); } } DBElement <string, List <string> > newelem1q = new DBElement <string, List <string> >(" element 1", "1 is first"); DBElement <string, List <string> > newelem2q = new DBElement <string, List <string> >(" element 2", "2 is second"); DBElement <string, List <string> > newelem3q = new DBElement <string, List <string> >(" element 3", " 3 is third"); newelem1q.children.AddRange(new List <string> { " one", "one", "one" }); newelem1q.payload = new List <string> { "h", "e", "l", "l", "o" }; newelem2q.children.AddRange(new List <string> { " two", "two", "two" }); newelem2q.payload = new List <string> { "h", "d", "w", "f", "b" }; newelem3q.children.AddRange(new List <string> { " three", "three", "three" }); newelem3q.payload = new List <string> { "a", "e", "i", "o", "u" }; newdbqs.insert("one", newelem1q); newdbqs.insert("two", newelem2q); newdbqs.insert("three", newelem3q); newdbqs.showEnumerableDB(); DBElement <string, List <string> > valuestring = new DBElement <string, List <string> >(); Console.WriteLine("\n \n getting value for key 2"); valuestring = queryv.queryvalue <string, DBElement <string, List <string> >, string>(newdbqs, "two"); if (valuestring != null) { valuestring.showEnumerableElement(); } DBElement <string, List <string> > valuestrings = new DBElement <string, List <string> >(); Console.WriteLine("\n \n getting children for key five"); List <string> childlists = new List <string>(); childlists = queryv.querychildren <string, DBElement <string, List <string> >, string>(newdbqs, "five"); if (childlists != null) { foreach (string cstring in childlists) { Console.WriteLine(cstring); } } }
static void Main(string[] args) { "Testing DBFactory Package".title('='); WriteLine(); "\nCreation of immutable database".title(); WriteLine(); "\nOriginal database".title(); DBEngine<int, DBElement<int, string>> db = new DBEngine<int, DBElement<int, string>>(); DBElement<int, string> elem1 = new DBElement<int, string>(); elem1.name = "India"; elem1.descr = "Country"; elem1.timeStamp = DateTime.Now; elem1.children.AddRange(new List<int> { 2, 3 }); elem1.payload = "Famous cricket player"; db.insert(1, elem1); DBElement<int, string> elem2 = new DBElement<int, string>(); elem2.name = "Roger federer"; elem2.descr = "Tennis player"; elem2.timeStamp = DateTime.Now.AddDays(-15); elem2.children.AddRange(new List<int> { 3 }); elem2.payload = "Famous tennis player"; db.insert(2, elem2); DBElement<int, string> elem3 = new DBElement<int, string>(); elem3.name = "Usain Bolt"; elem3.descr = "Athelte"; elem3.timeStamp = DateTime.Now; elem3.children.AddRange(new List<int> { 1 }); elem3.payload = "Fastest in the world"; db.insert(3, elem3); DBElement<int, string> elem4 = new DBElement<int, string>(); elem4.name = "Saina Nehwal"; elem4.descr = "Badminton Player"; elem4.timeStamp = DateTime.Now; elem4.children.AddRange(new List<int> { 2 }); elem4.payload = "Famous badminton player"; db.insert(4, elem4); db.showDB(); WriteLine(); "\n Fetch all the keys which are even from the above database".title(); try { QueryEngine<int, DBElement<int, string>> qEngine = new QueryEngine<int, DBElement<int, string>>(db); Dictionary<int, DBElement<int, string>> dictFactory = new Dictionary<int, DBElement<int, string>>(); DBFactory<int, DBElement<int, string>> dbFactory; var keys = qEngine.getListKeyPattern(); if (keys != null) { foreach (var key in keys) { var val = db.getValueOfKey(key); dictFactory.Add(key, val); //add keys and values to the dictionary } dbFactory = new DBFactory<int, DBElement<int, string>>(dictFactory); //store the dictionary in the WriteLine("\nThe below key/value pairs with even keys pattern are saved as an immutable database\n"); dbFactory.showDB(); //display the immutable database WriteLine(); WriteLine(); } else { WriteLine("\nNo keys are obtained from a query for creation of immutable database\n"); } WriteLine(); WriteLine(); } catch (Exception e) { Console.WriteLine("\n" + e.Message + "\n"); } }
static void Main(string[] args) { QueryEngine <int, DBElement <int, string>, string> qe = new QueryEngine <int, DBElement <int, string>, string>(); QueryEngine <string, DBElement <string, List <string> >, List <string> > qeLOS = new QueryEngine <string, DBElement <string, List <string> >, List <string> >(); DBEngine <int, DBElement <int, string> > db = new DBEngine <int, DBElement <int, string> >(); DBElement <int, string> elem = new DBElement <int, string>(); DBElement <int, string> Result = new DBElement <int, string>(); elem.name = "Test"; elem.descr = "Test descr"; elem.timeStamp = DateTime.Now; elem.children.AddRange(new List <int> { 1, 2, 3 }); elem.payload = "Test Payload"; db.insert(0, elem); DBElement <int, string> elem1 = new DBElement <int, string>(); elem1.name = "Test 1"; elem1.descr = "Test descr 1"; elem1.timeStamp = DateTime.Now; elem1.children.AddRange(new List <int> { 4, 5, 6 }); elem1.payload = "Test Payload 1"; db.insert(1, elem1); DBEngine <string, DBElement <string, List <string> > > dbLOS = new DBEngine <string, DBElement <string, List <string> > >(); DBElement <string, List <string> > elemLOS = new DBElement <string, List <string> >(); DBElement <string, List <string> > ResultLOS = new DBElement <string, List <string> >(); elemLOS.name = "Test"; elemLOS.descr = "Test descr"; elemLOS.timeStamp = DateTime.Now; elemLOS.children = new List <string> { "One", "Two", "Three" }; elemLOS.payload = new List <string> { "Test Payload", "Payload" }; dbLOS.insert("One", elemLOS); DBElement <string, List <string> > elemLOS1 = new DBElement <string, List <string> >(); elemLOS1.name = "Test 2"; elemLOS1.descr = "Test descr 2"; elemLOS1.timeStamp = DateTime.Now; elemLOS1.children = new List <string> { "Four", "Five", "Six" }; elemLOS1.payload = new List <string> { "Test Payload 2", "Payload 2" }; dbLOS.insert("Two", elemLOS1); if (qe.getValue(0, db, out Result)) { WriteLine("Value of key 0:\n{0}\n Payload: {1}", Result.showMetaData(), Result.payload.ToString()); } else { WriteLine("Key not found"); } WriteLine(); if (qeLOS.getValue("One", dbLOS, out ResultLOS)) { WriteLine("Value of key:\n{0}\n Payload: {1}", ResultLOS.showMetaData(), qeLOS.ToString(ResultLOS.payload)); } else { WriteLine("Key not found"); } WriteLine(); if (qe.getChildren(0, db, out children)) { WriteLine("Children of specified key: {0}", qe.ToString(children)); } else { WriteLine("Key not found"); } if (qeLOS.getChildren("One", dbLOS, out childrenLOS)) { WriteLine("Children of specified key: {0}", qeLOS.ToString(childrenLOS)); } else { WriteLine("Key not found"); } WriteLine(); if (qe.searchPattern(0, db, out Keys)) { Console.WriteLine("Set of Keys: {0}", qe.ToString(Keys)); } else { Console.WriteLine("No Keys found!"); } if (qeLOS.searchPattern("O", dbLOS, out KeysLOS)) { Console.WriteLine("Set of Keys: {0}", qeLOS.ToString(KeysLOS)); } else { Console.WriteLine("No Keys found!"); } WriteLine(); if (qe.searchString("descr", db, out Keys)) { Console.WriteLine("Set of Keys: {0}", qe.ToString(Keys)); } else { Console.WriteLine("\nNo Keys found!"); } if (qeLOS.searchString("Test", dbLOS, out KeysLOS)) { Console.WriteLine("Set of Keys: {0}", qeLOS.ToString(KeysLOS)); } else { Console.WriteLine("No Keys found!"); } WriteLine(); if (qe.searchInterval("10/7/1999 12:00:00 AM", "", db, out Keys)) { Console.WriteLine("Set of Keys: {0}", qe.ToString(Keys)); } else { Console.WriteLine("\nNo Keys found!"); } if (qeLOS.searchInterval("10/7/1999 12:00:00 AM", "", dbLOS, out KeysLOS)) { Console.WriteLine("Set of Keys: {0}", qeLOS.ToString(KeysLOS)); } else { Console.WriteLine("No Keys found!"); } WriteLine(); }
public QueryEngineCustomOperators() { GenerateData(1000); // Setup the query engine m_QueryEngine = new QueryEngine <MyCustomObjectType>(); // Id supports all operators m_QueryEngine.AddFilter("id", myObj => myObj.Id); // Setup what data will be matched against search words m_QueryEngine.SetSearchDataCallback(myObj => new[] { myObj.Id.ToString() }); // Extend the set of operators and type parsers // Modulo operator will work on all filters that are integers const string moduloOp = "%"; m_QueryEngine.AddOperator(moduloOp); m_QueryEngine.AddOperatorHandler(moduloOp, (int ev, int fv) => ev % fv == 0); // List operator will work on al filters that have an integer as left hand side and // a list of integers as right hand side var listOp = "?"; m_QueryEngine.AddOperator(listOp); m_QueryEngine.AddOperatorHandler(listOp, (int ev, List <int> values) => values.Contains(ev)); // To correctly parse this new type (because it is not supported by default), we add a type parser m_QueryEngine.AddTypeParser(s => { var tokens = s.Split(','); if (tokens.Length == 0) { return(new ParseResult <List <int> >(false, null)); } var numberList = new List <int>(tokens.Length); foreach (var token in tokens) { if (TryConvertValue(token, out int number)) { numberList.Add(number); } else { return(new ParseResult <List <int> >(false, null)); } } return(new ParseResult <List <int> >(true, numberList)); }); // We an also extend existing operators // Position supports =, !=, <, >, <=, >= m_QueryEngine.AddFilter("p", myObj => myObj.Position, new[] { "=", "!=", "<", ">", "<=", ">=" }); // Extend the =, !=, <, >, <=, >= operators to support comparing Vector2's magnitude m_QueryEngine.AddOperatorHandler("=", (Vector2 ev, Vector2 fv) => Math.Abs(ev.magnitude - fv.magnitude) < float.Epsilon); m_QueryEngine.AddOperatorHandler("!=", (Vector2 ev, Vector2 fv) => Math.Abs(ev.magnitude - fv.magnitude) > float.Epsilon); m_QueryEngine.AddOperatorHandler("<", (Vector2 ev, Vector2 fv) => ev.magnitude < fv.magnitude); m_QueryEngine.AddOperatorHandler(">", (Vector2 ev, Vector2 fv) => ev.magnitude > fv.magnitude); m_QueryEngine.AddOperatorHandler("<=", (Vector2 ev, Vector2 fv) => ev.magnitude <= fv.magnitude); m_QueryEngine.AddOperatorHandler(">=", (Vector2 ev, Vector2 fv) => ev.magnitude >= fv.magnitude); // Add a new type parser for Vector2 m_QueryEngine.AddTypeParser(s => { if (!s.StartsWith("[") || !s.EndsWith("]")) { return(new ParseResult <Vector2>(false, Vector2.zero)); } var trimmed = s.Trim('[', ']'); var vectorTokens = trimmed.Split(','); var vectorValues = vectorTokens.Select(token => float.Parse(token, CultureInfo.InvariantCulture.NumberFormat)).ToList(); Assert.AreEqual(vectorValues.Count, 2); var vector = new Vector2(vectorValues[0], vectorValues[1]); return(new ParseResult <Vector2>(true, vector)); }); // If you don't want to add a multitude of operator handlers, you can define // a generic filter handler that will handle all existing operators on a filter m_QueryEngine.AddFilter <string>("is", IsFilterResolver); }
object IInvokeServiceOps.InvokeServiceOperation(int opCode, object[] args) { MobiusQueryEngineService op = (MobiusQueryEngineService)opCode; switch (op) { case MobiusQueryEngineService.Initialize: { Qel.QueryEngine.InitializeForSession(); return(null); } case MobiusQueryEngineService.CreateInstance: { Qel.QueryEngine instance = new Mobius.QueryEngineLibrary.QueryEngine(); return(instance.Id); } case MobiusQueryEngineService.DisposeInstance: { int instanceId = (int)args[0]; bool disposed = Qel.QueryEngine.Dispose(instanceId); return(disposed); } case MobiusQueryEngineService.SetParameter: { string parm = "", value = ""; if (args.Length == 2) { parm = args[0].ToString(); value = args[1].ToString(); } else // old form (remove when all old clients are updated) { parm = "DatabaseSubset"; value = args[0].ToString(); } Qel.QueryEngine.SetParameter(parm, value); return(null); } case MobiusQueryEngineService.GetSummarizationDetailQuery: { int instanceId = (int)args[0]; string metaTableName = (string)args[1]; string metaColumnName = (string)args[2]; int level = (int)args[3]; string resultId = (string)args[4]; //Qel.QueryEngine qe = null; //lock (Qel.QueryEngine.IdToInstanceDict) //{ // if (Qel.QueryEngine.IdToInstanceDict.ContainsKey(instanceId)) // { // qe = Qel.QueryEngine.IdToInstanceDict[instanceId]; // } //} //if (qe != null) //{ string queryXml = ""; Data.Query query = QueryEngine.GetSummarizationDetailQuery(metaTableName, metaColumnName, level, resultId); if (query != null) { queryXml = query.Serialize(false); } return(queryXml); //} //else //{ // throw new ArgumentException("Not a valid query engine instance id!"); //} } case MobiusQueryEngineService.GetDrilldownDetailQuery: { int instanceId = (int)args[0]; string metaTableName = (string)args[1]; string metaColumnName = (string)args[2]; int level = (int)args[3]; string resultId = (string)args[4]; //Qel.QueryEngine qe = null; //lock (Qel.QueryEngine.IdToInstanceDict) //{ // if (Qel.QueryEngine.IdToInstanceDict.ContainsKey(instanceId)) // { // qe = Qel.QueryEngine.IdToInstanceDict[instanceId]; // } //} //if (qe != null) //{ Mobius.Data.MetaTable metaTable = Mobius.Data.MetaTableCollection.GetExisting(metaTableName); Mobius.Data.MetaColumn metaColumn = metaTable.GetMetaColumnByName(metaColumnName); Data.Query query = QueryEngine.GetDrilldownDetailQuery(metaTable, metaColumn, level, resultId); string queryXml = query.Serialize(false); return(queryXml); //} //else //{ // throw new ArgumentException("Not a valid query engine instance id!"); //} } case MobiusQueryEngineService.GetImage: { string mtMcName = null; int instanceId = (int)args[0]; if (args[1] is string) // New "mtName.mcName" format for arg (Post Client 5.0) { mtMcName = (string)args[1]; } else if (args[1] is MetaColumn) // old Mobius.Services.Types.MetaColumn format { MetaColumn mc = (MetaColumn)args[1]; mtMcName = mc.MetaTable.Name + "." + mc.Name; } else { return(null); // error } Mobius.Data.MetaColumn mobiusMC = Mobius.Data.MetaColumn.ParseMetaTableMetaColumnName(mtMcName); string graphicsIdString = (string)args[2]; int desiredWidth = (int)args[3]; Qel.QueryEngine qe = GetQueryEngineInstance(instanceId); //Mobius.Data.MetaColumn mobiusMC = _transHelper.Convert<MetaColumn, Mobius.Data.MetaColumn>(metaColumn); System.Drawing.Bitmap bitmap = qe.GetImage(mobiusMC, graphicsIdString, desiredWidth); Types.Bitmap result = new Types.Bitmap(bitmap); return(result); } case MobiusQueryEngineService.ResolveCidListReference: { string tok = (string)args[0]; Mobius.Data.UserObject uo = Qel.QueryEngine.ResolveCidListReference(tok); UserObjectNode result = _transHelper.Convert <Mobius.Data.UserObject, UserObjectNode>(uo); return(result); } case MobiusQueryEngineService.GetRootTable: { string queryString = (string)args[0]; Mobius.Data.Query mobiusQuery = Data.Query.Deserialize(queryString); Mobius.Data.MetaTable mobiusMT = Qel.QueryEngine.GetRootTable(mobiusQuery); string mtString = null; if (mobiusMT != null) { mtString = mobiusMT.Serialize(); } return(mtString); } case MobiusQueryEngineService.DoPresearchChecksAndTransforms: { string serializedQuery = (string)args[0]; Data.Query q = Data.Query.Deserialize(serializedQuery); q = Qel.QueryEngine.DoPreSearchTransformations(q); if (q == null) { return(null); } string serializedQuery2 = q.Serialize(true); return(serializedQuery2); } case MobiusQueryEngineService.GetKeys: { int instanceId = (int)args[0]; Qel.QueryEngine qe = GetQueryEngineInstance(instanceId); List <string> keys = qe.GetKeys(); return(keys); } case MobiusQueryEngineService.ExecuteQuery: { int instanceId = (int)args[0]; string serializedQuery = (string)args[1]; Qel.QueryEngine qe = GetQueryEngineInstance(instanceId); Data.Query q = Data.Query.Deserialize(serializedQuery); List <string> result = qe.ExecuteQuery(q, false, false); return(result); } case MobiusQueryEngineService.TransformAndExecuteQuery: { int instanceId = (int)args[0]; string serializedQuery = (string)args[1]; Qel.QueryEngine qe = GetQueryEngineInstance(instanceId); Data.Query q2; Data.Query q = Data.Query.Deserialize(serializedQuery); List <string> keyList = qe.TransformAndExecuteQuery(q, out q2); object[] sa = new object[2]; sa[0] = keyList; if (q2 != null) // any transformed query? { sa[1] = q2.Serialize(true, true); // serialize including metatables not previously send to client } return(sa); } case MobiusQueryEngineService.BuildSqlStatements: { int instanceId = (int)args[0]; string serializedQuery = (string)args[1]; Qel.QueryEngine qe = GetQueryEngineInstance(instanceId); Data.Query q = Data.Query.Deserialize(serializedQuery); string sqlStatements = qe.BuildSqlStatements(q); return(sqlStatements); } case MobiusQueryEngineService.SaveSpotfireSql: { string sqlStmtName = (string)args[0]; string serializedQuery = (string)args[1]; Data.Query q = Data.Query.Deserialize(serializedQuery); int stmtId = Mobius.QueryEngineLibrary.QueryEngine.SaveSpotfireSql(sqlStmtName, q); return(stmtId); } case MobiusQueryEngineService.SaveSpotfireKeyList: { string keyColName, listType, keyList; if (args.Length >= 3) { keyColName = (string)args[0]; listType = (string)args[1]; keyList = (string)args[2]; } else if (args.Length == 2) // old form { keyColName = "CORP_ID"; listType = (string)args[0]; keyList = (string)args[1]; } else // old form for cid list { keyColName = "CORP_ID"; listType = "CIDLIST"; keyList = (string)args[0]; } string keyListName = Mobius.QueryEngineLibrary.QueryEngine.SaveSpotfireKeyList(keyColName, listType, keyList); return(keyListName); } case MobiusQueryEngineService.ReadSpotfireSql: { string sqlStmtName = args[0] as string; int version = (int)args[1]; string sql = Mobius.QueryEngineLibrary.QueryEngine.ReadSpotfireSql(sqlStmtName, version); return(sql); } case MobiusQueryEngineService.RemapTablesForRetrieval: // DoPreRetrievalTransformation { int instanceId = (int)args[0]; Qel.QueryEngine qe = GetQueryEngineInstance(instanceId); Mobius.Data.Query q = qe.DoPreRetrievalTableExpansions(); if (q == null) { return(null); } string serializedQuery = q.Serialize(true); // serialize including metatables not previously included return(serializedQuery); } case MobiusQueryEngineService.NextRowsSerialized: { int minRows = 1; bool returnQeStats = false; List <Mobius.Data.MetaBrokerStats> mbStats = null; int instanceId = (int)args[0]; int ai = 1; if (args.Length >= 4) // newer version with minRows arg { minRows = (int)args[ai++]; } int maxRows = (int)args[ai++]; int maxTime = (int)args[ai++]; if (ai < args.Length) // newer version with returnQeStats arg { returnQeStats = (bool)args[ai++]; } Qel.QueryEngine qe = GetQueryEngineInstance(instanceId); if (returnQeStats) { mbStats = new List <Mobius.Data.MetaBrokerStats>(); } byte[] serializedRows = qe.NextRowsSerialized(minRows, maxRows, maxTime, mbStats); if (!returnQeStats) { return(serializedRows); } else // return serialized rows and stats in a two-element object array { object[] oa = new object[2]; oa[0] = serializedRows; oa[1] = Mobius.Data.MetaBrokerStats.SerializeList(mbStats); return(oa); } } case MobiusQueryEngineService.NextRows: { int minRows = 1; int instanceId = (int)args[0]; int ai = 1; if (args.Length >= 4) // newer version with minRows arg { minRows = (int)args[ai++]; } int maxRows = (int)args[ai++]; int maxTime = (int)args[ai++]; Qel.QueryEngine qe = GetQueryEngineInstance(instanceId); List <object[]> rows = qe.NextRows(minRows, maxRows, maxTime); DataRow dataRow = null; List <DataRow> dataRows = new List <DataRow>(); if (rows == null) { return(dataRows); } for (int ri = 0; ri < rows.Count; ri++) // convert each row { object[] row = rows[ri]; if (row != null) { dataRow = new DataRow(); object[] convertedRow = new object[row.Length]; for (int i = 0; i < row.Length; i++) { convertedRow[i] = _transHelper.ConvertObject(row[i]); } dataRow.Data = convertedRow; } dataRows.Add(dataRow); } return(dataRows); } case MobiusQueryEngineService.NextRow: { int instanceId = (int)args[0]; Qel.QueryEngine qe = GetQueryEngineInstance(instanceId); object[] row = qe.NextRow(); DataRow dataRow = null; if (row != null) { dataRow = new DataRow(); object[] convertedRow = new object[row.Length]; for (int i = 0; i < row.Length; i++) { convertedRow[i] = _transHelper.ConvertObject(row[i]); } dataRow.Data = convertedRow; } return(dataRow); } case MobiusQueryEngineService.Close: { int instanceId = (int)args[0]; Qel.QueryEngine qe = GetQueryEngineInstance(instanceId); qe.Close(); return(true); } case MobiusQueryEngineService.Cancel: { int instanceId = (int)args[0]; Qel.QueryEngine qe = GetQueryEngineInstance(instanceId); qe.Cancel(false); return(true); } case MobiusQueryEngineService.GetQueryEngineState: { int instanceId = (int)args[0]; Qel.QueryEngine qe = GetQueryEngineInstance(instanceId); Mobius.Data.QueryEngineState state = qe.State; QueryEngineState result = _transHelper.Convert <Mobius.Data.QueryEngineState, QueryEngineState>(state); return(result); } case MobiusQueryEngineService.LogExceptionAndSerializedQuery: { string exMsg = (string)args[0]; string serializedQuery = (string)args[1]; Data.Query query = Data.Query.Deserialize(serializedQuery); return(Qel.QueryEngine.LogExceptionAndSerializedQuery(exMsg, query)); } case MobiusQueryEngineService.LogQueryExecutionStatistics: { Qel.QueryEngine.LogQueryExecutionStatistics(); return(null); } case MobiusQueryEngineService.ValidateCalculatedFieldExpression: { string advExpr = (string)args[0]; return(Qel.QueryEngine.ValidateCalculatedFieldExpression(advExpr)); } case MobiusQueryEngineService.CreateQueryFromMQL: { string mql = (string)args[0]; Mobius.Data.Query mobiusQuery = Mobius.Data.MqlUtil.ConvertMqlToQuery(mql); Query result = _transHelper.Convert <Mobius.Data.Query, Query>(mobiusQuery); //translate the result return(result); } case MobiusQueryEngineService.ExecuteMQLQuery: { Mobius.Data.Query q2; int instanceId = (int)args[0]; string mql = (string)args[1]; Qel.QueryEngine qe = GetQueryEngineInstance(instanceId); Mobius.Data.Query q = Mobius.Data.MqlUtil.ConvertMqlToQuery(mql); List <string> result = qe.TransformAndExecuteQuery(q, out q2); return(result); } case MobiusQueryEngineService.GetSelectAllDataQuery: { string mtName = (string)args[0]; string cn = (string)args[1]; string queryXml = ""; Mobius.Data.Query q = QueryEngineLibrary.QueryEngine.GetSelectAllDataQuery(mtName, cn); if (q != null) { queryXml = q.Serialize(false); } return(queryXml); } case MobiusQueryEngineService.GetStandardMobileQueries: { Data.Query[] mobileQueries = QueryEngineLibrary.QueryEngine.GetStandardMobileQueries(); List <Query> queries = new List <Query>(); foreach (Data.Query query in mobileQueries) { Query typesQuery = _transHelper.Convert <Mobius.Data.Query, Query>(query); queries.Add(typesQuery); } return(queries.ToArray()); } case MobiusQueryEngineService.GetMobileQueriesByOwner: { string user = (string)args[0]; Data.Query[] mobileQueries = QueryEngineLibrary.QueryEngine.GetMobileQueriesByOwner(user); List <Query> queries = new List <Query>(); foreach (Data.Query query in mobileQueries) { Query typesQuery = _transHelper.Convert <Mobius.Data.Query, Query>(query); queries.Add(typesQuery); } return(queries.ToArray()); } case MobiusQueryEngineService.GetAdditionalData: { int instanceId = (int)args[0]; string command = (string)args[1]; Qel.QueryEngine qe = GetQueryEngineInstance(instanceId); object o = qe.GetAdditionalData(command); return(o); } case MobiusQueryEngineService.ExportDataToSpotfireFiles: { int instanceId = (int)args[0]; Qel.QueryEngine qe = GetQueryEngineInstance(instanceId); ExportParms ep = ExportParms.Deserialize(args[1] as string); QueryEngineStats qeStats = qe.ExportDataToSpotfireFiles(ep); return(qeStats != null ? qeStats.Serialize() : null); } case MobiusQueryEngineService.CompleteRowRetrieval: { int instanceId = (int)args[0]; Qel.QueryEngine qe = GetQueryEngineInstance(instanceId); QueryEngineStats qeStats = qe.CompleteRowRetrieval(); return(qeStats != null ? qeStats.Serialize() : null); } default: throw new InvalidOperationException("Unrecognized operation: " + (int)op); } }
// function to getchildren public XElement getchildren(XElement dbe, DBEngine<int, DBElement<int, string>> db, QueryEngine QE) { Console.WriteLine("\n The children List is obtained "); QE.querychildren<int, DBElement<int, string>, string>(db, 1); if (QE.Equals(null)) { XElement f = new XElement("result", " no children in list "); return f; } else { XElement s = new XElement("result", " children obtained from the specified key "); return s; } }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OkButton_Click(object sender, EventArgs e) { QueryTable qt; QueryColumn qc, qc2; MetaTable mt; string tName, tableLabel, selectedTableLabel = null, txt; bool b1; int ti, i1; // Get summarization & table position tab info ti = GetSelectedRow(); if (ti >= 0) { selectedTableLabel = (string)DataTable.Rows[ti]["TableNameCol"]; } List <QueryTable> newTables = new List <QueryTable>(); // build new query table list Query.Tables = newTables; // new set of reordered query tables for (i1 = 0; i1 < DataTable.Rows.Count; i1++) { tableLabel = (string)DataTable.Rows[i1]["TableNameCol"]; if (tableLabel == "") { continue; } qt = OriginalQueryTables[tableLabel]; // map text label back to query table if (qt == null) { continue; // shouldn't happen } object cs = DataTable.Rows[i1]["SummarizedCol"]; bool useSummarized = (cs is bool && (bool)cs == true); if ((useSummarized && !qt.MetaTable.UseSummarizedData) || // summary status change? (!useSummarized && qt.MetaTable.UseSummarizedData)) { qt = qt.AdjustSummarizationLevel(useSummarized); } //if (Query.GetQueryTableByName(qt.MetaTable.Name) != null) continue; // don't allow same table twice (comment out, multiples of same table allowed now) newTables.Add(qt); // no change to summary info qt.Query = Query; } if (Query.Tables.Count > 0 && ti < 0) { ti = 0; // in case nothing selected } // Get basic options if (DnfQc.DisplayFormat != ColumnFormatEnum.Unknown) // default number format changed? { SS.I.DefaultNumberFormat = DnfQc.DisplayFormat; Preferences.Set("DefaultNumberFormat", SS.I.DefaultNumberFormat.ToString()); SS.I.DefaultDecimals = DnfQc.Decimals; Preferences.Set("DefaultDecimals", SS.I.DefaultDecimals.ToString()); } txt = QnfStatsTextEdit.Text; Query.StatDisplayFormat = QbUtil.ConvertStatDisplayFormat(txt); if (SS.I.TableColumnZoom != TableColumnZoom.ZoomPct) { SS.I.TableColumnZoom = TableColumnZoom.ZoomPct; Preferences.Set("TableColumnZoom", TableColumnZoom.ZoomPct); } if (SS.I.GraphicsColumnZoom != GraphicsColumnZoom.ZoomPct) { SS.I.GraphicsColumnZoom = GraphicsColumnZoom.ZoomPct; Preferences.Set("GraphicsColumnZoom", GraphicsColumnZoom.ZoomPct); } // Advanced options - query specific Query.DuplicateKeyValues = DuplicateKeyValues.Checked; Query.FilterNullRows = FilterNullRows.Checked; Query.ShowCondFormatLabels = ShowCondFormatLabels.Checked; //Query.BrowseExistingResultsWhenOpened = BrowseExistingResultsWhenOpened.Checked; Query.RunQueryWhenOpened = RunQueryWhenOpened.Checked; Query.SingleStepExecution = CombineSearchAndRetrieval.Checked; //Query.UseCachedData = UseCachedData.Checked; Query.Multitable = Multitable.Checked; // (not visible) Query.Mobile = MobileQuery.Checked; //if (cbDefaultMobileQuery.Checked) Preferences.Set("MobileDefaultQuery",Query.UserObject.Id); // Advanced options - applies to all queries if (RestoreWindowsAtStartup.Checked != SS.I.RestoreWindowsAtStartup) { SS.I.RestoreWindowsAtStartup = !SS.I.RestoreWindowsAtStartup; Preferences.Set("RestoreWindowsAtStartup", SS.I.RestoreWindowsAtStartup); } if (HilightCorpIdChanges.Checked != SS.I.HilightCidChanges) { SS.I.HilightCidChanges = !SS.I.HilightCidChanges; Preferences.Set("HilightCorpIdChanges", SS.I.HilightCidChanges); } if (RemoveLeadingZerosFromCids.Checked != SS.I.RemoveLeadingZerosFromCids) { SS.I.RemoveLeadingZerosFromCids = !SS.I.RemoveLeadingZerosFromCids; Preferences.Set("RemoveLeadingZerosFromCids", SS.I.RemoveLeadingZerosFromCids); } if (RepeatReport.Checked != SS.I.RepeatReport) { SS.I.RepeatReport = !SS.I.RepeatReport; Preferences.Set("RepeatReport", SS.I.RepeatReport); } if (ShowStereoComments.Checked != SS.I.ShowStereoComments) { SS.I.ShowStereoComments = !SS.I.ShowStereoComments; Preferences.Set("ShowStereoComments", SS.I.ShowStereoComments); } if (BreakHtmlPopupsAtPageWidth.Checked != SS.I.BreakHtmlPopupsAtPageWidth) { SS.I.BreakHtmlPopupsAtPageWidth = !SS.I.BreakHtmlPopupsAtPageWidth; Preferences.Set("BreakHtmlPopupsAtPageWidth", SS.I.BreakHtmlPopupsAtPageWidth); } if (DefaultToSingleStepQueryExecution.Checked != MqlUtil.DefaultToSingleStepQueryExecution) { MqlUtil.DefaultToSingleStepQueryExecution = !MqlUtil.DefaultToSingleStepQueryExecution; Preferences.Set("DefaultToSingleStepQueryExecution", MqlUtil.DefaultToSingleStepQueryExecution); // set user preference QueryEngine.SetParameter("DefaultToSingleStepQueryExecution", MqlUtil.DefaultToSingleStepQueryExecution.ToString()); // set in QE for current session } //if (AllowNetezzaUse.Checked != SS.I.AllowNetezzaUse) //{ // SS.I.AllowNetezzaUse = AllowNetezzaUse.Checked; // Preferences.Set("AllowNetezzaUse", SS.I.AllowNetezzaUse); //} b1 = MarkCheckBoxesInitially.Checked; if (b1 != SS.I.GridMarkCheckBoxesInitially) { SS.I.GridMarkCheckBoxesInitially = b1; Preferences.Set("GridMarkCheckBoxesInitially", b1); } if (SS.I.EvenRowBackgroundColor != EvenRowBackgroundColor.Color) { SS.I.EvenRowBackgroundColor = EvenRowBackgroundColor.Color; Preferences.Set("EvenRowBackgroundColor", EvenRowBackgroundColor.Color.ToArgb()); } if (SS.I.OddRowBackgroundColor != OddRowBackgroundColor.Color) { SS.I.OddRowBackgroundColor = OddRowBackgroundColor.Color; Preferences.Set("OddRowBackgroundColor", OddRowBackgroundColor.Color.ToArgb()); } QbUtil.RenderQuery(ti); Progress.Hide(); DialogResult = DialogResult.OK; return; }