public ParseError(ParseErrorType parseErrorType, int lineNum, int columnNum, Lex.Token errorInfo) : base(lineNum, columnNum) { if (errorInfo is Lex.Word) { Lex.Word word = errorInfo as Lex.Word; ErrorInfo = word.Lexeme; } else { ErrorInfo = errorInfo.TokenInfo; } ParseErrorType = parseErrorType; }
/// <summary> /// Delete all user account information and user objects /// </summary> /// <param name="commandLine"></param> /// <returns></returns> public static string DeleteUser( string commandLine) { string tok, msg; Lex lex = new Lex(); lex.OpenString(commandLine); string userName = lex.Get(); bool interactive = Lex.IsNullOrEmpty(userName); while (true) { if (interactive) { userName = InputBoxMx.Show("Enter the Username of the user to delete:", "Delete User", userName); if (Lex.IsNullOrEmpty(userName)) { return(""); } } userName = userName.ToUpper(); UserInfo ui = Security.ReadUserInfo(userName); if (ui == null) { msg = "User doesn't exist: " + userName; if (!interactive) { return(msg); } MessageBoxMx.ShowError(msg); continue; } msg = "Are you sure you want to delete user: "******" (" + ui.FullName + ")"; DialogResult dr = MessageBoxMx.Show(msg, "Delete User", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning); if (dr != DialogResult.Yes) { if (!interactive) { return(""); } else { continue; } } bool result = Security.DeleteUser(userName); if (result == true) { msg = "User deleted: " + userName; } else { msg = "Delete user failed for: " + userName; } if (!interactive) { return(msg); } MessageBoxMx.Show(msg); userName = ""; continue; } }
/// <summary> /// Process command line to create a user /// </summary> /// <param name="commandLine"></param> /// <returns></returns> public static string CreateUser( string commandLine) { string tok, msg; Lex lex = new Lex(); lex.OpenString(commandLine); if (!Security.IsAdministrator(SS.I.UserName)) { return("You must be a Mobius administrator to create users"); } string userName = lex.GetUpper(); // get user name bool interactive = Lex.IsNullOrEmpty(userName); while (true) { UserInfo ui = new UserInfo(); int i1 = userName.IndexOf(@"\"); if (i1 < 0) { i1 = userName.IndexOf(@"/"); // try forward slash } if (i1 < 0) // domain not specified, default is AM { ui.UserName = userName; } else if (i1 > 0) { ui.UserDomainName = userName.Substring(0, i1); ui.UserName = userName.Substring(i1 + 1); } if (interactive) // prompt { DialogResult dr = CreateUserDialog.ShowDialog(ui, "Create User"); if (dr == DialogResult.Cancel) { return(""); } } else { // Syntax: CREATE USER [domain\]userid firstname [mi] lastname [emailAddress] [company] [site] [department] ui.FirstName = Lex.CapitalizeFirstLetters(Lex.RemoveAllQuotes(lex.Get())); tok = Lex.CapitalizeFirstLetters(Lex.RemoveAllQuotes(lex.Get())); if (tok.Length == 1) { ui.MiddleInitial = tok; } else { lex.Backup(); } ui.LastName = Lex.CapitalizeFirstLetters(Lex.RemoveAllQuotes(lex.Get())); ui.EmailAddress = Lex.CapitalizeFirstLetters(Lex.RemoveAllQuotes(lex.Get())); ui.Company = Lex.CapitalizeFirstLetters(Lex.RemoveAllQuotes(lex.Get())); ui.Site = Lex.CapitalizeFirstLetters(Lex.RemoveAllQuotes(lex.Get())); ui.Department = Lex.CapitalizeFirstLetters(Lex.RemoveAllQuotes(lex.Get())); } UserInfo existingUi = Security.ReadUserInfo(ui.UserName); try { Security.CreateUser(ui); if (existingUi == null) { msg = "User successfully created"; } else { msg = "User information updated"; } msg += "\n\n" + "User: "******"\n" + "Domain: " + ui.UserDomainName + "\n" + "First Name: " + ui.FirstName + "\n" + "Middle Initial: " + ui.MiddleInitial + "\n" + "Last Name: " + ui.LastName; } catch (Exception ex) { msg = "User creation failed: " + ex.Message; } if (!interactive) { return(msg); } MessageBoxMx.Show(msg); userName = ""; } }
/** * Renvoit l'arbre syntaxique du code source contenu dans InputPath. * Si une exception survient dans le chargement de la grammaire, pendant * l'analyse lexicale ou pendant l'analyse syntaxique, l'analyse est stoppée. * * @return "Analyse lexicale terminée" s'affiche à l'écran si le code source * est syntaxiquement correct à la grammaire ou une exception est déclenchée * s'il y a une erreur. * * @post G initialisé, Lex initialisé, SymbolToIndex intialisé, ParseTable * initialisé * * @throws Exception */ public Tree <Symbol> Parse() { /* * Cette méthode vérifie que le code source est syntaxiquement * correct par rapport à la grammaire. * * Etape 1: Chargement de l'analyseur lexical * Etape 2: Chargement de la grammaire. * Etape 3: Création de la grammaire étendue. * Etape 4: Calcul des ensembles P1 et S1. * Etape 5: Vérification que la grammaire est bien LL1. * Etape 6: Génération des relations objets Terminal du Lexer -> Index dans la parsing table * (Les index sont calculés à la création d'un Terminal) * Etape 7: Génération de la table de parsing * Etape 8: Analyse syntaxique (+ génération de l'arbre syntaxique) * */ // Analyse Lexicale. // Le fichier contenant le code source sera traduit en // une série d'objets du package Slip.mylexer.* représentant des "Terminal" // dont le dernier est EOF signifiant qu'on a lu tous les symboles. // On utilisera plus bas la méthode nextTerminal() qui renvoit // le prochain symbole à lire. // Si un symbole n'est pas reconnu par l'analyseur lexical, une // exception se déclenche (par exemple ').System.Console.WriteLine("Analyse syntaxique..."); lex = new Lex(inputPath); // Chargement de la grammaire GrammarLoader GL = new GrammarLoader(grammarPath); // Le fichier contenant la grammaire BNF du langage est // traduit en une série de symboles de type Slip.myLL1parser.Terminal // et Slip.myLL1parser.NotTerminal. // Si la syntaxe BNF n'est pas respectée ou si un Non Terminal ne // possède pas au moins une dérivation, une exception se déclenche. // NB: Pour charger une grammaire BNF plus facilement, celle ci // doit respecter certaines normes spécifiées dans la classe GrammarLoader. G = GL.Load(); // Augmentation de la grammaire selon ce schéma: // Pour toute règle: // Y -> alpha X beta // on crée // X2 -> beta Y2 // où alpha, beta sont des terminaux. G.ComputeExtendedRules(); // Calcul des ensembles P1 de chaque symbole en utilisant // l'algorithme du point fixe. G.ComputeP1(); // Calcul des ensembles S1 de chaque symbole "de base". // Tous les ensembles P1 des symboles "prime" deviennent les // ensembles S1 de leur correspondant "de base". G.ComputeS1(); // Vérification que la grammaire est bien LL1. // Condition 1: Pour chaque non terminal X, il ne peut pas exister de // dérivations différentes o et o' de X telle que l'intersection de // p1(o) et p1(o') est non vide. CheckCondition1(); // Condition 2: Pour chaque non terminal X, si p1(X) contient lambda alors l'intersection // de p1(X) et s1(X) doit etre vide. CheckCondition2(); // On crée une relation entre un objet Terminal renvoyé par le Lexer // et son index dans la table de parsing. En effet, la table de parsing // est générée à partir d'objet Terminal de GrammarLoader. GenerateSymbolToIndex(); // Génération de la table de parsing. // Pour chaque règle "de base": // Soit A -> alpha, pour chaque élément "a" de p1(alpha) // on définit table[A, a] : A -> alpha. // // Si lambda est contenu dans p1(alpha), on va aller voir AUSSI dans // l'ensemble s1(alpha) qui sont les terminaux pouvant se trouver après A // puisque p1(alpha) peut etre vide. On fera donc: // Pour tout b dans s1(A): table[A, b] : A -> alpha GenerateParsingTable(); // Pile qui sert à savoir ce qui est attendu comme symbole provenant du lexer Stack <Tree <Symbol> > stack = new Stack <Tree <Symbol> >(); // Premier terminal du code source Terminal t = lex.NextTerminal(); // Ajout d'un élément à la pile, le symbole <PROGRAM> // On encapsule l'élément dans un arbre qui servira à la traduction // en langage interne. Pour l'algorithme, il ne sert à rien. Tree <Symbol> root = new Tree <Symbol>(Grammar.program); stack.Push(root); //System.Console.WriteLine("Analyse syntaxique..."); // Début de l'algorithme while (stack.Count() > 0) { // Récupération du symbole au sommet de la pile Tree <Symbol> tree = stack.Pop(); Symbol x = tree.Element(); //Console.WriteLine("Symbole attendu: " + x); //Console.WriteLine("Symbole en cours: " + t); //Console.WriteLine("Symboles restants sur la pile: " + stack); //Console.WriteLine(); // Si le symbole attendu est non terminal, on va vérifier // que le symbole en cours est identique à ce symbole // ou qu'il est égal à lambda (auquels cas on passera au symbole // suivant de la pile). if (x is Terminal) { if ((x == Grammar.identifier && t is Identifier) || (x == Grammar.constant && t is Constant) || (x == Grammar.control && t is ControlType) || (x == Grammar.myString && t is MyString) || (x == Grammar.selector && t is Selector) || (x == Grammar.all && t is All) || (x == Grammar.myProperty && t is MyProperty) || (x.GetText().Equals(t.GetText()))) { // On remplace le terminal "générique" par celui créé dans le lexer. tree.SetElement(t); // Terminal lu correspond au Terminal attendu, on lit le prochain Terminal. t = lex.NextTerminal(); } else if (x != Grammar.lambda) { //Console.WriteLine(t + ": " + (t.GetType())); throw new ParserException("Symbole " + t + " incorrect. Attendu: " + x); } } // Si le symbole attendu est non terminal, on va récupérer la règle // à appliquer en fonction de celui-ci et du symbole en cours. else if (x is NotTerminal) { int index; // On récupère l'index du symbole en cours dans la parsing table if (t is Identifier) { index = symbolToIndex[Grammar.identifier]; } else if (t is Constant) { index = symbolToIndex[Grammar.constant]; } else if (t is MyString) { index = symbolToIndex[Grammar.myString]; } else if (t is ControlType) { index = symbolToIndex[Grammar.control]; } else if (t is All) { index = symbolToIndex[Grammar.all]; } else if (t is Selector) { index = symbolToIndex[Grammar.selector]; } else if (t is MyProperty) { index = symbolToIndex[Grammar.myProperty]; } else { index = symbolToIndex[t]; } // Récupération de la règle Rule r; if ((r = parsingTable[x.Index(), index]) == null) { throw new ParserException("Pas de règle pour " + t.GetText() + " (" + t.GetType() + "). x = " + x.GetText() + " (" + x.GetType() + ")"); } // On ajoute sur la pile tous les symboles présents dans // la règle à exécuter. // On les ajoute dans l'ordre inverse pour qu'on puisse les // retirer dans le bon ordre avec la pile. LinkedList <Symbol> right = r.Right(); int i = right.Count() - 1; while (i > -1) { // On ajoute des enfants à l'arbre contenant le symbole attendu. // Ces enfants contiennent les futurs symboles attendus de la pile. // A la fin de l'algorithme, on aura donc un arbre syntaxique du code source. Tree <Symbol> tmp = new Tree <Symbol>(right.ElementAt(i)); tree.Add(tmp); stack.Push(tmp); i--; } } } // Si le dernier symbole du lexer est le symbole de fin du fichier. On // renvoit l'arbre syntaxique. Sinon on provoque une exception. if (t == SpecialChar.EOF) { //System.Console.WriteLine("Analyse syntaxique terminée."); return(root); } else { throw new ParserException("Dernier symbole différent de EOF."); } }
/// <summary> /// Command entry to execute a query in the background and save the results for later retrieval /// </summary> /// <param name="file"></param> /// <returns></returns> public static string RunBackgroundQuery( string args) { UserObject uo = null; bool sendEmail = false; string emailSubject = null; string msg; int queryId = -1; string[] sa = args.Split(' '); if (sa.Length > 0) { if (int.TryParse(sa[0].Trim(), out queryId)) { uo = UserObjectDao.Read(queryId); } } if (uo == null) { emailSubject = UmlautMobius.String + " background query results error"; msg = "RunQueryInBackground failed to read query " + queryId; ServicesLog.Message(msg); Email.Send( null, SS.I.UserInfo.EmailAddress, emailSubject, msg); return(msg); } if (sa.Length > 1) { bool.TryParse(sa[1].Trim(), out sendEmail); } Query q = Query.Deserialize(uo.Content); q.UserObject = uo; // copy user object to get current name, etc. q.IncludeRootTableAsNeeded(); if (sendEmail) { emailSubject = UmlautMobius.String + " background query results for " + Lex.Dq(q.UserObject.Name); } return(RunBackgroundQuery(q, emailSubject, "MobiusBackgroundQueryEmailTemplate.htm")); }
/// <summary> /// Method to run query in background and save the results for later retrieval /// </summary> /// <param name="q"></param> /// <param name="emailSubject">Send email if defined</param> /// <param name="templateName"></param> /// <returns></returns> public static string RunBackgroundQuery( Query q, string emailSubject, string templateName) { ResultsFormat rf; QueryManager qm; DataTableManager dtm; string msg = "", html = "", resultsFileName; string viewCmd = "View Background Query Results"; bool notifyUserByEmail = !Lex.IsNullOrEmpty(emailSubject); try // execute the query & read in all results { QbUtil.AddQueryAndRender(q, false); // add it to the query builder q.BrowseSavedResultsUponOpen = false; // be sure query is run rather than using existing results msg = QueryExec.RunQuery(q, OutputDest.WinForms); qm = q.QueryManager as QueryManager; dtm = qm.DataTableManager; DialogResult dr = dtm.CompleteRetrieval(); } catch (Exception ex) // some exceptions are normal, e.g. no criteria, others may be bugs { msg = "RunQueryInBackground could not complete due to an unexpected exception: " + DebugLog.FormatExceptionMessage(ex); ServicesLog.Message(msg); if (notifyUserByEmail) { Email.Send(null, SS.I.UserInfo.EmailAddress, emailSubject, msg); } return(msg); } if (dtm.KeyCount == 0) { msg = "Query " + Lex.Dq(q.UserObject.Name) + " returned no results."; if (notifyUserByEmail) { Email.Send(null, SS.I.UserInfo.EmailAddress, emailSubject, msg); } return(msg); } try { resultsFileName = q.ResultsDataTableFileName; // see if name supplied in query if (Lex.IsNullOrEmpty(resultsFileName)) { resultsFileName = "Query_" + q.UserObject.Id + "_Results.bin"; } resultsFileName = ServicesIniFile.Read("BackgroundExportDirectory") + @"\" + resultsFileName; dtm.WriteBinaryResultsFile(resultsFileName); // write the file UserObject cidListUo = SaveBackgroundQueryResultsReferenceObject(qm, "BkgrndQry", resultsFileName); if (!Lex.IsNullOrEmpty(templateName)) { html = ReadTemplateFile(templateName); } if (notifyUserByEmail) { AlertUtil.MailResultsAvailableMessage( // send the mail q, dtm.KeyCount, SS.I.UserInfo.EmailAddress, emailSubject, viewCmd, cidListUo.Id, null, html); } else { html = SubstituteBackgroundExportParameters(html, "", "", dtm.RowCount, dtm.KeyCount, false, ""); return(html); // return the html } } catch (Exception ex) { msg = "Error sending background query results: " + DebugLog.FormatExceptionMessage(ex); ServicesLog.Message(msg); } return(msg); }
/// <summary> /// Update the match counts panel and structure view based on a set of structures and filter values /// </summary> /// <param name="excludeCurrentHitList"></param> /// <param name="rssrs"></param> public void DisplayRelatedStructures( List <StructSearchMatch> fml) { MoleculeMx cs; if (fml == null || fml.Count == 0) { DisplayEmptyStructureGrid(); return; } if (StructureDisplayQuery == null) { BuildStructureDisplayQuery(); // initial setup } Query q = StructureDisplayQuery; QueryTable qt = q.Tables[0]; DataTableMx dt = Qm.DataTable; MoleculeGridControl grid = Qm.MoleculeGrid; grid.BeginUpdate(); dt.Clear(); // filter table HashSet <string> cidSet = new HashSet <string>(); for (int mi = 0; mi < fml.Count; mi++) // build and add the rows to the datatable of structures { StructSearchMatch ssm = fml[mi]; DataRowMx dr = dt.NewRow(); dr[qt.Alias + ".CompoundId"] = ssm.SrcCid; cs = new MoleculeMx(ssm.MolStringFormat, ssm.MolString); if (Lex.IsDefined(ssm.SrcCid)) { cs.SetMolComments("CorpId=" + ssm.SrcCid); // Attach CorpId to Molfile so it will be rendered correctly } if (ssm.SearchType == StructureSearchType.SmallWorld && Lex.IsDefined(ssm.GraphicsString)) { cs.SvgString = ssm.GraphicsString; } dr[qt.Alias + ".Structure"] = cs; dr[qt.Alias + ".MatchType"] = ssm.SearchTypeName; dr[qt.Alias + ".MatchScore"] = ssm.MatchScore; dr[qt.Alias + ".Database"] = ssm.SrcName; dt.Rows.Add(dr); cidSet.Add(ssm.SrcCid); } Qm.DataTableManager.InitializeRowAttributes(); string title = "Related Structures - Matches: " + fml.Count + ", Compound Ids: " + cidSet.Count; Qm.MoleculeGrid.SetTableHeaderCaption(0, title); if (!RSC.MoleculeGridPageControl.Visible) { RSC.MoleculeGridPageControl.Visible = true; } grid.EndUpdate(); ToolHelper.RefreshDataDisplay(Qm); return; }
/// <summary> /// Set the default look and feel /// </summary> /// <param name="lookAndFeelName"></param> public static void SetLookAndFeel( string lookAndFeelName) { if (Instance == null) { Instance = new PreferencesDialog(); } Color mainMenuFontColor = LookAndFeelMx.SetLookAndFeel(lookAndFeelName, Instance.DefaultLookAndFeel.LookAndFeel); int mainMenuLeft = 45; SessionManager sm = SessionManager.Instance; if (sm != null && sm.RibbonCtl != null) { RibbonControl ribbon = sm.RibbonCtl; RibbonViewInfo vi = ribbon.ViewInfo; ribbon.Minimized = true; // be sure minimized if (MobiusIcon == null) { MobiusIcon = ribbon.ApplicationIcon; } if (QuickSearchImageIndex < 0) { QuickSearchImageIndex = sm.QuickSearchControl.ImageIndex; } if (Lex.Contains(lookAndFeelName, "Office 2010")) // || Lex.Contains(lookAndFeelName, "Windows 7")) { // use new style ribbon ribbon.RibbonStyle = RibbonControlStyle.Office2010; ribbon.ShowPageHeadersMode = ShowPageHeadersMode.Hide; ribbon.ApplicationIcon = null; // don't show Mobius icon on application button ribbon.ApplicationButtonText = ""; sm.QuickSearchControl.ImageIndex = -1; } else // Office 2007 ribbon { ribbon.RibbonStyle = RibbonControlStyle.Office2007; ribbon.ApplicationIcon = MobiusIcon; sm.QuickSearchControl.ImageIndex = QuickSearchImageIndex; } // Obsolete //if (sm != null && sm.MainMenuControl != null && sm.ShellForm != null) //{ // MainMenuControl menu = sm.MainMenuControl; // if (ribbon.RibbonStyle == RibbonControlStyle.Office2010) // mainMenuLeft += 14; // menu.Left = mainMenuLeft; // SetMainMenuTopPosition(); // menu.SetFontColor(mainMenuFontColor); //} } DevExpress.LookAndFeel.LookAndFeelHelper.ForceDefaultLookAndFeelChanged(); Application.DoEvents(); // repaint return; /// Get skin element color //DevExpress.Skins.Skin currentSkin = DevExpress.Skins.CommonSkins.GetSkin(PreferencesDialog.Instance.DefaultLookAndFeel.LookAndFeel); //string elementName = DevExpress.Skins.CommonSkins.SkinTextBorder; //DevExpress.Skins.SkinElement element = currentSkin[elementName]; //QueryDescDivider.BackColor = element.Border.All; }
/// <summary> /// Set any display level override values /// </summary> /// <param name="mt"></param> static void NormalizeMetaTable( MetaTable mt) { string tableColumn; if (DisplayLevelOverride == null) { // read in data if necessary DisplayLevelOverride = new Dictionary <string, ColumnSelectionEnum>(); string fileName = ServicesDirs.MetaDataDir + @"\Metatables\DisplayLevelOverride.txt"; StreamReader sr; try { sr = new StreamReader(fileName); } catch (Exception ex) { return; } while (true) { // parse lines of format: <tableName>.<columnName> <selectLevel> string txt = sr.ReadLine(); if (txt == null) { break; } if (txt.StartsWith(";")) { continue; } int i1 = txt.IndexOf(" "); if (i1 <= 0) { continue; } tableColumn = txt.Substring(0, i1).Trim().ToUpper(); ColumnSelectionEnum dl; txt = txt.Substring(i1 + 1).Trim(); if (Lex.Eq(txt, "Selected") || Lex.Eq(txt, "Default") || Lex.Eq(txt, "SelectedByDefault")) { dl = ColumnSelectionEnum.Selected; } else if (Lex.Eq(txt, "Selectable")) { dl = ColumnSelectionEnum.Unselected; } else if (Lex.Eq(txt, "Hidden")) { dl = ColumnSelectionEnum.Hidden; } else { continue; // not recognized } DisplayLevelOverride[tableColumn] = dl; } sr.Close(); } foreach (MetaColumn mc in mt.MetaColumns) { tableColumn = mc.MetaTable.Name.ToUpper() + "." + mc.Name.ToUpper(); if (DisplayLevelOverride.ContainsKey(tableColumn)) { mc.InitialSelection = DisplayLevelOverride[tableColumn]; } if (mc.ColumnMap == null || mc.ColumnMap == "") { mc.ColumnMap = mc.Name; // define map column same as name if not defined } } return; }
public static string GetFIKHB(string inchiKey) { return(Lex.IsDefined(inchiKey) ? inchiKey.Substring(0, 14) : ""); }
private void Timer_Tick(object sender, EventArgs e0) { QueryColumn qc; if (!Timer.Enabled) { return; } Timer.Enabled = false; MouseEventArgs e = LastMouseDownEventArgs; Point p = new Point(e.X, e.Y); GridHitInfo ghi = FieldGridView.CalcHitInfo(p); int ri = ghi.RowHandle; if (ri < 0) { return; } GridColumn gc = ghi.Column; if (gc == null) { return; } int c = gc.AbsoluteIndex; DataRow dRow = FieldDataTable.Rows[ri]; ColumnMapMsx i = dRow["ColumnMapMsxRefCol"] as ColumnMapMsx; // currently item if (i == null) { qc = null; } else { qc = i.QueryColumn; } if (Lex.Eq(gc.FieldName, "FieldDatabaseTableCol") || Lex.Eq(gc.FieldName, "FieldDatabaseColumnCol")) { FieldSelectorControl fieldSelector = new FieldSelectorControl(); fieldSelector.QueryColumn = qc; p = this.PointToScreen(p); SelectColumnOptions sco = new SelectColumnOptions(); sco.ExcludeImages = true; sco.FirstTableKeyOnly = true; sco.SelectFromQueryOnly = true; sco.IncludeNoneItem = true; DialogResult dr = fieldSelector.SelectColumnFromQuery(Query, fieldSelector.QueryColumn, sco, p.X, p.Y, out qc); if (dr != DialogResult.OK) { return; } if (qc != null) { if (i == null) { i = new ColumnMapMsx(); } i.QueryColumn = qc; dRow["FieldSelectedCol"] = true; dRow["ColumnMapMsxRefCol"] = i; dRow["FieldDatabaseTableCol"] = qc.QueryTable.ActiveLabel; dRow["FieldDatabaseColumnCol"] = qc.ActiveLabel; FieldGrid.RefreshDataSource(); } else // set to none { dRow["ColumnMapMsxRefCol"] = null; dRow["FieldDatabaseTableCol"] = dRow["FieldDatabaseColumnCol"] = ""; } if (ri == FieldDataTable.Rows.Count - 1) { // add blank row at end if needed dRow = FieldDataTable.NewRow(); FieldDataTable.Rows.Add(dRow); } } //else if (Lex.Eq(gc.FieldName, "EditAxisPropertiesCol")) //{ // DialogResult dr = AxisOptionsDialog.ShowDialog(ax); // if (dr == DialogResult.OK) Changed = true; //} return; }
/// <summary> /// Allow messages to be sent to different files based on substring matching on message content /// </summary> /// <param name="msg"></param> /// <param name="logFileName"></param> /// <returns></returns> static string AssignSuffixToFileNameBasedOnMessageContent( string msg, string logFileName) { string suffix = null; if (SecondaryErrorMessages != null) // write to secondary message file if msg is in exclusion list { foreach (string msg0 in SecondaryErrorMessages.Keys) { if (Lex.IsUndefined(msg0)) { continue; } if (Lex.Contains(msg, msg0)) { suffix = SecondaryErrorMessages[msg0]; if (Lex.IsUndefined(suffix)) { suffix = "Secondary"; } break; } } } if (Lex.IsUndefined(suffix)) // check special cases before SecondaryErrorMessages may be available { if (Lex.Contains(msg, "ApplicationRecovery_OnApplicationCrash event occurred") || Lex.Contains(msg, "There was no endpoint listening at")) { suffix = "ClientCrash"; } else if (Lex.Contains(msg, "out of range for Vo of size")) { suffix = "VoPosError"; } } if (Lex.IsDefined(suffix)) { if (!suffix.StartsWith(".")) { suffix = "." + suffix; } string ext = Path.GetExtension(logFileName); if (Lex.IsUndefined(ext)) { logFileName += suffix; } else { logFileName = Lex.ReplaceFirst(logFileName, ext, suffix + ext); } } return(logFileName); }
public static string Process( string command) { string tok; Lex lex = new Lex(); lex.OpenString(command); tok = lex.Get(); if (Lex.Eq(tok, "List")) { tok = lex.Get(); } string arg = Lex.RemoveAllQuotes(lex.Get()); if (Lex.Eq(tok, "New")) { return(CreateNewList()); } else if (Lex.Eq(tok, "EditSaved")) { return(EditSaved()); } else if (Lex.Eq(tok, "EditTemp")) { return(EditTemp(arg)); } else if (Lex.Eq(tok, "SaveCurrent")) { return(SaveCurrentCommand()); } else if (Lex.Eq(tok, "SaveCurrentToTemp")) { return(SaveCurrentToTempCommand(arg)); } else if (Lex.Eq(tok, "SaveCurrentToNewTemp")) { return(SaveCurrentToNewTempCommand()); } else if (Lex.Eq(tok, "CopySavedToCurrent")) { return(CopySavedToCurrentCommand()); } else if (Lex.Eq(tok, "CopyTempToCurrent")) { return(CopyTempToCurrentCommand(arg)); } else if (Lex.Eq(tok, "Delete")) { return(DeleteList()); } else if (Lex.Eq(tok, "Logic")) { return(LogicallyCombineLists("")); } else if (Lex.Eq(tok, "Export")) { return(ExportList()); } else if (Lex.Eq(tok, "Import")) { return(ImportList()); } else if (Lex.Eq(tok, "Subset")) { return(SubsetDatabase(arg)); } else { return(tok + " is not a valid List command"); } }
/// <summary> /// Extract any special Corp Stereocomments from molString (usually from Oracle) /// </summary> /// <param name="molString"></param> /// <returns></returns> public static string ExtractStereoComments( ref string molString) { string commentLabel = "\vSTEREO_FLGS:"; string comment = ""; int pos = Lex.IndexOf(molString, commentLabel); if (pos < 0) { return(""); } comment = molString.Substring(pos + commentLabel.Length); molString = molString.Substring(0, pos); // remove from molString string[] sa = comment.Split(','); if (sa.Length < 9) { return(""); // be sure long enough } comment = ""; string noStereo = sa[0]; if (Lex.Eq(sa[1], "T")) // "abs_flg" { if (comment != "") { comment += ", "; } comment += "Absolute"; } if (Lex.Eq(sa[2], "T")) // "unk_flg" { if (comment != "") { comment += ", "; } comment += "Unknown Stereo"; } if (Lex.Eq(sa[2], "T")) // "e_isomer_flg" { if (comment != "") { comment += ", "; } comment += "E Isomer"; } if (Lex.Eq(sa[4], "T")) // "z_isomer_flg" { if (comment != "") { comment += ", "; } comment += "Z Isomer"; } if (Lex.Eq(sa[5], "T")) // "mix_flg" { if (comment != "") { comment += ", "; } comment += "Stereo Mixture"; } if (Lex.Eq(sa[6], "T")) // "rac_flg" { if (comment != "") { comment += ", "; } comment += "Racemic"; } string isomer = sa[7]; // isomer_number if (isomer != "") { if (comment != "") { comment += ", "; } comment += "Isomer " + isomer; } string other = sa[8]; // other_stereo_txt if (other.StartsWith("[") && other.EndsWith("]")) { other = other.Substring(1, other.Length - 2); } if (other != "") { if (comment != "") { comment += ", "; } comment += other; } return(comment); }
/// <summary> /// (OLD VERSION) /// Get list of compounds whose fragments match those of the compounds in the list. /// </summary> /// <param name="cnList"></param> /// <returns></returns> public static Dictionary <string, List <string> > GetAllSaltFormsNew( List <string> cnList) { int t0, t1; t0 = TimeOfDay.Milliseconds(); Dictionary <string, List <string> > cidDict = new Dictionary <string, List <string> >(); List <string> cnList2 = new List <string>(); foreach (string s in cnList) { // get just the list entries that are integers (e.g. remove MFCD numbers) if (Lex.IsInteger(s)) { cnList2.Add(s); } } t1 = TimeOfDay.Milliseconds() - t0; if (cnList2.Count == 0) { return(cidDict); } //MetaTable mt = MetaTableCollection.Get("frag_occurrence"); MetaTable mt = MetaTableCollection.Get("CorpId_salt_isomer_info"); if (mt == null) { return(cidDict); } string sql = mt.TableMap; // get sql to use from metatable if (sql.StartsWith("(")) { sql = sql.Substring(1, sql.Length - 2); // remove surround parens if necessary } sql = Lex.Replace(sql, "where", "where CorpId in (<list>) and "); // add criteria needed to do list search DbCommandMx drd = new DbCommandMx(); try { drd.PrepareListReader(sql, DbType.Int32); drd.ExecuteListReader(cnList2); if (drd.Cancelled) { drd.Dispose(); return(null); } while (true) { if (!drd.ListRead()) { break; } string cn = CompoundId.Normalize(drd.GetInt(0).ToString()); string cn2 = CompoundId.Normalize(drd.GetInt(1).ToString()); if (!cidDict.ContainsKey(cn)) { cidDict[cn] = new List <string>(); } List <string> al = cidDict[cn]; if (al.Count == 0 || al[al.Count - 1] != cn2) // add if not dup { al.Add(cn2); } } drd.Dispose(); } catch (Exception ex) { // catch case non-numeric item in list, single-row subquery returns more than one row, etc. drd.Dispose(); return(new Dictionary <string, List <string> >()); } t1 = TimeOfDay.Milliseconds() - t0; return(cidDict); }
/// <summary> /// Select structures for a list of compound ids using a single SQL cursor. /// </summary> /// <param name="notInCache"></param> /// <param name="mt"></param> /// <param name="strMc"></param> static Dictionary <string, MoleculeMx> SelectChemicalStructuresForCorpIdList( List <string> cidList, MetaTable mt) { List <string> notInCacheKeyList; Dictionary <Int64, string> intKeyToStringKey; DbType parmType; MoleculeMx cs; Int64 intCid; string cid; int li; Stopwatch sw = Stopwatch.StartNew(); Dictionary <string, MoleculeMx> csDict = new Dictionary <string, MoleculeMx>(); List <string> notInCacheList = new List <string>(); // Get structures already in the cache for (li = 0; li < cidList.Count; li++) { cid = cidList[li]; if (RestrictedDatabaseView.KeyIsRetricted(cid)) { continue; } cid = CompoundId.Normalize(cid, mt); if (!Int64.TryParse(cid, out intCid)) { continue; // make sure an integer } if (MoleculeCache.Contains(cid)) // see if in cache { csDict[cid] = MoleculeCache.Get(cid); continue; } else { notInCacheList.Add(cid); } } // Retrieve structures from the database for those not in cache if (notInCacheList.Count == 0) { return(csDict); } MetaColumn strMc = mt.GetMetaColumnByName("molstructure"); if (strMc == null) { return(null); } string tableMap = mt.GetTableMapWithAliasAppendedIfNeeded(); // some SQL (e.g. Postgres) requires an alias for subqueries) string keyColName = mt.KeyMetaColumn.ColumnMap; if (Lex.IsUndefined(keyColName)) { keyColName = mt.KeyMetaColumn.Name; } string strColExpr = strMc.ColumnMap; if (strColExpr == "") { strColExpr = strMc.Name; } if (MqlUtil.IsCartridgeMetaTable(mt)) // selecting from Direct cartridge { if (!Lex.Contains(tableMap, "chime(")) // if no chime expression { strColExpr = "chime(ctab)"; // then create one (gets clob) } strColExpr += ", chime(ctab)"; // add 2nd column that gets clob in case first just gets first 4000 characters } string sql = "select " + keyColName + ", " + strColExpr + " " + "from " + tableMap + " " + "where " + keyColName + " in (<list>)"; DbCommandMx drd = new DbCommandMx(); bool isNumericKey = (mt.KeyMetaColumn.IsNumeric); bool isStringKey = !isNumericKey; if (isStringKey) { parmType = DbType.String; } else { parmType = DbType.Int64; } try { drd.PrepareListReader(sql, parmType); drd.ExecuteListReader(notInCacheList); while (drd.Read()) { if (drd.Rdr.IsDBNull(0)) { continue; } if (isNumericKey) { intCid = drd.GetLong(0); cid = intCid.ToString(); } else // string cid { cid = drd.GetString(0); } cid = CompoundId.Normalize(cid, mt); string molString = drd.GetString(1); cs = new MoleculeMx(MoleculeFormat.Chime, molString); csDict[cid] = cs; MoleculeCache.AddMolecule(cid, cs); } drd.Dispose(); int msTime = (int)sw.ElapsedMilliseconds; return(csDict); } catch (Exception ex) { if (drd != null) { drd.Dispose(); } throw new Exception( "SelectStructuresForCorpIdList, table: " + mt.Name + "\n" + "sql: " + OracleMx.FormatSql(sql) + "\n"); } }
/// <summary> /// Calculate & persist metatable stats for tables belonging to broker /// </summary> /// <returns></returns> public int UpdateMetaTableStatistics() { Dictionary <string, MetaTableStats> stats = new Dictionary <string, MetaTableStats>(); //return stats.Count; // debug foreach (MetaTable mt in MetaTableCollection.TableMap.Values) { if (String.IsNullOrEmpty(mt.RowCountSql) && String.IsNullOrEmpty(mt.UpdateDateTimeSql)) { continue; // if no sql defined for stats then skip } string mtName = mt.Name.ToUpper(); // Get row count string rowCountSql = null; if (Lex.Eq(mt.RowCountSql, "TableMap")) // use native source { rowCountSql = "select count(*) from " + mt.TableMap; } else if (mt.RowCountSql != "") // use table-specific sql { rowCountSql = mt.RowCountSql; } if (rowCountSql != null) { try { int rowCount = SelectSingleValueDao.SelectInt(rowCountSql); if (!stats.ContainsKey(mtName)) { stats[mtName] = new MetaTableStats(); } stats[mtName].RowCount = rowCount; } catch (Exception ex) { continue; } } // Get date string dateSql = null; if (Lex.Eq(mt.UpdateDateTimeSql, "TableMap")) // use native source { for (int mci = mt.MetaColumns.Count - 1; mci >= 0; mci--) { // search backwards for date col MetaColumn mc = mt.MetaColumns[mci]; if (mc.DataType == MetaColumnType.Date) { dateSql = "select max(" + mc.Name + ") from " + mt.TableMap + " where " + mc.Name + " <= current_date"; break; } } } else if (mt.UpdateDateTimeSql != "") // use table-specific sql { dateSql = mt.UpdateDateTimeSql; } if (dateSql != null) { try { if (!stats.ContainsKey(mtName)) { stats[mtName] = new MetaTableStats(); } DateTime dt = SelectSingleValueDao.SelectDateTime(dateSql); stats[mtName].UpdateDateTime = dt; } catch (Exception ex) { continue; } } } string fileName = MetaTableXmlFolder + @"\GenericMetaTableStats"; WriteMetaTableStats(stats, fileName); return(stats.Count); }
private void ConsumeToken() { CurrentToken = Lex.GetToken(); }
/// <summary> /// Get related compound ids & update display /// </summary> /// <param name="parm"></param> void SearchAndRetrieveRelatedStructuresThreadMethod(object parm) { try { int searchId = 0; // id for search associated with this thread lock (RSMLock) { SearchCounter++; // assign id for the search associated with this thread searchId = SearchCounter; } RelatedStructureSearchResults rss = RelatedStructureSearchResults.SearchHistory(Cid, CidMtName); if (rss == null || Lex.IsUndefined(Cid) || Lex.IsUndefined(CidMtName) || !UseCachedResults) { PendingStatusMessage = "Searching..."; rss = new RelatedStructureSearchResults(); rss.Cid = Cid; rss.CidMtName = CidMtName; if (Debug) { DebugLog.Message("=== Client === " + searchId + ". Starting search for CID: " + Cid + " ========="); } string hitString = MoleculeUtil.GetRelatedMatchCounts(Cid, CidMtName, QueryStruct.GetChimeString(), SearchTypes, searchId); if (Superseded(searchId)) { return; // return now if superceded and no longer needed } if (Debug) { DebugLog.Message("=== Client === " + searchId + ". Search step complete: " + hitString); } if (Lex.IsUndefined(hitString)) { if (Debug) { DebugLog.Message("=== Client === " + searchId + ". Hit string is undefined."); } return; } string[] sa = hitString.Split(';'); if (sa.Length != 10) { return; } rss.AltCorpDbCnt = int.Parse(sa[0]); rss.SimCorpDbCnt = int.Parse(sa[1]); rss.MmpCorpDbCnt = int.Parse(sa[2]); rss.SwCorpDbCnt = int.Parse(sa[3]); rss.CorpDbCnt = int.Parse(sa[4]); rss.AltChemblCnt = int.Parse(sa[5]); rss.SimChemblCnt = int.Parse(sa[6]); rss.MmpChemblCnt = int.Parse(sa[7]); rss.SwChemblCnt = int.Parse(sa[8]); rss.ChemblCnt = int.Parse(sa[9]); RelatedStructureSearchResults.History.Add(rss); } RelatedStructuresResults = rss; RenderResultsRequested = true; // request render of initial results if (rss.CorpDbCnt <= 0 && rss.ChemblCnt <= 0) // if no hits then assign empty structure list and don't do retrieve { rss.MatchList = new List <StructSearchMatch>(); } if (rss.MatchList == null) // retrieve structures if structure list doesn't exist { if (Debug) { DebugLog.Message("=== Client === " + searchId + ". Starting structure retrieval..."); } PendingStatusMessage = "Retrieving..."; rss.Cid = Cid; rss.CidMtName = CidMtName; List <StructSearchMatch> ssml = MoleculeUtil.GetRelatedMatchRows(Cid, CidMtName); if (Superseded(searchId)) { return; // return now if superceded and no longer needed } rss.MatchList = ssml; if (Debug) { DebugLog.Message("=== Client === " + searchId + ". Structure retrieval complete"); } } else { if (Debug) { DebugLog.Message("=== Client === " + searchId + ". Already have structures"); } } PendingStatusMessage = ""; RenderResultsRequested = true; // request render of associated structures StructureRetrievalCompletedRenderRequest = true; if (Debug) { DebugLog.Message("=== Client === " + searchId + ". Search and retrieval complete"); } return; } catch (Exception ex) // log any exception since any thrown exception for thread can't be caught { DebugLog.Message(ex); } }
/// <summary> /// Draw conditional formatting field value headers with appropriate background color /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Grid_CustomDrawFieldValue(object sender, PivotCustomDrawFieldValueEventArgs e) { string txt; PivotGridFieldContext fc = GetPivotGridFieldContext(e.Field); if (fc == null) { return; } ResultsField rfld = fc.ResultsField; if (rfld == null) { return; } //DebugLog.Message(rfld.QueryColumn.MetaColumn.Name); //if (rfld.QueryColumn.MetaColumn.Name == "ACTIVITY_BIN") rfld = rfld; // debug //if (e.DisplayText == "0") e = e; // debug CondFormat cf = rfld.QueryColumn.CondFormat; if (cf == null || cf.Rules.Count == 0) { return; } foreach (CondFormatRule rule in cf.Rules) { // look for rule name that matches field value text if (Lex.Eq(rule.Name, e.DisplayText) || Lex.Eq(rule.Value, e.DisplayText)) { if (!Lex.IsNullOrEmpty(rule.Name)) { txt = rule.Name; // display rule name if defined } else { txt = e.DisplayText; // otherwise display field value } Rectangle rect = e.Bounds; ControlPaint.DrawBorder3D(e.Graphics, e.Bounds); Brush brush = e.GraphicsCache.GetSolidBrush(rule.BackColor1); rect.Inflate(-1, -1); e.Graphics.FillRectangle(brush, rect); e.Appearance.DrawString(e.GraphicsCache, txt, e.Info.CaptionRect); //e.Appearance.DrawString(e.GraphicsCache, e.Info.Caption, e.Info.CaptionRect); foreach (DevExpress.Utils.Drawing.DrawElementInfo info in e.Info.InnerElements) { DevExpress.Utils.Drawing.ObjectPainter.DrawObject(e.GraphicsCache, info.ElementPainter, info.ElementInfo); } e.Handled = true; return; //e.Painter.DrawObject(e.Info); // change tone of skin //e.Graphics.FillRectangle(e.GraphicsCache.GetSolidBrush(Color.FromArgb(50, 0, 0, 200)), e.Bounds); //e.Handled = true; } } return; }
void SetSearchStatusLabelText(string txt) { RSC.SearchStatusLabel.Text = txt; RSC.SearchStatusLabel.Visible = Lex.IsDefined(RSC.SearchStatusLabel.Text); // hide text ctl if no text to avoid hiding part of structure }
/// <summary> /// Open the specified target /// </summary> /// <param name="mtn"></param> public static void OpenMetaTreeNode( MetaTreeNode mtn) { UserObject uo; string tok; int i1; if (mtn == null) { return; } MetaTreeNodeType nodeType = mtn.Type; string target = mtn.Target; //if (!Permissions.UserHasReadAccess(SS.I.UserName, target)) //{ // MessageBoxMx.ShowError("You are not authorized to open: " + mtn.Label); // return; //} if (nodeType == MetaTreeNodeType.MetaTable || // data table types nodeType == MetaTreeNodeType.CalcField || nodeType == MetaTreeNodeType.Annotation || nodeType == MetaTreeNodeType.ResultsView) { QbUtil.AddAndRenderTables(target); //.CallCurrentProcessTreeItemOperationMethod("Open", target); } else if (nodeType == MetaTreeNodeType.CondFormat) { uo = ParseAndReadUserObject(mtn.Name); if (uo == null) { return; } tok = uo.InternalName; CondFormatEditor.EditUserObject(uo.InternalName); } else if (MetaTreeNode.IsFolderNodeType(nodeType)) { if (Lex.StartsWith(target, "USERDATABASE_")) // edit a user compound database { uo = ParseAndReadUserObject(target); if (uo == null) { return; } UserData.OpenExistingUserDatabase(uo); } } else if (nodeType == MetaTreeNodeType.Url) { // open url or execute click function if ((i1 = Lex.IndexOf(target, "ClickFunction")) >= 0) { string cmd = target.Substring(i1 + "ClickFunction".Length + 1); // get function name ClickFunctions.Process(cmd, null); } else if (Lex.Contains(target, "SpotfireWeb")) // link to Spotfire webplayer { SpotfireLinkUI.OpenLink(target); } else { SystemUtil.StartProcess(target); // open in default user browser } } else if (nodeType == MetaTreeNodeType.Action) { // execute action CommandLine.Execute(mtn.Target); } else if (nodeType == MetaTreeNodeType.CnList) // open list { uo = ParseAndReadUserObject(target); if (uo == null) { return; } tok = uo.InternalName; CidListEditor.Edit(tok); } else if (nodeType == MetaTreeNodeType.Query) // open query { uo = ParseAndReadUserObject(target); if (uo == null) { return; } if (uo.Type == UserObjectType.Query) // normal query { tok = uo.InternalName; string nextCommand = QbUtil.OpenQuery(tok); while (!(String.IsNullOrEmpty(nextCommand))) { nextCommand = CommandExec.ExecuteCommand(nextCommand); } } else if (uo.Type == UserObjectType.MultiTable) // multitable query { QbUtil.AddAndRenderTables(target); } } else if (nodeType == MetaTreeNodeType.Library) { CommandExec.ExecuteCommandAsynch("ContentsViewLibAsList " + mtn.Name); } }
/// <summary> /// This method runs in a background process and exports data to the specified destination /// </summary> /// <param name="objectIdString">Id of UserObject containing run parameters in a serialized ResultsFormat</param> /// <param name="templateFileName">Name of template file to use</param> /// <param name="emailResultsHtml">If true then send email otherwise just return html</param> /// <returns></returns> public static string RunBackgroundExport( string objectIdString, string templateFileName, bool emailResultsHtml, out bool copiedToDestinationFile, int alertId = 0) { ResultsFormat rf; Query q; string msg = ""; int objId; //if (ClientState.IsDeveloper) //{ // ServicesLog.Message(SS.I.UserName + ": BackgrounExport Debug"); // //DataTableManager.AllowCaching = false; // DataTableManager.DebugBasics = true; // DataTableManager.DebugCaching = true; //} if (String.IsNullOrEmpty(templateFileName)) { templateFileName = "MobiusBackgroundExportEmailTemplate.htm"; } ServicesLog.Message("RunBackgroundExport started: UserObject id = " + objectIdString); string emailSubject = UmlautMobius.String + " background export results"; copiedToDestinationFile = false; try { if (!int.TryParse(objectIdString, out objId)) { throw new Exception("Invalid UserObjectId"); } UserObject uo = UserObjectDao.Read(objId); if (uo == null) { throw new Exception("UserObject not found"); } QueryManager qm = new QueryManager(); rf = ResultsFormat.Deserialize(uo.Content); if (rf == null) { throw new Exception("Failed to deserialize ResultsFormat"); } string clientFile = rf.OutputFileName; // ultimate file we want to go to rf.OutputFileName = GetServerFileName(rf, objId); // get file name to export to on server & use here temporarily qm.ResultsFormat = rf; rf.QueryManager = qm; q = QbUtil.ReadQuery(rf.QueryId); if (q == null) { throw new Exception("Failed to read query: " + rf.QueryId); } q.IncludeRootTableAsNeeded(); qm.Query = q; q.QueryManager = qm; emailSubject += " for query " + Lex.Dq(q.UserObject.Name); // include query name in subject ResultsFormatFactory rff = new ResultsFormatFactory(rf); rff.Build(); ResultsFormatter fmtr = new ResultsFormatter(qm); DataTableManager dtm = new DataTableManager(qm); dtm.BeginCaching(); // allow caching of DataTable dtm.PurgeDataTableWithoutWritingToCacheFile = true; // skip actual writing of cache since it won't be read back in qm.DataTableManager = dtm; qm.DataTable = DataTableManager.BuildDataTable(rf.Query); // build data table to receive data QueryExec qex = new QueryExec(rf); msg = qex.RunQuery3(rf, false, false); // do the export int compoundCount = 0; int rowCount = 0; QueryEngine qe = qex.QueryEngine; if (qe != null) { compoundCount = qm.DataTableManager.KeyCount; rowCount = qm.DataTableManager.TotalRowsTransferredToDataTable; // use this for accurate row count } dtm.EndCaching(); // close cache file (note: resets key/row counts) if (compoundCount <= 0 || rowCount <= 0) // any results { msg = "Query " + Lex.Dq(q.UserObject.Name) + " returned no results."; Email.Send( null, SS.I.UserInfo.EmailAddress, emailSubject, msg); return(msg); } if (ServerFile.CanWriteFileFromServiceAccount(clientFile)) { // copy to dest file if possible try { FileUtil.CopyFile(rf.OutputFileName, clientFile); copiedToDestinationFile = true; rf.OutputFileName = clientFile; } catch (Exception ex) { ServicesLog.Message("Error copying file from service account: " + clientFile + "\n" + DebugLog.FormatExceptionMessage(ex)); } } string viewCmd = "Retrieve Background Export " + uo.Id; msg = "RunBackgroundExport ended: UserObjectId = " + objectIdString; if (emailResultsHtml) { MailBackgroundExportResults( q, clientFile, rowCount, compoundCount, copiedToDestinationFile, viewCmd, SS.I.UserInfo.EmailAddress, emailSubject, templateFileName); ServicesLog.Message(msg); return(msg); } else // just fill in values & return { string html = ReadTemplateFile(templateFileName); html = SubstituteBackgroundExportParameters( html, "", rf.OutputFileName, rowCount, compoundCount, copiedToDestinationFile, viewCmd); ServicesLog.Message(msg); return(html); } } catch (Exception ex) { if (alertId > 0) { msg += "Alert: " + alertId + " "; } msg += "RunBackgroundExport exception: BackgroundExportId = " + objectIdString + ",\r\n" + DebugLog.FormatExceptionMessage(ex); Email.Send( null, SS.I.UserInfo.EmailAddress, emailSubject, msg); ServicesLog.Message(msg); return(msg); } }
public static ColumnExpressionMsx Parse(string expr) { Lex lex = new Lex(); lex.SetDelimiters(" , ; ( ) [ ]"); lex.OpenString(expr); StringBuilder sb = new StringBuilder(); PositionedToken lastTok = null, leftBracket = null; ColumnExpressionMsx colExpr = new ColumnExpressionMsx(); List <PositionedToken> tokens = new List <PositionedToken>(); // list of tokens seen int parenDepth = 0; while (true) { PositionedToken pTok = lex.GetPositionedToken(); if (pTok == null) { break; } tokens.Add(pTok); if (lastTok != null) { // include same white space between tokens int wsBeg = lastTok.Position + lastTok.Text.Length; sb.Append(expr.Substring(wsBeg, pTok.Position - wsBeg)); } string tok = pTok.Text; if (pTok.Text == "(") { parenDepth++; } else if (pTok.Text == ")") { parenDepth--; } else if (tok == "[") { leftBracket = pTok; } else if (tok == "]") { if (leftBracket != null) { int p = leftBracket.Position + 1; int l = pTok.Position - p; string colName = expr.Substring(p, l); colExpr.ColumnNames.Add(colName); leftBracket = null; } } } return(colExpr); }
/// <summary> /// Retrieve the results of a background export /// Example: Retrieve Background Export 231243 /// </summary> /// <param name="objectIdString">Id of BackgroundExport UserObject containing serialized ResultsFormat</param> /// <returns></returns> public static string RetrieveBackgroundExport( string objectIdString) { ResultsFormat rf; Query q; int objId; QbUtil.SetMode(QueryMode.Build); // be sure in build mode if (!int.TryParse(objectIdString, out objId)) { return("Invalid UserObjectId: " + objectIdString); } UserObject uo = UserObjectDao.Read(objId); if (uo == null) { return("RunInBackground UserObject not found: " + objectIdString); } if (uo.Type != UserObjectType.BackgroundExport) { return("Object is not the expected RunInBackground UserObject type"); } rf = ResultsFormat.Deserialize(uo.Content); if (rf == null) { throw new Exception("Failed to deserialize ResultsFormat: " + objectIdString); } string clientFile = rf.OutputFileName; string serverFile = GetServerFileName(rf, objId); string ext = Path.GetExtension(clientFile); string filter = "*" + ext + "|*" + ext; if (SharePointUtil.IsRegularFileSystemName(clientFile)) { clientFile = UIMisc.GetSaveAsFilename("Retrieve Background Export File", clientFile, filter, ext); } else { clientFile = SharePointFileDialog.GetSaveAsFilename("Retrieve Background Export File", clientFile, filter, ext); } if (String.IsNullOrEmpty(clientFile)) { return(""); } Progress.Show("Retrieving file..."); try { ServerFile.CopyToClient(serverFile, clientFile); } catch (Exception ex) { string msg = "Unable to retrieve cached export file: " + serverFile + "\n" + "to client file: " + clientFile + "\n" + DebugLog.FormatExceptionMessage(ex); ServicesLog.Message(msg); Progress.Hide(); return(msg); } Progress.Hide(); if (Lex.Eq(ext, ".xls") || Lex.Eq(ext, ".xlsx") || Lex.Eq(ext, ".doc") || Lex.Eq(ext, ".docx")) { DialogResult dr = MessageBoxMx.Show("Do you want to open " + clientFile + "?", UmlautMobius.String, MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dr == DialogResult.Yes) { SystemUtil.StartProcess(clientFile); } } return("Background export file retrieved: " + clientFile); }
/// <summary> /// Split an axis expression into a list of column expressions /// </summary> /// <param name="axisExpr"></param> /// <returns></returns> public static List <string> Split(string axisExpr) { List <string> colExprs = new List <string>(); Lex lex = new Lex(); lex.SetDelimiters(" , ( ) "); lex.OpenString(axisExpr); StringBuilder sb = new StringBuilder(); PositionedToken lastTok = null; List <PositionedToken> tokens = new List <PositionedToken>(); // list of tokens seen int parenDepth = 0; while (true) { PositionedToken pTok = lex.GetPositionedToken(); if (pTok == null) { break; } tokens.Add(pTok); if (lastTok != null) { // include same white space between tokens int wsBeg = lastTok.Position + lastTok.Text.Length; sb.Append(axisExpr.Substring(wsBeg, pTok.Position - wsBeg)); } string tok = pTok.Text; if (pTok.Text == "(") { parenDepth++; } else if (pTok.Text == ")") { parenDepth--; } if (Lex.Eq(pTok.Text, ",") && parenDepth == 0 && sb.Length > 0) { colExprs.Add(sb.ToString()); sb.Clear(); } else { sb.Append(tok); } lastTok = pTok; } if (sb.Length > 0) // final col expr { colExprs.Add(sb.ToString()); } return(colExprs); }
/// <summary> /// Setup the dropdown for a Column(s) expression /// </summary> /// <param name="parsedColExpr"></param> /// <param name="axis"></param> /// <param name="visual"></param> /// <param name="b"></param> /// <param name="parentColumnExressionSelectorControl"></param> /// <param name="callerEditValueChanged"></param> public void Setup( ParsedColumnExpressionMsx parsedColExpr, AxisMsx axis, VisualMsx visual, DropDownButton b, ColumnsSelector parentColumnExressionSelectorControl, EventHandler callerEditValueChanged = null) { InSetup = true; ParsedColExpr = parsedColExpr; Axis = axis; Visual = visual; InvokingButton = b; PC = parentColumnExressionSelectorControl; SVM = PC.SVM; CallerEditValueChanged = callerEditValueChanged; DataTableMsx dt = GetSelectorDataTable(); if (dt != null) { TableSelector.Name = dt.Name; } else { TableSelector.Name = ""; } List <DataTableMsx> tables = Axis.GetAllowedDataTables(); ColumnList.Items.Clear(); string selectedColName = null; if (parsedColExpr.ColumnNames.Count > 0) { selectedColName = parsedColExpr.ColumnNames[0]; } foreach (DataColumnMsx col in dt.Columns) { CheckedListBoxItem item = new CheckedListBoxItem(); item.Description = col.Name; if (Lex.Eq(col.Name, selectedColName)) { item.CheckState = CheckState.Checked; } ColumnList.Items.Add(item); } //DataMapControl.ShowSelectedColumnCheckBoxes = true; //DataMapControl.SelectSingleColumn = true; //DataMapControl.ShowTableControls = false; //DataMapControl.Setup(SVM, DataMapSelectedColumnChanged); ////DataMapControl.MobiusTableNameCol.Visible = false; ////DataMapControl.MobiusColNameCol.Visible = false; //DataMapControl.FieldGridView.OptionsView.ColumnAutoWidth = false; ////DataMapControl.FieldGridView.OptionsView.ShowColumnHeaders = false; InSetup = false; return; }
/// <summary> /// Get image & coordinates file from KEGG FTP /// </summary> /// <param name="pathwayId"></param> /// <returns></returns> public static TargetMap GetKeggPathway( string pathwayId) { String ftpPath, rec; if (TargetMapDict == null) { ReadTargetMapDict(); } TargetMap tm = new TargetMap(); tm.Name = pathwayId; tm.Label = pathwayId; // default label tm.Source = "KEGG"; tm.Type = "Pathway"; // Build basic paths string ftpFolder = ServicesIniFile.Read("KeggPathWayFtpDirectory"); // get from here if (String.IsNullOrEmpty(ftpFolder)) { throw new Exception("KeggPathWayFtpDirectory not defined"); } if (!ftpFolder.EndsWith(@"/")) { ftpFolder += @"/"; } // Get map_title file and read title for pathway string filePath = TargetMapDir + @"\map_title.tab"; string pathwayPrefix = pathwayId.Substring(0, 3); string pathwayNbr = pathwayId.Substring(3); // bool download = false; if (!File.Exists(filePath)) { download = true; } while (true) { if (download) { ftpPath = ftpFolder + "map_title.tab"; Download(ftpPath, filePath); } StreamReader sr = new StreamReader(filePath); while (true) { rec = sr.ReadLine(); if (rec == null) { break; } if (!rec.StartsWith(pathwayNbr)) { continue; } string[] sa = rec.Split('\t'); tm.Label = sa[1].Trim() + " (KEGG: " + pathwayId + ")"; break; } sr.Close(); if (!String.IsNullOrEmpty(tm.Label)) { break; // have it } else if (download) // already downloaded but not found { tm.Label = pathwayId; break; } else { // download again if not done yet download = true; continue; } } // Get gif file if (Lex.Ne(pathwayPrefix, "map")) // if not a base level map then in organisms { ftpFolder += @"organisms/"; } ftpFolder += pathwayPrefix + @"/"; ftpPath = ftpFolder + pathwayId + ".gif"; filePath = TargetMapDir + @"\" + pathwayId + ".gif"; Download(ftpPath, filePath); Image img = Image.FromFile(filePath); tm.Bounds = new Rectangle(0, 0, img.Width, img.Height); tm.MarkBounds = true; filePath = TargetMapDir + @"\" + pathwayId + ".png"; // save as .png file that Spotfire can read img.Save(filePath, System.Drawing.Imaging.ImageFormat.Png); tm.ImageType = "png"; tm.ImageFile = Path.GetFileName(filePath); // store just file name // Get coordinates file if (Lex.Eq(pathwayPrefix, "map")) { ftpPath = ftpFolder + pathwayId + "_ec.coord"; filePath = TargetMapDir + @"\" + pathwayId + "_ec.coord"; } else { ftpPath = ftpFolder + pathwayId + "_gene.coord"; filePath = TargetMapDir + @"\" + pathwayId + "_gene.coord"; } Download(ftpPath, filePath); tm.CoordsFile = Path.GetFileName(filePath); TargetMapDict[tm.Name.ToUpper()] = tm; // add to list of maps TargetMapDictByLabel[tm.Label.ToUpper()] = tm; GetMapWithCoords(pathwayId); // read in coords to validate file format // Write out the map file containing basic map data filePath = TargetMapDir + @"\" + pathwayId + ".map"; StreamWriter sw = new StreamWriter(filePath); rec = tm.Name + "\t" + tm.Label + "\t" + tm.Source + "\t" + tm.Type + "\t" + tm.ImageType + "\t" + tm.ImageFile + "\t" + tm.Bounds.Left + "\t" + tm.Bounds.Top + "\t" + tm.Bounds.Right + "\t" + tm.Bounds.Bottom + "\t" + tm.MarkBounds + "\t" + tm.CoordsFile; sw.WriteLine(rec); sw.Close(); return(tm); }
/// <summary> /// Update user /// </summary> /// <param name="commandLine"></param> /// <returns></returns> public static string UpdateUser( string commandLine) { string msg; Lex lex = new Lex(); lex.OpenString(commandLine); if (!Security.IsAdministrator(SS.I.UserName)) { return("You must be a Mobius administrator to update users"); } string userName = lex.GetUpper(); // get user name bool interactive = Lex.IsNullOrEmpty(userName); while (true) { if (interactive) { userName = InputBoxMx.Show("Enter the Username of the user to update:", "Update User", userName); if (Lex.IsNullOrEmpty(userName)) { return(""); } } userName = userName.ToUpper(); UserInfo ui = Security.ReadUserInfo(userName); if (ui == null) { msg = "User doesn't exist: " + userName; if (!interactive) { return(msg); } MessageBoxMx.ShowError(msg); continue; } DialogResult dr = CreateUserDialog.ShowDialog(ui, "Update User"); if (dr == DialogResult.Cancel) { return(""); } try { Security.CreateUser(ui); msg = "User information updated"; } catch (Exception ex) { msg = "User update failed: " + ex.Message; } if (!interactive) { return(msg); } MessageBoxMx.Show(msg); userName = ""; continue; } }
private MetaTable GetMetaTableLevel2( string name) { UserObject uo; Query incQry = null; // included query QueryTable qt, qt1, qt2; QueryColumn qc, qc1, qc2; CalcFieldMetaTable mt; MetaTable mt1, mt2; MetaColumn mc, mc1, mc2, cfMc, cfMcModel; ExecuteQueryParms eqp; string cfLabel = "", mcName, mcLabel; string sql = null, tables = null, exprs = null, criteria = null; int objectId, startingSuffix, ci, i1; string prefix = "calcfield_"; // calculated field metatable names begin with "calcfield_" if (name.ToLower().IndexOf(prefix) != 0) { return(null); } if (Lex.Eq(name, "CALCFIELD_826476")) { name = name; // debug } string tok = name.Substring(prefix.Length); // get the object id try { objectId = Int32.Parse(tok); } catch (Exception ex) { return(null); } uo = UserObjectDao.Read(objectId); if (uo == null) { return(null); } if (!Permissions.UserHasReadAccess(Security.UserName, uo)) { return(null); } CalcField cf = CalcField.Deserialize(uo.Content); if (cf == null) { return(null); } if (cf.FinalResultType == MetaColumnType.Unknown) { return(null); // need a final result type } mt = new CalcFieldMetaTable(); mt.Name = name; mt.CalcField = cf; // include associated CalcField object mt.Label = uo.Name; if (MetaTableFactory.ShowDataSource) // add source to label if requested { mt.Label = MetaTableFactory.AddSourceToLabel(mt.Name, mt.Label); } mt.Description = cf.Description; mt.MetaBrokerType = MetaBrokerType.CalcField; bool keyAdded = false; cfLabel = cf.ColumnLabel; // get any user defined label for result // Add metacolumns for basic calculated field if (cf.CalcType == CalcTypeEnum.Basic && cf.Column1.MetaColumn != null) { cfMcModel = cf.Column1.MetaColumn; tok = cf.Operation; if (Lex.IsNullOrEmpty(cfLabel)) { if (tok.IndexOf("/") == 0) { cfLabel = "Ratio"; } else if (tok.IndexOf("*") == 0) { cfLabel = "Product"; } else if (tok.IndexOf("+") == 0) { cfLabel = "Sum"; } else if (tok.IndexOf("-") == 0) { cfLabel = "Difference"; } else { if (cf.Column1.FunctionEnum == CalcFuncEnum.None) // just use existing col name { cfLabel = cf.Column1.MetaColumn.Label; } else // use function & col name { tok = cf.Column1.Function; i1 = tok.IndexOf("("); if (i1 >= 0) { tok = tok.Substring(0, i1); } if (!tok.EndsWith(" ")) { tok += " "; } tok += cf.MetaColumn1.Label; cfLabel = tok; } } if (cf.IsClassificationDefined) { cfLabel += " Class"; // add class suffix if classifier } } } else if (cf.CalcType == CalcTypeEnum.Advanced && cf.AdvancedExpr != "") { List <MetaColumn> mcList = cf.GetInputMetaColumnList(); if (mcList.Count == 0) { return(null); } cfMcModel = mcList[0]; if (cfLabel == "") { cfLabel = "Value"; } } else { return(null); } mt.Parent = cfMcModel.MetaTable.Parent; // set parent if (mt.Root == mt) { mt.Parent = cfMcModel.MetaTable; // if F1 table is a root set it as parent } // Add key value mc = cfMcModel.MetaTable.KeyMetaColumn; // make copy of first table key field for our key if (mc == null) { return(null); } mc = mc.Clone(); mc.ColumnMap = mc.Name; // map to self mc.MetaTable = mt; mt.AddMetaColumn(mc); keyAdded = true; mc.IsSearchable = cf.IsSearchable; // Add calculated value column mc = new MetaColumn(); mt.AddMetaColumn(mc); mc.MetaTable = mt; mc.Name = "CALC_FIELD"; mc.Label = cfLabel; mc.DataType = cf.FinalResultType; // final result type mc.InitialSelection = ColumnSelectionEnum.Selected; mc.Format = cfMcModel.Format; mc.Width = cfMcModel.Width; mc.Decimals = cfMcModel.Decimals; if (cf.FinalResultType == MetaColumnType.Integer) { mc.Format = ColumnFormatEnum.Decimal; mc.Decimals = 0; } if (cf.FinalResultType == MetaColumnType.Image) { mc.Width = (int)(mc.Width * 2.0); // make CF images wider } mc.IsSearchable = cfMcModel.IsSearchable; if (mc.IsSearchable) // refine searchability { mc.IsSearchable = cf.IsSearchable; } cfMc = mc; // Add metacolumns for the underlying columns that go into the calculation foreach (CalcFieldColumn cfc in cf.CfCols) { if (cfc.MetaColumn == null) { continue; } if (cfc.MetaColumn.IsKey) { continue; // don't add additional key } mc = cfc.MetaColumn.Clone(); mcName = mc.MetaTable.Name + "_" + mc.Name; mc.Name = mt.GetValidMetaColumnName(mcName); mc.DetailsAvailable = false; // no drill-down for now (can cause issues) mc.IsSearchable = false; // no searching for now (can cause issues) mc.ColumnMap = mc.Name; // map to self if (Lex.Eq(mc.Label, cfLabel)) // if same as result start suffix checking at 2 { startingSuffix = 1; } else { startingSuffix = 2; } mc.Label = mt.GetUniqueMetaColumnLabel(mc.Label, startingSuffix); mc.InitialSelection = ColumnSelectionEnum.Hidden; // hide for now mc.TableMap = cfc.MetaColumn.MetaTable.Name + "." + cfc.MetaColumn.Name; // save source table and column //mc.TableMap = cfc.MetaColumn.MetaTable.Name; // save source table and column //mc.ColumnMap = cfc.MetaColumn.Name; mt.AddMetaColumn(mc); } //mt.MetaColumns.Remove(cfMc); // move cf result column to end after the inputs //mt.MetaColumns.Add(cfMc); return(mt); }
/// <summary> /// Word operation /// </summary> /// <param name="command"></param> /// <param name="sArg"></param> /// <param name="nArg1"></param> /// <param name="nArg2"></param> /// <param name="nArg3"></param> /// <param name="nArg4"></param> /// <returns></returns> public static string Call( string command, string sArg, int nArg1, int nArg2, int nArg3, int nArg4, bool bArg) { object missingObj = System.Reflection.Missing.Value; // missing object parameter if (SS.I.DebugFlags[5] != null) // dump out command for debug { ClientLog.Message("Call " + command + " " + sArg); } try // catch any Word exception { //****************************************************************************** if (Lex.Eq(command, "CreateObject")) // create the word object //****************************************************************************** { try { WdApp = new Microsoft.Office.Interop.Word.Application(); } catch (Exception ex) { return "Word failed to start"; } } //****************************************************************************** else if (Lex.Eq(command, "Quit")) { // quit application //****************************************************************************** //Microsoft.Office.Interop.Word.Application. WdApp.Quit(ref missingObj, ref missingObj, ref missingObj); // AutoWrap(DISPATCH_METHOD, NULL, WdApp, L"Quit", 0); } //****************************************************************************** else if (Lex.Eq(command, "Cells.SetWidth")) { //****************************************************************************** WdSel.Cells.SetWidth(nArg1, WdRulerStyle.wdAdjustNone); #if false release_obj(WdTemp); // get current font object AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"Cells", 0); WdTemp = result.pdispVal; SETLONG(Arg1,nArg1); // width in points SETLONG(Arg2,wdAdjustNone); // ruler style, required sArg AutoWrap(DISPATCH_METHOD, &result, WdTemp, L"Setwidth", 2, Arg2, Arg1); VariantClear(&Arg1); VariantClear(&Arg2); #endif } //****************************************************************************** else if (Lex.Eq(command, "DeleteObject")) { //****************************************************************************** WdSel = null; WdTable = null; WdTables = null; WdDoc = null; WdDocs = null; WdApp = null; #if false // Release references, must do lower to higher level... release_obj(WdTemp); release_obj(WdSel); release_obj(WdTable); release_obj(WdTables); release_obj(WdDoc); release_obj(WdDocs); release_obj(WdApp); #endif } //****************************************************************************** else if (Lex.Eq(command, "Close")) { //****************************************************************************** // excelobj.ActiveWorkbook.Close False ' no prompt for save ((_Document)WdDoc).Close(ref missingObj, ref missingObj, ref missingObj); // SETLONG(SaveChanges,wdSaveChanges); // don't prompt // AutoWrap(DISPATCH_METHOD, NULL, WdDoc, L"Close", 1, SaveChanges); // VariantClear(&SaveChanges); } //****************************************************************************** else if (Lex.Eq(command, "Documents.Add")) { // Add a new document //****************************************************************************** WdDocs = WdApp.Documents; WdDoc = WdDocs.Add(ref missingObj, ref missingObj, ref missingObj, ref missingObj); #if false release_obj(WdDocs); // Get active documents AutoWrap(DISPATCH_PROPERTYGET, &result, WdApp, L"Documents", 0); // Get Documents collection WdDocs = result.pdispVal; release_obj(WdDoc); // Add new document AutoWrap(DISPATCH_METHOD, &result, WdDocs, L"Add", 0); WdDoc = result.pdispVal; #endif if (WdDoc == null) return ("Error adding document"); UpdateSelection(); // update selection } //****************************************************************************** else if (Lex.Eq(command, "EndKey")) { //****************************************************************************** Object unit = nArg1; WdSel.HomeKey(ref unit, ref missingObj); // SETLONG(Arg,nArg1); // AutoWrap(DISPATCH_METHOD, &result, WdSel, L"HomeKey", 1, Arg); // VariantClear(&Arg); UpdateSelection(); // update selection } //****************************************************************************** else if (Lex.Eq(command, "Font.Name")) { //****************************************************************************** // WordObj.Selection.Font.Name = sArg WdSel.Font.Name = sArg; #if false release_obj(WdTemp); // get current font object AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"Font", 0); WdTemp = result.pdispVal; SETSTR(Arg,sArg); // set font name AutoWrap(DISPATCH_PROPERTYPUT, &result, WdTemp, L"Name", 1, Arg); VariantClear(&Arg); #endif } //****************************************************************************** else if (Lex.Eq(command, "Font.Size")) { //****************************************************************************** // WordObj.Selection.Font.Size = sArg WdSel.Font.Size = nArg1; #if false release_obj(WdTemp); // get current font object AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"Font", 0); WdTemp = result.pdispVal; SETLONG(Arg,nArg1); // set font size AutoWrap(DISPATCH_PROPERTYPUT, &result, WdTemp, L"Size", 1, Arg); VariantClear(&Arg); #endif } //****************************************************************************** else if (Lex.Eq(command, "Font.Bold")) //****************************************************************************** { if (bArg) WdSel.Font.Bold = -1; else WdSel.Font.Bold = 0; } //****************************************************************************** else if (Lex.Eq(command, "Font.Italic")) //****************************************************************************** { if (bArg) WdSel.Font.Italic = -1; else WdSel.Font.Italic = 0; } //****************************************************************************** else if (Lex.Eq(command, "Font.Subscript")) //****************************************************************************** { WdSel.Font.Subscript = nArg1; #if false release_obj(WdTemp); // get current font object AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"Font", 0); WdTemp = result.pdispVal; SETLONG(Arg,nArg1); // set font size AutoWrap(DISPATCH_PROPERTYPUT, &result, WdTemp, L"Subscript", 1, Arg); VariantClear(&Arg); #endif } //****************************************************************************** else if (Lex.Eq(command, "Font.Superscript")) { //****************************************************************************** WdSel.Font.Superscript = nArg1; #if false release_obj(WdTemp); // get current font object AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"Font", 0); WdTemp = result.pdispVal; SETLONG(Arg,nArg1); // set font size AutoWrap(DISPATCH_PROPERTYPUT, &result, WdTemp, L"Superscript", 1, Arg); VariantClear(&Arg); #endif } //****************************************************************************** else if (Lex.Eq(command, "SetDefaultCellStyle")) //****************************************************************************** { // Cell style (e.g. backcolor) automatically carries down do successive // rows and must be explicitly reset // int rgbBlack = 0; // if (WdSel.Font.Color != (Microsoft.Office.Interop.Word.WdColor)rgbBlack) // WdSel.Font.Color = (Microsoft.Office.Interop.Word.WdColor)rgbBlack; // int rgbWhite = 255 + 255 * 256 + 255 * 65536; // if (WdSel.Cells.Shading.BackgroundPatternColor != (Microsoft.Office.Interop.Word.WdColor)rgbWhite) // WdSel.Cells.Shading.BackgroundPatternColor = (Microsoft.Office.Interop.Word.WdColor)rgbWhite; if (WdSel.Font.Color != Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic) WdSel.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic; if (WdSel.Cells.Shading.BackgroundPatternColor != Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic) WdSel.Cells.Shading.BackgroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic; } //****************************************************************************** else if (Lex.Eq(command, "Font.Color")) //****************************************************************************** { Color c = Color.FromArgb(nArg1); int rgb = c.R + c.G * 256 + c.B * 65536; WdSel.Font.Color = (Microsoft.Office.Interop.Word.WdColor)rgb; } //****************************************************************************** else if (Lex.Eq(command, "BackColor")) //****************************************************************************** { Color c = Color.FromArgb(nArg1); int rgb = c.R + c.G * 256 + c.B * 65536; WdSel.Cells.Shading.BackgroundPatternColor = (Microsoft.Office.Interop.Word.WdColor)rgb; } //****************************************************************************** else if (Lex.Eq(command, "HomeKey")) { //****************************************************************************** Object unit = nArg1; WdSel.HomeKey(ref unit, ref missingObj); #if false SETLONG(Arg,nArg1); AutoWrap(DISPATCH_METHOD, &result, WdSel, L"HomeKey", 1, Arg); VariantClear(&Arg); #endif UpdateSelection(); // update selection } //****************************************************************************** else if (Lex.Eq(command, "InlineShapes.AddPicture")) { // insert image from file //****************************************************************************** InlineShape ils = WdSel.InlineShapes.AddPicture(sArg, ref missingObj, ref missingObj, ref missingObj); ils.Width = nArg1; ils.Height = nArg2; #if false release_obj(WdTemp); // get current font object AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"InlineShapes", 0); WdTemp = result.pdispVal; SETSTR(Filename,sArg); // filename SETLONG(Width,nArg1); // in points SETLONG(Height,nArg2); AutoWrap(DISPATCH_METHOD, &result, WdTemp, L"AddPicture", 1, Filename); release_obj(WdTemp); WdTemp = result.pdispVal; // new shape object AutoWrap(DISPATCH_PROPERTYPUT, NULL, WdTemp, L"Width", 1, Width); AutoWrap(DISPATCH_PROPERTYPUT, NULL, WdTemp, L"Height", 1, Height); VariantClear(&Filename); VariantClear(&Width); VariantClear(&Height); #endif } //****************************************************************************** else if (Lex.Eq(command, "InsertBreak")) { //****************************************************************************** object type = nArg1; WdSel.InsertBreak(ref type); // SETLONG(Arg,nArg1); // AutoWrap(DISPATCH_METHOD, &result, WdSel, L"InsertBreak", 1, Arg); // VariantClear(&Arg); UpdateSelection(); // update selection } //****************************************************************************** else if (Lex.Eq(command, "InsertSymbol")) { //****************************************************************************** // InsertSymbol(CharacterNumber as Long, Font as String) int characterNumber = nArg1; object font = sArg; WdSel.InsertSymbol(characterNumber, ref font, ref missingObj, ref missingObj); #if false SETLONG(Arg,nArg1); // get char number SETSTR(Arg2,sArg); // get font AutoWrap(DISPATCH_METHOD, &result, WdSel, L"InsertSymbol", 2, Arg2, Arg); VariantClear(&Arg); VariantClear(&Arg2); #endif } //****************************************************************************** else if (Lex.Eq(command, "Cells.Merge")) { // merge cells together //****************************************************************************** WdSel.Cells.Merge(); #if false release_obj(WdTemp); // get current font object AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"Cells", 0); WdTemp = result.pdispVal; AutoWrap(DISPATCH_METHOD, &result, WdTemp, L"Merge", 0); #endif } //****************************************************************************** else if (Lex.Eq(command, "MoveLeft")) { // units, count //****************************************************************************** if (nArg2 <= 0) nArg2 = 1; object unit = nArg1; object count = nArg2; WdSel.MoveLeft(ref unit, ref count, ref missingObj); #if false SETLONG(Arg1,nArg1); SETLONG(Arg2,nArg2); AutoWrap(DISPATCH_METHOD, &result, WdSel, L"MoveLeft", 2, Arg2, Arg1); VariantClear(&Arg1); VariantClear(&Arg2); #endif UpdateSelection(); // update selection } //****************************************************************************** else if (Lex.Eq(command, "MoveRight")) { // units, count, extend //****************************************************************************** object extend; if (nArg2 <= 0) nArg2 = 1; object unit = nArg1; object count = nArg2; if (nArg3 <= 0) extend = missingObj; else extend = nArg3; WdSel.MoveRight(ref unit, ref count, ref extend); #if false SETLONG(Arg1,nArg1); SETLONG(Arg2,nArg2); SETLONG(Arg3,nArg3); AutoWrap(DISPATCH_METHOD, &result, WdSel, L"MoveRight", 3, Arg3, Arg2, Arg1); VariantClear(&Arg1); VariantClear(&Arg2); VariantClear(&Arg3); #endif UpdateSelection(); // update selection } //****************************************************************************** else if (Lex.Eq(command, "MoveDown")) { // units, count //****************************************************************************** if (nArg2 <= 0) nArg2 = 1; object unit = nArg1; object count = nArg2; WdSel.MoveDown(ref unit, ref count, ref missingObj); #if false SETLONG(Arg1,nArg1); SETLONG(Arg2,nArg2); AutoWrap(DISPATCH_METHOD, &result, WdSel, L"MoveDown", 2, Arg2, Arg1); VariantClear(&Arg1); VariantClear(&Arg2); #endif UpdateSelection(); // update selection } //****************************************************************************** else if (Lex.Eq(command, "MoveUp")) { // units, count //****************************************************************************** if (nArg2 <= 0) nArg2 = 1; object unit = nArg1; object count = nArg2; WdSel.MoveUp(ref unit, ref count, ref missingObj); #if false SETLONG(Arg1,nArg1); SETLONG(Arg2,nArg2); AutoWrap(DISPATCH_METHOD, &result, WdSel, L"MoveUp", 2, Arg2, Arg1); VariantClear(&Arg1); VariantClear(&Arg2); #endif UpdateSelection(); // update selection } //****************************************************************************** else if (Lex.Eq(command, "PageSetup.Orientation")) { //****************************************************************************** if (nArg1 == 0) WdSel.PageSetup.Orientation = WdOrientation.wdOrientPortrait; WdSel.PageSetup.Orientation = WdOrientation.wdOrientLandscape; #if false release_obj(WdTemp); AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"PageSetup", 0); WdTemp = result.pdispVal; SETLONG(Arg,nArg1); AutoWrap(DISPATCH_PROPERTYPUT, &result, WdTemp, L"Orientation", 1, Arg); VariantClear(&Arg); #endif } //****************************************************************************** else if (Lex.Eq(command, "PageSetup.Margins")) { //****************************************************************************** WdSel.PageSetup.TopMargin = nArg1; WdSel.PageSetup.BottomMargin = nArg2; WdSel.PageSetup.LeftMargin = nArg3; WdSel.PageSetup.RightMargin = nArg4; } //****************************************************************************** else if (Lex.Eq(command, "PageSetup.PageSize")) { //****************************************************************************** WdSel.PageSetup.PageWidth = nArg1; WdSel.PageSetup.PageHeight = nArg2; } //****************************************************************************** else if (Lex.Eq(command, "ParagraphFormat.Alignment")) { //****************************************************************************** WdSel.ParagraphFormat.Alignment = (WdParagraphAlignment)nArg1; } //****************************************************************************** else if (Lex.Eq(command, "Cells.VerticalAlignment")) //****************************************************************************** { WdSel.Cells.VerticalAlignment = (WdCellVerticalAlignment)nArg1; } //****************************************************************************** else if (Lex.Eq(command, "Paste")) //****************************************************************************** { WdSel.Paste(); } //****************************************************************************** else if (Lex.Eq(command, "PasteSpecial")) { //****************************************************************************** // PasteSpecial(IconIndex, Link, Placement, DisplayAsIcon, DataType) object iconIndex = 0; object link = false; object placement = InLine; object displayAsIcon = false; object dataType = nArg1; // set type of data to paste // ClientLog.Message("Before PasteSpecial"); // TST & PRD WdSel.PasteSpecial(ref iconIndex, ref link, ref placement, ref displayAsIcon, ref dataType, ref missingObj, ref missingObj); // ClientLog.Message("After PasteSpecial"); } //****************************************************************************** else if (Lex.Eq(command, "InsertStructure")) //****************************************************************************** // Selection.InlineShapes.AddOLEObject ClassType:="ISISServer", FileName:= _ // "C:\Isis\sketch1-small.skc", LinkToFile:=False, DisplayAsIcon:=False // This is significantly slower than a paste { object classType = "ISISServer"; object fileName = sArg; WdSel.InlineShapes.AddOLEObject( ref classType, ref fileName, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj); } //****************************************************************************** else if (Lex.Eq(command, "Rows.AllowBreakAcrossPages")) { // keep all contents of row on same page //****************************************************************************** WdSel.Rows.AllowBreakAcrossPages = nArg1; } //****************************************************************************** else if (Lex.Eq(command, "Rows.HeadingFormat")) { // mark rows as headings //****************************************************************************** WdSel.Rows.HeadingFormat = nArg1; } //****************************************************************************** else if (Lex.Eq(command, "SaveAs")) { // save file in .doc format //****************************************************************************** try { File.Delete(sArg); } // delete any existing file catch (Exception ex) { }; object fileName = sArg; object fileFormat = WdSaveFormat.wdFormatDocument; WdDoc.SaveAs( ref fileName, // FileName ref fileFormat, // FileFormat ref missingObj, // LockComments ref missingObj, // Password ref missingObj, // AddToRecentFiles ref missingObj, // WritePassword ref missingObj, // ReadOnlyRecommended ref missingObj, // EmbedTrueTypeFonts ref missingObj, // SaveNativePictureFormat ref missingObj, // SaveFormsData ref missingObj, // SaveAsAOCELetter ref missingObj, // Encoding ref missingObj, // InsertLineBreaks ref missingObj, // AllowSubstitutions ref missingObj, // LineEnding ref missingObj); // AddBiDiMarks } //****************************************************************************** else if (Lex.Eq(command, "ScreenUpdating")) { //****************************************************************************** WdApp.ScreenUpdating = bArg; } //****************************************************************************** else if (Lex.Eq(command, "SelectColumn")) { // select current column of table //****************************************************************************** WdSel.SelectColumn(); // AutoWrap(DISPATCH_METHOD, NULL, WdSel, L"SelectColumn", 0); UpdateSelection(); } //****************************************************************************** else if (Lex.Eq(command, "SelectRow")) { // select current row of table //****************************************************************************** WdSel.SelectRow(); UpdateSelection(); } //****************************************************************************** else if (Lex.Eq(command, "Tables.Add")) { // number of rows & cols supplied //****************************************************************************** WdTables = WdDoc.Tables; Microsoft.Office.Interop.Word.Range range = WdSel.Range; int numRows = nArg1; int numCols = nArg2; WdTable = WdTables.Add(range, numRows, numCols, ref missingObj, ref missingObj); WdTable.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle; WdTable.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle; UpdateSelection(); } //****************************************************************************** else if (Lex.Eq(command, "TableSelect")) { //****************************************************************************** WdTable.Select(); UpdateSelection(); // update selection } //****************************************************************************** else if (Lex.Eq(command, "TypeParagraph")) { //****************************************************************************** WdSel.TypeParagraph(); UpdateSelection(); } //****************************************************************************** else if (Lex.Eq(command, "TypeText")) { //****************************************************************************** WdSel.TypeText(sArg); // SETSTR(Arg,sArg); // AutoWrap(DISPATCH_METHOD, &result, WdSel, L"TypeText", 1, Arg); // VariantClear(&Arg); UpdateSelection(); } //****************************************************************************** else if (Lex.Eq(command, "Visible")) { //****************************************************************************** WdApp.Visible = bArg; #if false SETBOOL(True,1); SETBOOL(False,0); if (strcmpi((CCP)sArg,"true)) AutoWrap(DISPATCH_PROPERTYPUT, NULL, WdApp, L"Visible", 1, True); else AutoWrap(DISPATCH_PROPERTYPUT, NULL, WdApp, L"Visible", 1, False); #endif } //****************************************************************************** else throw new Exception("WordOp - Invalid operation " + command); //****************************************************************************** return ""; // everything must be ok } // end of try
public LL1StackElement(bool flag, Lex.TokenType tokenType, int productionNum) : this(productionNum) { this.Flag = flag; this.TokenType = tokenType; }