public void Publish_WithEntry_SetsDateCreatedToBlogCurrentTimeZoneTime() { //arrange DateTime currentTime = DateTime.Now; var repository = new Mock <ObjectProvider>(); repository.Setup(r => r.Create(It.IsAny <Entry>(), null)); var context = new Mock <ISubtextContext>(); context.Setup(c => c.Blog.TimeZone.Now).Returns(currentTime); context.Setup(c => c.Repository).Returns(repository.Object); var searchengine = new Mock <IIndexingService>(); var publisher = new EntryPublisher(context.Object, null, null, searchengine.Object); var entry = new Entry(PostType.BlogPost) { Title = "this is a test" }; entry.Blog = new Blog() { Title = "MyTestBlog" }; //act publisher.Publish(entry); //assert Assert.AreEqual(currentTime, entry.DateCreated); //cheating by shoving this extra assert here. MUAHAHAHA!!! ;) Assert.IsTrue(NullValue.IsNull(entry.DateSyndicated)); }
/// <summary> /// Return the next matching row value object /// </summary> /// <returns></returns> public override Object[] NextRow() { Object[] row; object v; QueryTable qt0; if (Lex.IsDefined(Sql)) { while (true) { row = base.NextRow(); if (row == null) { return(null); } if (CfValColSelectListPos < 0) { continue; // just return if calc field value not selected } v = row[CfValColSelectListPos]; // calculated value if (NullValue.IsNull(v)) { continue; // ignore row if value is null } return(row); } } else { return(null); // filled in later from other buffer values } }
public virtual VirtualPath EntryUrl(IEntryIdentity entry, Blog entryBlog) { if (entry == null) { throw new ArgumentNullException("entry"); } if (entry.PostType == PostType.None) { throw new ArgumentException(Resources.Argument_EntryMustHaveValidPostType, "entry"); } if (NullValue.IsNull(entry.Id)) { return(null); } string routeName; var routeValues = new RouteValueDictionary(); if (entry.PostType == PostType.BlogPost) { #if DEBUG var blogEntry = entry as Entry; if (blogEntry != null && blogEntry.IsActive && blogEntry.DateSyndicated.Year == 1) { throw new InvalidOperationException("DateSyndicated was not properly set."); } #endif routeValues.Add("year", entry.DateSyndicated.ToString("yyyy", CultureInfo.InvariantCulture)); routeValues.Add("month", entry.DateSyndicated.ToString("MM", CultureInfo.InvariantCulture)); routeValues.Add("day", entry.DateSyndicated.ToString("dd", CultureInfo.InvariantCulture)); routeName = "entry-"; } else { routeName = "article-"; } if (string.IsNullOrEmpty(entry.EntryName)) { routeValues.Add("id", entry.Id); routeName += "by-id"; } else { routeValues.Add("slug", entry.EntryName); routeName += "by-slug"; } if (entryBlog != null) { routeValues.Add("subfolder", entryBlog.Subfolder); } VirtualPathData virtualPath = Routes.GetVirtualPath(RequestContext, routeName, routeValues); if (virtualPath != null) { return(virtualPath.VirtualPath); } return(null); }
public void SettingDateSyndicatedToNullRemovesItemFromSyndication() { //arrange Config.CreateBlog("", "username", "password", _hostName, string.Empty); BlogRequest.Current.Blog = Config.GetBlog(_hostName, string.Empty); Entry entry = UnitTestHelper.CreateEntryInstanceForSyndication("Haacked", "Title Test", "Body Rocking"); UnitTestHelper.Create(entry); Assert.IsTrue(entry.IncludeInMainSyndication, "Failed to setup this test properly. This entry should be included in the main syndication."); Assert.IsFalse(NullValue.IsNull(entry.DateSyndicated), "Failed to setup this test properly. DateSyndicated should be null."); //act entry.DateSyndicated = NullValue.NullDateTime; //assert Assert.IsFalse(entry.IncludeInMainSyndication, "Setting the DateSyndicated to a null date should have reset 'IncludeInMainSyndication'."); //save it var subtextContext = new Mock <ISubtextContext>(); subtextContext.Setup(c => c.Blog).Returns(Config.CurrentBlog); subtextContext.Setup(c => c.Repository).Returns(ObjectProvider.Instance()); UnitTestHelper.Update(entry, subtextContext.Object); Entry savedEntry = UnitTestHelper.GetEntry(entry.Id, PostConfig.None, false); //assert again Assert.IsFalse(savedEntry.IncludeInMainSyndication, "This item should still not be included in main syndication."); }
public static DateTime?NullIfEmpty(this DateTime dateTime) { if (NullValue.IsNull(dateTime)) { return(null); } return(dateTime); }
/// <summary> /// Checks the value type and returns null if the /// value is "null-equivalent". /// </summary> public static int?NullIfMinValue(this int value) { if (NullValue.IsNull(value)) { return(null); } return(value); }
/// <summary> /// Accumulate data for a compound /// </summary> /// <param name="mElem"></param> /// <param name="dt"></param> /// <param name="dr"></param> /// <param name="rgroupKey"></param> static void AccumulateMatrixElements( Dictionary <string, List <QualifiedNumber> > mElem, Query q, DataRowMx dr, string rgroupKey, string rgroupKeyLast, string cid) { QualifiedNumber qn = null; foreach (QueryTable qt in q.Tables) { MetaTable mt = qt.MetaTable; if (Lex.Eq(mt.Name, "Rgroup_Decomposition")) { continue; // ignore the rgroup info here } foreach (QueryColumn qc in qt.QueryColumns) { if (!qc.Selected) { continue; } MetaColumn mc = qc.MetaColumn; if (mc.DataType == MetaColumnType.CompoundId) { continue; // no data for compound ids } object o = dr[qc.VoPosition]; if (NullValue.IsNull(o)) { continue; // skip null; } string key = rgroupKey + "\t" + mt.Name + "." + mc.Name + "\t" + rgroupKeyLast; if (!mElem.ContainsKey(key)) { mElem[key] = new List <QualifiedNumber>(); } if (!QualifiedNumber.TryConvertTo(o, out qn)) { continue; } if (qn.NumberValue == QualifiedNumber.NullNumber) { continue; } qn.Hyperlink = qn.DbLink = mt.Name + "," + mc.Name + "," + cid; // store metatable/col name & compound id used for drilldown mElem[key].Add(qn); // add object } } }
private void RepositoryItemCheckEdit_EditValueChanging(object sender, ChangingEventArgs e) { if (NullValue.IsNull(e.OldValue)) { e.Cancel = true; // don't allow change of indeterminates } else if (e.OldValue is bool && (bool)e.OldValue == true && NullValue.IsNull(e.NewValue)) { e.NewValue = false; // go from checked to not checked and skip indeterminate } }
private void UnsummarizedAll_Click(object sender, EventArgs e) { for (int i1 = 0; i1 < DataTable.Rows.Count; i1++) { object cs = DataTable.Rows[i1]["SummarizedCol"]; if (NullValue.IsNull(cs)) { continue; } DataTable.Rows[i1]["SummarizedCol"] = false; } }
private static bool CachedVersionIsOkay(HttpRequestBase request) { //Get header value DateTime dt = HttpHelper.GetIfModifiedSinceDateUtc(request); if (NullValue.IsNull(dt)) { return(false); } //convert to datetime and add 6 hours. //We don't want to count quick reclicks. return(dt.AddHours(6) >= DateTime.UtcNow); }
private void Unsummarized_Click(object sender, EventArgs e) { if (GridView.RowCount == 0) { return; } int sri = GetSelectedRow(); object cs = DataTable.Rows[sri]["SummarizedCol"]; if (NullValue.IsNull(cs)) { return; } DataTable.Rows[sri]["SummarizedCol"] = false; }
/// <summary> /// Saves changes to the specified entry attaching the specified categories. /// </summary> /// <param name="entry">Entry.</param> /// <param name="categoryIds">Category Ids.</param> /// <returns></returns> public override bool Update(Entry entry, IEnumerable <int> categoryIds) { ValidateEntry(entry); if (entry.IsActive && NullValue.IsNull(entry.DateSyndicated)) { entry.DateSyndicated = CurrentDateTime; } bool updated = _procedures.UpdateEntry( entry.Id , entry.Title ?? string.Empty , entry.Body.NullIfEmpty() , (int)entry.PostType , entry.Author.NullIfEmpty() , entry.Email.NullIfEmpty() , entry.Description.NullIfEmpty() , entry.DateModified , (int)entry.PostConfig , entry.EntryName.NullIfEmpty() , entry.DateSyndicated.NullIfEmpty() , BlogId , CurrentDateTime); if (!updated) { return(false); } if (!categoryIds.IsNullOrEmpty()) { SetEntryCategoryList(entry.Id, categoryIds); } if (Config.Settings.Tracking.UseTrackingServices) { if (entry.Id > -1) { Config.CurrentBlog.LastUpdated = entry.DateModified; } } return(true); }
/// <summary> /// Store selected formatting information for possible use later needed later /// </summary> /// <param name="ffi"></param> /// <param name="fieldValue"></param> /// <param name="dr"></param> /// <param name="ci"></param> /// <param name="mdt"></param> void StoreFormattingInformationInMdt(FormattedFieldInfo ffi, object fieldValue, DataRowMx dr, CellInfo ci, MobiusDataType mdt) { bool hyperLinked = !String.IsNullOrEmpty(ffi.Hyperlink); if (ffi.ForeColor != Color.Black || ffi.BackColor != Color.Empty || hyperLinked) { // store any formatting info in a MDT so that it's available for the later display RowCellStyle event if (mdt == null && !NullValue.IsNull(fieldValue)) // need to create MDT? { //if (ci.Mc.DataType == MetaColumnType.Structure) ci = ci; // debug mdt = MobiusDataType.New(ci.Mc.DataType, fieldValue); dr.ItemArrayRef[ci.DataColIndex] = mdt; // store new value without firing event } if (mdt.BackColor != ffi.BackColor) { mdt.BackColor = ffi.BackColor; // set in DataTable only if changed to avoid repaints } if (mdt.ForeColor != ffi.ForeColor) { mdt.ForeColor = ffi.ForeColor; } if (mdt.Hyperlink != ffi.Hyperlink) { mdt.Hyperlink = ffi.Hyperlink; } if (mdt.Hyperlinked != hyperLinked) { mdt.Hyperlinked = hyperLinked; } if (ffi.FormattedBitmap != null) { mdt.FormattedBitmap = ffi.FormattedBitmap; } if (ffi.FormattedText != null) { mdt.FormattedText = ffi.FormattedText; } } }
/// <summary> /// GetVoValQualifiedNumber /// </summary> /// <param name="qc"></param> /// <param name="vo"></param> /// <returns></returns> QualifiedNumber GetVoValQualifiedNumber( int voPos) { QualifiedNumber qn = null; object value = GetVoVal(voPos); if (NullValue.IsNull(value)) { return(null); } if (value is QualifiedNumber) { qn = (QualifiedNumber)value; } else { QualifiedNumber.TryConvertTo(value, out qn); } return(qn); }
public void IsNullReturnsTrueForNullDateTime() { Assert.IsTrue(NullValue.IsNull(DateTime.MinValue)); }
public void IsNullReturnsTrueForNullInt() { Assert.IsTrue(NullValue.IsNull(int.MinValue)); }
public void IsNullReturnsTrueForNullGuid() { Assert.IsTrue(NullValue.IsNull(Guid.Empty)); }
public void IsNullReturnsTrueForNullDouble() { Assert.IsTrue(NullValue.IsNull(double.NaN)); }
/// <summary> /// Search button clicked, process input /// </summary> /// <returns></returns> DialogResult ProcessInput() { CidList cidList = null; StreamReader structureFileReader = null; string qid; // query identifier, compoundId, file name or sdFile key value QueryManager qm; DataTableMx dt; DataColumn dc; DataRowMx dr; //object[] dr; // if using Qe DialogResult dlgRslt = DialogResult.OK; Query q = null; QueryTable qt = null; QueryColumn simScoreQc, structQc; // query column containing latest query settings MetaTable mt = null; MetaColumn keyMc = null, structMc = null, dbSetMc = null, simScoreMc = null, mc; MetaColumnType storageType; string txt, tok; if (DatabasesToSearch.Text == "") { MessageBoxMx.ShowError("Databases to search must be defined."); DatabasesToSearch.Focus(); return(DialogResult.Cancel); } // Get list of databases string[] dba = DatabasesToSearch.Text.Split(','); List <MetaTable> tables = new List <MetaTable>(); foreach (string dbLabel0 in dba) { string dbLabel = dbLabel0.Trim(); RootTable dbInfo = RootTable.GetFromTableLabel(dbLabel); if (dbInfo == null) { MessageBoxMx.ShowError("Can't find database " + DatabasesToSearch.Text); DatabasesToSearch.Focus(); return(DialogResult.Cancel); } mt = MetaTableCollection.Get(dbInfo.MetaTableName); if (mt == null) { MessageBoxMx.ShowError("Unable to locate parent structure table for database: " + DatabasesToSearch.Text); DatabasesToSearch.Focus(); return(DialogResult.Cancel); } if (dbSetMc == null) { dbSetMc = mt.DatabaseListMetaColumn; } tables.Add(mt); } if (dbSetMc == null) { throw new Exception("\"Databases\" metacolumn not found for any of the databases to search"); } // Validate other form values RetrieveStructures = RetrieveMatchingStructures.Checked; bool fromList = FromList.Checked; int listCidsRead = 0; int inputQueryCount = -1; if (fromList) // using list, validate list name { if (SavedListUo == null) { MessageBoxMx.ShowError("Compound list must be defined."); ListName.Focus(); return(DialogResult.Cancel); } cidList = CidListCommand.Read(SavedListUo); if (cidList == null) { MessageBoxMx.ShowError("Error reading list."); ListName.Focus(); return(DialogResult.Cancel); } inputQueryCount = cidList.Count; } else // Using SdFile, validate SdFile name { StructureFile = FileName.Text; if (StructureFile == "") { MessageBoxMx.ShowError("File must be defined."); FileName.Focus(); return(DialogResult.Cancel); } try { structureFileReader = new StreamReader(StructureFile); structureFileReader.Close(); } catch (Exception ex) { MessageBoxMx.ShowError("Can't read file: " + Lex.Dq(StructureFile)); FileName.Focus(); return(DialogResult.Cancel); } keyField = KeyField.Text; // get key, blank to use name in 1st line inputQueryCount = -1; // don't know how many queries unless we read the file (todo?) } tok = ResultsName.Text.Trim(); // name to store results under if (tok == "") { MessageBoxMx.ShowError("A name for the results must be provided."); ResultsName.Focus(); return(DialogResult.Cancel); } if (SubStruct.Checked) { Psc.SearchType = StructureSearchType.Substructure; } else if (Full.Checked) { Psc.SearchType = StructureSearchType.FullStructure; } else if (Similarity.Checked) { Psc.SearchType = StructureSearchType.MolSim; } else { throw new Exception("Unrecognized search type"); } // Write initial log entries SearchCount++; string logFileName = ClientDirs.DefaultMobiusUserDocumentsFolder + @"\Multistructure Search " + SearchCount + ".txt"; if (!UIMisc.CanWriteFileToDefaultDir(logFileName)) { return(DialogResult.Cancel); } LogStream = new StreamWriter(logFileName); if (ResultsUo == null) { ResultsUo = new UserObject(UserObjectType.Annotation); } ResultsUo.Name = tok; UserObjectTree.GetValidUserObjectTypeFolder(ResultsUo); DateTime startTime = DateTime.Now; WriteToLog("Multiple " + Psc.SearchType + " Search"); WriteToLog("Databases: " + DatabasesToSearch.Text); WriteToLog("Date: " + startTime); if (fromList) { WriteToLog("Input List: " + SavedListUo.Name); } else { WriteToLog("Input Structure File: " + StructureFile); } WriteToLog("Output List: " + ResultsUo.Name); WriteToLog("Log File: " + logFileName); WriteToLog(""); WriteToLog("Query, Match, Score"); int queryCount = 0; int matchAtLeastOneCount = 0; MoleculeMx queryStructure = null; // current structure being searched CidList matchList = new CidList(); List <MatchData> matchData = new List <MatchData>(); if (FromFile.Checked) // open SdFile as required { structureFileReader = new StreamReader(StructureFile); } // Search of structures one at a time while (true) { if (fromList) // get next structure from list { if (listCidsRead >= cidList.Count) { break; } qid = cidList[listCidsRead].Cid; listCidsRead++; if (qid.Trim() == "") { continue; } if (qid.ToLower().IndexOf(".mol") > 0 || qid.ToLower().IndexOf(".skc") > 0) { // file reference if (!File.Exists(qid)) { continue; } if (qid.ToLower().IndexOf(".mol") > 0) { queryStructure = MoleculeMx.ReadMolfile(qid); } else { queryStructure = MoleculeMx.ReadSketchFile(qid); } } else { queryStructure = MoleculeUtil.SelectMoleculeForCid(qid); } if (queryStructure == null || queryStructure.AtomCount == 0) { continue; // oops } } else // get next structure from input file { qid = null; if (StructureFile.ToLower().EndsWith(".sdf")) { List <SdFileField> fList = SdFileDao.Read(structureFileReader); if (fList == null) // end of sdFile { structureFileReader.Close(); break; } if (fList.Count == 0) { continue; } queryStructure = new MoleculeMx(MoleculeFormat.Molfile, fList[0].Data); if (queryStructure == null || queryStructure.AtomCount == 0) { continue; } if (keyField != "") // key field specified? { qid = SdFileDao.GetDataField(fList, keyField); } else // get name from 1st line of molfile { string molFile = fList[0].Data; int i1 = molFile.IndexOf("\n"); if (i1 == 0) { qid = ""; } else { qid = molFile.Substring(0, i1).Trim(); } } if (string.IsNullOrEmpty(qid)) { qid = SdFileDao.GetDataField(fList, "compound_id"); } } else // assume smiles file { string smiles = structureFileReader.ReadLine(); if (smiles == null) // end of sdFile { structureFileReader.Close(); break; } smiles = smiles.Trim(); if (smiles.Length == 0) { continue; } int i1 = smiles.IndexOf(","); // get any preceeding queryId if (i1 < 0) { i1 = smiles.IndexOf("\t"); } if (i1 >= 0) { qid = smiles.Substring(0, i1).Trim(); smiles = smiles.Substring(i1 + 1).Trim(); } queryStructure = new MoleculeMx(MoleculeFormat.Smiles, smiles); if (queryStructure == null || queryStructure.AtomCount == 0) { continue; } } if (qid == null || qid.Trim() == "") { qid = (queryCount + 1).ToString(); // be sure we have a query id } } queryCount++; // count the query if (queryStructure == null || queryStructure.AtomCount == 0) { WriteToLog("Error converting specific structure " + queryCount.ToString() + ", " + qid); continue; } queryStructure.RemoveStructureCaption(); // remove any Mobius-added caption Psc.Molecule = queryStructure; string msg = "Searching Structure: " + queryCount.ToString(); if (inputQueryCount > 0) { msg += " of " + inputQueryCount.ToString(); } msg += "\n" + "Structures with one or more matches: " + matchAtLeastOneCount.ToString() + "\n" + "Total Matches: " + matchList.Count.ToString(); Progress.Show(msg); // Do the search over the list of databases for (int ti = 0; ti < tables.Count; ti++) { mt = tables[ti]; q = new Query(); // build basic query //q.SingleStepExecution = true; // do in single step (doesn't currently return sim score) q.ShowStereoComments = false; qt = new QueryTable(mt); q.AddQueryTable(qt); qt.SelectKeyOnly(); // start selecting desired cols keyMc = mt.KeyMetaColumn; structMc = mt.FirstStructureMetaColumn; structQc = qt.GetQueryColumnByName(structMc.Name); structQc.Selected = RetrieveStructures; dbSetMc = mt.DatabaseListMetaColumn; if (dbSetMc == null) { throw new Exception("\"Databases\" metacolumn not found for table: " + mt.Label); } QueryColumn dbSetQc = qt.GetQueryColumnByName(dbSetMc.Name); dbSetQc.Selected = true; // select the database name RootTable root = RootTable.GetFromTableName(mt.Name); txt = " in (" + root.Label + ")"; dbSetQc.Criteria = dbSetMc.Name + txt; dbSetQc.CriteriaDisplay = txt; simScoreMc = mt.SimilarityScoreMetaColumn; simScoreQc = null; if (simScoreMc != null) // get sim score if it exists { simScoreQc = qt.GetQueryColumnByName(simScoreMc.Name); simScoreQc.Selected = true; // return sim score } Psc.QueryColumn = structQc; ParsedStructureCriteria psc2 = AdjustSearchForSmallWorldAsNeeded(Psc); psc2.ConvertToQueryColumnCriteria(structQc); // format the QC for the structure search DateTime t0 = DateTime.Now; //QueryEngine qe = new QueryEngine(); //qe.NextRowsMin = 1000; // minimum number of rows to prefetch //qe.NextRowsMax = -1; // maximum number of rows to prefetch //qe.NextRowsMaxTime = 10000; // max time in milliseconds for next fetch //qe.ExecuteQuery(q); qm = new QueryManager(); try { dlgRslt = qm.ExecuteQuery(ref q); } catch (Exception ex) { WriteToLog("Error searching structure: " + ex.Message + ", " + queryCount.ToString() + ", " + qid); continue; } if (dlgRslt != DialogResult.OK) { return(dlgRslt); } double executeTime = TimeOfDay.Delta(ref t0); int offset = qm.DataTableManager.KeyValueVoPos + 1; //int offset = 0; // for QE int keyPos = offset++; int strPos = RetrieveStructures ? offset++ : -1; int dbPos = offset++; int simPos = offset++; int fetchCnt = 0; while (true) { dr = qm.NextRow(); //dr = qe.NextRow(); // for Qe if (dr == null) { break; } fetchCnt++; if (fetchCnt == 1) { matchAtLeastOneCount++; // number of queries that have at least one match } MatchData md = new MatchData(); md.Qno = queryCount; md.Qid = qid; if (RetrieveStructures) { md.Qstr = "Chime=" + queryStructure.GetChimeString(); } CompoundId cid = CompoundId.ConvertTo(dr[keyPos]); md.Mid = cid.Value; if (RetrieveStructures) { MoleculeMx ms = MoleculeMx.ConvertTo(dr[strPos]); if (!NullValue.IsNull(ms)) { md.Mstr = "Chime=" + ms.GetChimeString(); } } StringMx db = StringMx.ConvertTo(dr[dbPos]); if (!NullValue.IsNull(db)) { md.Db = db.Value; } if (Psc.SearchType == StructureSearchType.MolSim) { NumberMx nex = NumberMx.ConvertTo(dr[simPos]); if (!NullValue.IsNull(nex)) { md.Score = nex.Value; } } if (matchList.Contains(cid.Value)) // already have compound id as match for other query? { if (Psc.SearchType != StructureSearchType.MolSim) { continue; // if similarity search see if more similar } CidListElement le = matchList.Get(cid.Value); // reference current score if (le.Tag > md.Score) { continue; // only replace if more similar } matchList.Remove(le.Cid); // remove from list for (int mi = 0; mi < matchData.Count; mi++) // remove from data { if (matchData[mi].Mid == md.Mid) { matchData.RemoveAt(mi); break; } } } matchList.Add(md.Mid); matchList.Get(md.Mid).Tag = md.Score; // keep score in list matchData.Add(md); // add to results txt = md.Qid + ", " + md.Mid + ", " + md.Score.ToString(); WriteToLog(txt); } // Fetch result loop double fetchTime = TimeOfDay.Delta(ref t0); } // DB loop if (Progress.CancelRequested) { Progress.Hide(); MessageBoxMx.ShowError("Search cancelled."); try { LogStream.Close(); } catch { } return(DialogResult.Cancel); } } // key loop CidListCommand.WriteCurrentList(matchList); // write the list of numbers UsageDao.LogEvent("MultipleStructSearch"); txt = "=== Multiple structure search complete ===\r\n\r\n" + "Structures Searched: " + queryCount.ToString() + "\r\n"; txt += "Structures with one or more matches: " + matchAtLeastOneCount.ToString() + "\r\n" + "Total Matches: " + matchList.Count.ToString() + "\r\n"; TimeSpan ts = DateTime.Now.Subtract(startTime); ts = new TimeSpan(ts.Hours, ts.Minutes, ts.Seconds); txt += "Total Time: " + ts + "\r\n\r\n"; WriteToLog("\r\n" + txt); try { LogStream.Close(); } catch { } if (matchList.Count == 0) { Progress.Hide(); MessageBoxMx.ShowError("No matches have been found."); return(DialogResult.Cancel); } tok = "Matching compound ids"; if (Psc.SearchType == StructureSearchType.MolSim) { tok = "Similar compound ids"; } txt += tok + " have been written to the current list: " + ResultsUo.Name + "\n" + "Log file written to: " + logFileName + "\n\n" + "Do you want to view the match results?"; DialogResult dRslt = MessageBoxMx.Show(txt, "Multiple Structure Search", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (dRslt == DialogResult.Cancel) { return(DialogResult.Cancel); } else if (dRslt == DialogResult.No) // show log { SystemUtil.StartProcess(logFileName); return(DialogResult.Cancel); } // Display results Progress.Show("Formatting results..."); mt = new MetaTable(); mt.Name = "MULTSTRUCTSEARCH_" + SearchCount; mt.Label = "Multiple Structure Search " + SearchCount; mt.TableMap = "Mobius.Tools.MultStructSearch"; // plugin id mt.MetaBrokerType = MetaBrokerType.NoSql; ColumnSelectionEnum structureColumnSelection = RetrieveStructures ? ColumnSelectionEnum.Selected : ColumnSelectionEnum.Unselected; keyMc = keyMc.Clone(); keyMc.Name = "MatchingCid"; keyMc.Label = "Matching Compound Id"; mt.AddMetaColumn(keyMc); structMc = structMc.Clone(); structMc.Name = "MatchingStructure"; structMc.Label = "Matching Structure"; structMc.InitialSelection = structureColumnSelection; mt.AddMetaColumn(structMc); dbSetMc = dbSetMc.Clone(); dbSetMc.Name = "Database"; mt.AddMetaColumn(dbSetMc); //if (DatabasesToSearch.Text.Contains(",")) dbSetMc.InitialSelection = ColumnSelectionEnum.Selected; mc = mt.AddMetaColumn("Molsimilarity", "Similarity Search Score", MetaColumnType.Number, ColumnSelectionEnum.Unselected, 10); if (Psc.SearchType == StructureSearchType.MolSim) { mc.InitialSelection = ColumnSelectionEnum.Selected; } mc = mt.AddMetaColumn("QueryNo", "Query Number", MetaColumnType.Integer); //mc = mt.AddMetaColumn("QueryMatchNo", "Query Match Number", MetaColumnType.Integer); mc = mt.AddMetaColumn("QueryId", "Query Id", MetaColumnType.String); mc = mt.AddMetaColumn("QueryStructure", "Query Structure", MetaColumnType.Structure); mc.InitialSelection = structureColumnSelection; q = ToolHelper.InitEmbeddedDataToolQuery(mt); dt = q.ResultsDataTable as DataTableMx; for (int mi = 0; mi < matchData.Count; mi++) { MatchData md = matchData[mi]; dr = dt.NewRow(); dr[qt.Alias + ".MatchingCid"] = new CompoundId(md.Mid); if (RetrieveStructures) { dr[qt.Alias + ".MatchingStructure"] = new MoleculeMx(MoleculeFormat.Chime, md.Mstr); } dr[qt.Alias + ".Database"] = new StringMx(md.Db); if (Psc.SearchType == StructureSearchType.MolSim) { dr[qt.Alias + ".Molsimilarity"] = new NumberMx(md.Score); } dr[qt.Alias + ".QueryNo"] = new NumberMx(md.Qno); dr[qt.Alias + ".QueryId"] = new StringMx(md.Qid); if (RetrieveStructures) { dr[qt.Alias + ".QueryStructure"] = new MoleculeMx(MoleculeFormat.Chime, md.Qstr); } dt.Rows.Add(dr); } ToolHelper.DisplayData(q, dt, true); Progress.Hide(); return(DialogResult.OK); }
/// <summary> /// Read input data from database /// </summary> /// <param name="smp"> /// <returns></returns> List<CompoundStructureActivityData> ReadData( SasMapParms smp) { MetaColumn activityMc = smp.EndpointMc; QueryColumn keyCriteriaQc = smp.KeyCriteriaQc; AssertMx.IsNotNull(activityMc, "mc"); AssertMx.IsNotNull(keyCriteriaQc, "keyCriteriaQc"); MetaTable mt, mt2; MetaColumn mc2 = null; Query q = new Query(); mt = activityMc.MetaTable; QueryTable qt = new QueryTable(mt); if (mt.SummarizedExists && !mt.UseSummarizedData) { // retrieve summarized data if exists mt2 = MetaTableCollection.Get(mt.Name + MetaTable.SummarySuffix); if (mt2 != null) { mc2 = mt2.GetMetaColumnByName(activityMc.Name); if (mc2 == null) mc2 = mt2.GetMetaColumnByLabel(activityMc.Label); } if (mc2 != null) // same column available in summarized? { mt = mt2; activityMc = mc2; } } SMP.KeyCriteriaQc.CopyCriteriaToQueryKeyCritera(q); q.KeyCriteriaDisplay = SMP.KeyCriteriaQc.CriteriaDisplay; qt.SelectKeyOnly(); QueryColumn qc = qt.GetQueryColumnByName(activityMc.Name); qc.Selected = true; q.AddQueryTable(qt); QueryEngine qe = new QueryEngine(); List<string> keyList = qe.ExecuteQuery(q); // note that keylist may be empty if single-step query HashSet<string> keySet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); List<CompoundStructureActivityData> data = new List<CompoundStructureActivityData>(); int rowCount = 0; while (true) { object[] vo = qe.NextRow(); if (vo == null) break; CompoundStructureActivityData cd = new CompoundStructureActivityData(); string cid = (string)vo[0]; cd.Cid = cid; keySet.Add(cid); // accumulate keys object val = vo[2]; if (NullValue.IsNull(val)) continue; if (val is double) cd.Activity = (double)val; else if (val is Int32) cd.Activity = (Int32)val; else if (val is NumberMx) { NumberMx nex = val as NumberMx; cd.Activity = nex.Value; } else if (val is QualifiedNumber) { QualifiedNumber qn = val as QualifiedNumber; cd.Activity = qn.NumberValue; //if (qn.Qualifier != null && qn.Qualifier != "" && qn.Qualifier != "=") // continue; // (don't want to do this since may filter out good data (e.g. IC50 <0.0001)) } else continue; if (cd.Activity == NullValue.NullNumber) continue; data.Add(cd); rowCount++; } // Retrieve structures keyList = new List<string>(keySet); Dictionary<string, MoleculeMx> csDict = MoleculeUtil.SelectMoleculesForCidList(keyList, qt.MetaTable); // get the structures in a single step // Add structures and build/store fingerprints to data DebugLog.Message("========== Fingerprints ============"); foreach (CompoundStructureActivityData cd in data) { if (!csDict.ContainsKey(cd.Cid) || csDict[cd.Cid] == null) continue; if (cd.Cid == "111" || cd.Cid == "222") csDict = csDict; // debug MoleculeMx cs = csDict[cd.Cid]; cd.Structure = cs; FingerprintType fpType = FingerprintType.Circular; int fpSubtype = -1; if (SMP.SimilarityType == SimilaritySearchType.ECFP4) // some issue with ECFP4? { fpType = FingerprintType.Circular; fpSubtype = CircularFingerprintType.ECFP4; } else if (SMP.SimilarityType == SimilaritySearchType.Normal) { fpType = FingerprintType.MACCS; } cd.BitsetFingerprint = cs.BuildBitSetFingerprint(fpType, fpSubtype); if (cd.BitsetFingerprint == null) continue; // couldn't build fingerprint (e.g. no structure) if (Debug) DebugLog.Message(cd.Cid + ": " + Lex.Join(CdkMolUtil.GetBitSet(cd.BitsetFingerprint), ", ")); } return data; }
private void FindNext_Click(object sender, EventArgs e) { string findText, cellText; bool matches; string s = FindText.Text.Trim(); if (s == "") { return; } if (InFindNext_Click) { return; // avoid recursion } InFindNext_Click = true; if (MatchCase.Checked) { findText = s; } else { findText = s.ToLower(); } int startRow = Grid.Row; // where we are now if (startRow < 0) { startRow = 0; } int startCol = Grid.Col; if (startCol < 0) { startCol = 0; } int row = startRow; // where we will start to search int col = startCol; Progress.Text = "Searching row " + row.ToString() + "..."; Progress.Visible = true; FindNext.Enabled = false; CloseButton.Text = "Cancel"; int t0 = TimeOfDay.Milliseconds(); bool [] checkColumn = new bool[Grid.V.Columns.Count]; // get list of columns to check for (int ci = 0; ci < Grid.V.Columns.Count; ci++) { GridColumn gc = Grid.V.Columns[ci]; ColumnInfo cInf = Grid.GetColumnInfo(gc); if (cInf == null || cInf.Mc == null || cInf.Mc.IsGraphical) { checkColumn[ci] = false; } else { checkColumn[ci] = true; } } int iteration = -1; // Loop through grid checking cells while (true) { iteration++; if (iteration > 0 && row == startRow && col == startCol) { // if back at start then not found MessageBoxMx.Show(UmlautMobius.String + " cannot find the data you're searching for.", UmlautMobius.String, MessageBoxButtons.OK, MessageBoxIcon.Information); break; } if (!Visible) { break; // cancelled by user } col++; // go to next column if (col >= Grid.V.Columns.Count) { col = 1; // start at 1st col past check mark col row++; if (TimeOfDay.Milliseconds() - t0 > 500) // update display periodically { Progress.Text = "Searching row " + row.ToString() + "..."; this.Refresh(); Application.DoEvents(); t0 = TimeOfDay.Milliseconds(); } } if (row >= Grid.V.RowCount) // past end of grid? { if (Dtm.RowRetrievalComplete) // end of grid & have all data { row = col = 0; // cycle back to top } else // need to read more data { int chunkSize = 100; Dtm.StartRowRetrieval(chunkSize); Progress.Text = "Retrieving data..."; while (true) // loop until requested rows have been read, no more rows or cancel requested { Thread.Sleep(250); Application.DoEvents(); if (row < Grid.V.RowCount) // have data for next row? { break; } else if (Dtm.RowRetrievalState != RowRetrievalState.Running) // must be at end of query { row = 0; break; } else if (!Visible) // cancelled by user { Progress.Text = ""; FindNext.Enabled = true; CloseButton.Text = "Close"; InFindNext_Click = false; return; } } Progress.Text = "Searching row " + row.ToString() + "..."; // restore search message } } if (!checkColumn[col]) { continue; } object vo = Grid[row, col]; if (NullValue.IsNull(vo)) { continue; } else if (vo is MobiusDataType && (vo as MobiusDataType).FormattedText != null) { cellText = (vo as MobiusDataType).FormattedText; // use existing formatted value } else // need to format value { CellInfo cInf = Grid.GetCellInfo(row, col); cellText = Grid.Helpers.FormatFieldText(cInf); } if (String.IsNullOrEmpty(cellText)) { continue; } if (!MatchCase.Checked) { cellText = cellText.ToLower(); } if (MatchEntireCell.Checked) { matches = (cellText == findText); } else { matches = (cellText.IndexOf(findText) >= 0); } if (matches) { //Grid.Focus(); Grid.SelectCell(row, col); Grid.FocusCell(row, col); // put focus on cell found, may cause scroll event Grid.NotFocusedRowToHighlight = row; Grid.NotFocusedColToHighlight = col; // Reposition search box out of the way if necessary (above current cell) Rectangle findRect = // rectangle for find dialog new Rectangle(Instance.Left, Instance.Top, Instance.Width, Instance.Height); Rectangle cellRect = Grid.GetCellRect(row, col); // get rectangle relative to control Point p = Grid.PointToScreen(new Point(cellRect.Left, cellRect.Top)); // get coords relative to screen cellRect = new Rectangle(p.X, p.Y, cellRect.Width, cellRect.Height); if (findRect.IntersectsWith(cellRect)) { Instance.Top = cellRect.Top - Instance.Height - 4; } break; } } Progress.Text = ""; FindNext.Enabled = true; CloseButton.Text = "Close"; InFindNext_Click = false; return; }
/// <summary> /// Build a set of rows from data in the buffer /// </summary> public override void BuildDataFromOtherRetrievedData( QueryEngine qe, int ti, List <object[]> results, int firstResult, int resultCount) { // This routine takes a set of results in the buffer, computes the calculated field value // and stores the results back in the buffer. For a calc field derived from a single column // the process is simple; however, for two column calculations there are two cases to consider. // 1. If no values then nothing to compute. // 2. If both values are present in the buffer row then just use them. // 3. If a single value is present then pick up the most recent other value that // exists for the same key. // Note that if the query only retrieves one of the two fields the the other field // will be retrieved into the calc field buffer. QueryColumn qc; MetaColumn mc; CalcFieldColumn cfc, cfc2; int voiCfKey, voiCf, voi; object v, v1, v2, vn; object[] vo, mergedVo; const int keyOffset = 1; throw new NotImplementedException(); #if false Query q = qe.Query; CalcFieldMetaTable cfMt = GetCalcFieldMetaTable(q.Tables[ti].MetaTable); CalcField cf = cfMt.CalcField; // Setup if (resultCount <= 0) { return; } if (SelectList.Count <= 1) { return; // just return if only key selected } voiCfKey = Qt.KeyQueryColumn.VoPosition; // calc field key value buffer index voiCf = Qt.GetQueryColumnByNameWithException("CALC_FIELD").VoPosition; // calculated value buffer index mergedVo = new object[results[0].Length]; // merged vo containing latest values for each column // Process each result row for (int ri = firstResult; ri < firstResult + resultCount; ri++) // result loop { vo = results[ri]; if (vo[0] == null) { continue; } if (mergedVo[0] == null || Lex.Ne(vo[0].ToString(), mergedVo[0].ToString())) { // if new key init voVals Array.Clear(mergedVo, 0, mergedVo.Length); mergedVo[0] = vo[0]; } int nonNullCount = 0; int nullCount = 0; QueryColumn[] colMap = _dataMap.InputColMap; for (int mi = 0; mi < colMap.Length; mi++) { if (colMap[mi] == null) { continue; // } voi = colMap[mi].VoPosition; v = vo[voi]; if (!NullValue.IsNull(v)) { mergedVo[voi] = v; nonNullCount++; } else { nullCount++; } } if (nonNullCount == 0) { continue; // if all inputs are null then all done (assume all outputs are null also) } vo[voiCfKey] = vo[0]; // copy key value QueryTableData qtd = qe.Qtd[ti]; // Pick up each retrieved value in the from other data fields for (int cfci = 0; cfci < qtd.SelectedColumns.Count; cfci++) // columns to retrieve/calculate loop { qc = qtd.SelectedColumns[cfci]; mc = qc.MetaColumn; voi = qc.VoPosition; bool calcFieldCol = Lex.Eq(mc.Name, "CALC_FIELD"); bool selectedCol = !calcFieldCol; // Input value column if (selectedCol) // retrieved input value { QueryColumn cmi = _dataMap.SelectedColMap[cfci]; if (cmi != null && cmi.VoPosition > 0) { v = mergedVo[cmi.VoPosition]; if (mc.DataType == MetaColumnType.Image) // convert to proper image reference { MetaTable sourceMt = cmi.QueryTable.MetaTable; GenericMetaBroker gmb = QueryEngine.GetGlobalBroker(cmi.QueryTable.MetaTable); v = gmb.ConvertValueToImageReference(v); } vo[voi] = v; } } // Calculate the CF value else { cfc = cf.CfCols[0]; vn = vo[voiCf]; // get possible single retrieved value vo[voiCf] = null; // clear calc value (may hold one of two values) v = mergedVo[colMap[0].VoPosition]; // get first value if (NullValue.IsNull(v)) { continue; // if null then result must be null } v = ApplyFunction(cfc, v); for (int mi = 1; mi < colMap.Length; mi++) // combine with { v1 = v; // reference previous value if (colMap[mi] == null) { continue; } cfc2 = cf.CfCols[mi]; voi = colMap[mi].VoPosition; v2 = mergedVo[voi]; v2 = ApplyFunction(cfc2, v2); v = CalculateValue(cf, v1, cfc2, v2); if (v == null) { break; } } v = ApplyClassification(cf, v); vo[voiCf] = v; // store calculated value } } // column loop vo = vo; // debug to check row loop at end } // row loop return; #endif }
/// <summary> /// Assign class to result /// </summary> /// <returns></returns> StringMx AssignClass() { if (Vo == null || ActivityClassVoi < 0) { return(null); } StringMx sx = new StringMx(); try { Vo[ActivityClassVoi] = null; if (NullValue.IsNull(ValNbr) && NullValue.IsNull(ValTxt)) { return(null); // need a numeric or text value } if (NullValue.IsNull(MethodId)) { throw new Exception("MethodId not defined"); } if (NullValue.IsNull(ResultTypeId)) { throw new Exception("ResultTypeId not defined"); } string actClass = ""; // Default SP/CRC activity class assignment if (NullValue.IsNull(ValNbr)) { return(null); // valid for numeric results only } // SP if (Lex.Eq(ResultSpCrc, "SP")) { if (Lex.Eq(ValPrefix, "<")) { actClass = "Fail"; } else if (ValNbr < 70) { actClass = "Fail"; } else if (ValNbr < 90) { actClass = "BorderLine"; } else if (ValNbr >= 90) { actClass = "Pass"; } } // CRC else if (Lex.Eq(ResultSpCrc, "CRC")) { double factor = 1.0; // normalize to uM units if (Lex.Eq(Units, "uM")) { factor = 1; } else if (Lex.Eq(Units, "mM")) { factor = 1000; } else if (Lex.Eq(Units, "nM")) { factor = 0.001; } else { return(null); } double v = ValNbr * factor; if (Lex.Eq(ValPrefix, ">")) { actClass = "Fail"; } else if (v > 5) { actClass = "Fail"; } else if (v > 0.1) { actClass = "BorderLine"; } else { actClass = "Pass"; } } else { return(null); } sx.Value = actClass; //todo: apply coloring... } catch (Exception ex) // if exception, store exception message in class result { sx = new StringMx(); sx.Value = ex.Message; } Vo[ActivityClassVoi] = sx; // store class info return(sx); }
/// <summary> /// Summarize pivoted data /// </summary> /// <param name="sumLevel"></param> /// <param name="sumMethod"></param> /// <returns></returns> public QueryManager SummarizePivoted( TargetAssaySummarizationLevel sumLevel, SummarizationType sumMethod, ColumnsToTransform colsToSumm, OutputDest outputDest, TargetMap targetMap) { QueryManager qm2; QueryTable qt; DataRow dr, dr2; DataRowAttributes dra; string cid = "", currentCid; int rti, rfi; qm2 = InitializeSubqueryQm(MultiDbAssayDataNames.CombinedNonSumTableName); #if false // Get the data for a compound, summarize & add results to data for charting DataTableManager dtm = Qm0.DataTableManager; for (int dri = 0; dri < dtm.DataTable.Rows.Count; dri++) { DataRow dr = dtm.DataTable.Rows[dri]; DataRowAttributes dra = GetRowAttributes(dr); string keyVal = dr[KeyValueVoPos] as string; if (keyVal != curKeyVal || Rf.Tables.Count <= 1) // going to new key { curKeyVal = keyVal; curKeyRow = dri; rowsForKey = 0; } rowsForKey++; object o = dr[dci]; // if (o is string && ((string)o) == "") o = o; // debug if (NullValue.IsNull(o)) { if (rowsForKey == 0 || // count as null if first row for key dra.TableRowState[colInfo.TableIndex] != RowStateEnum.Undefined) // or real row data but col is null { stats.NullsExist = true; } continue; } else if (o is MobiusDataType) { // create a MobiusDataType that we can point to o = MobiusDataType.New(o); dr[dci] = o; } MobiusDataType val = o as MobiusDataType; try { if (val.FormattedText == null) // get formatted text if not done yet { val = QueryManager.ResultsFormatter.FormatField(rt, ti, rfld, fi, dr, dri, val, -1, false); } dictKey = val.FormattedText.ToUpper(); if (!stats.DistinctValueDict.ContainsKey(dictKey)) { DistinctValueAndPosition dvp = new DistinctValueAndPosition(); dvp.Value = val; stats.DistinctValueDict[dictKey] = dvp; } } catch (Exception ex) { val = val; } } // row loop dtm.n #endif return(qm2); }
/// <summary> /// Prompt user for structure file name and read in structure /// </summary> /// <returns></returns> public static bool ReadMoleculeFileDialog( out MoleculeMx mol, out string fileName) { while (true) { mol = null; string filter = "Molecule Files (*.mol; *.sdf; *.smi; *.helm; *.txt)|*.mol; *.sdf; *.smi; *.helm; *.hlm; *.txt;|All files (*.*)|*.*"; fileName = UIMisc.GetOpenFilename( "Retrieve Model Structure from File", "", filter, "MOL"); if (String.IsNullOrEmpty(fileName)) { return(false); } try { if (Lex.EndsWith(fileName, ".mol") || Lex.EndsWith(fileName, ".sdf")) { mol = MoleculeMx.ReadMolfile(fileName); } if (Lex.EndsWith(fileName, ".smi")) { mol = MoleculeMx.ReadSmilesFile(fileName); } else if (Lex.EndsWith(fileName, ".skc")) { mol = MoleculeMx.ReadSketchFile(fileName); } else if (Lex.EndsWith(fileName, ".helm")) { mol = MoleculeMx.ReadHelmFile(fileName); } else if (Lex.EndsWith(fileName, ".fasta")) { mol = MoleculeMx.ReadFastaFile(fileName); } else if (Lex.EndsWith(fileName, ".seq")) { mol = MoleculeMx.ReadBiopolymerSequenceFile(fileName); } else // something else, look at the contents { string txt = FileUtil.ReadFile(fileName); mol = new MoleculeMx(txt); } } catch (Exception ex) // if error clear mol and try again { mol = null; } if (NullValue.IsNull(mol)) { MessageBoxMx.ShowError("Unable to read molecule file: " + fileName); continue; // try again } return(true); } }
private void BindPostEdit() { Debug.Assert(PostId != null, "PostId Should not be null when we call this"); SetConfirmation(); Entry entry = GetEntryForEditing(PostId.Value); if (entry == null) { ReturnToOrigin(null); return; } txbTitle.Text = entry.Title; if (!NullValue.IsNull(entry.DateSyndicated) && entry.DateSyndicated > Config.CurrentBlog.TimeZone.Now) { txtPostDate.Text = entry.DateSyndicated.ToString(CultureInfo.CurrentCulture); } VirtualPath entryUrl = Url.EntryUrl(entry); if (entryUrl != null) { hlEntryLink.NavigateUrl = entryUrl; hlEntryLink.Text = entryUrl.ToFullyQualifiedUrl(Config.CurrentBlog).ToString(); hlEntryLink.Attributes.Add("title", "view: " + entry.Title); } else { hlEntryLink.Text = "This post has not been published yet, so it doesn't have an URL"; } PopulateMimeTypeDropDown(); //Enclosures if (entry.Enclosure != null) { Enclosure.Collapsed = false; txbEnclosureTitle.Text = entry.Enclosure.Title; txbEnclosureUrl.Text = entry.Enclosure.Url; txbEnclosureSize.Text = entry.Enclosure.Size.ToString(); if (ddlMimeType.Items.FindByText(entry.Enclosure.MimeType) != null) { ddlMimeType.SelectedValue = entry.Enclosure.MimeType; } else { ddlMimeType.SelectedValue = "other"; txbEnclosureOtherMimetype.Text = entry.Enclosure.MimeType; } ddlAddToFeed.SelectedValue = entry.Enclosure.AddToFeed.ToString().ToLower(); ddlDisplayOnPost.SelectedValue = entry.Enclosure.ShowWithPost.ToString().ToLower(); } chkComments.Checked = entry.AllowComments; chkCommentsClosed.Checked = entry.CommentingClosed; SetCommentControls(); if (entry.CommentingClosedByAge) { chkCommentsClosed.Enabled = false; } chkDisplayHomePage.Checked = entry.DisplayOnHomePage; chkMainSyndication.Checked = entry.IncludeInMainSyndication; chkSyndicateDescriptionOnly.Checked = entry.SyndicateDescriptionOnly; chkIsAggregated.Checked = entry.IsAggregated; // Advanced Options txbEntryName.Text = entry.EntryName; txbExcerpt.Text = entry.Description; SetEditorText(entry.Body); ckbPublished.Checked = entry.IsActive; BindCategoryList(); for (int i = 0; i < cklCategories.Items.Count; i++) { cklCategories.Items[i].Selected = false; } ICollection <Link> postCategories = Repository.GetLinkCollectionByPostId(PostId.Value); if (postCategories.Count > 0) { foreach (Link postCategory in postCategories) { ListItem categoryItem = cklCategories.Items.FindByValue(postCategory.CategoryId.ToString(CultureInfo.InvariantCulture)); if (categoryItem == null) { throw new InvalidOperationException( string.Format(Resources.EntryEditor_CouldNotFindCategoryInList, postCategory.CategoryId, cklCategories.Items.Count)); } categoryItem.Selected = true; } } SetEditorMode(); Advanced.Collapsed = !Preferences.AlwaysExpandAdvanced; var adminMasterPage = Page.Master as AdminPageTemplate; if (adminMasterPage != null) { string title = string.Format(CultureInfo.InvariantCulture, Resources.EntryEditor_EditingTitle, CategoryType == CategoryType.StoryCollection ? Resources.Label_Article : Resources.Label_Post, entry.Title); adminMasterPage.Title = title; } if (entry.HasEntryName) { Advanced.Collapsed = false; txbEntryName.Text = entry.EntryName; } }
public int Publish(Entry entry) { if (entry == null) { throw new ArgumentNullException("entry"); } if (entry.PostType == PostType.None) { throw new ArgumentException(Resources.InvalidOperation_PostTypeIsNone, "entry"); } entry.Body = Transformation.Transform(entry.Body); if (String.IsNullOrEmpty(entry.EntryName)) { entry.EntryName = SlugGenerator.GetSlugFromTitle(entry); } if (entry.EntryName.IsNumeric()) { entry.EntryName = "n_" + entry.EntryName; } if (NullValue.IsNull(entry.DateCreated)) { entry.DateCreated = SubtextContext.Blog.TimeZone.Now; } if (NullValue.IsNull(entry.DateModified)) { entry.DateModified = SubtextContext.Blog.TimeZone.Now; } if (entry.IsActive) { if (NullValue.IsNull(entry.DateSyndicated) && entry.IncludeInMainSyndication) { entry.DateSyndicated = SubtextContext.Blog.TimeZone.Now; } } else { entry.DateSyndicated = NullValue.NullDateTime; } IEnumerable <int> categoryIds = null; if (entry.Categories.Count > 0) { categoryIds = GetCategoryIdsFromCategoryTitles(entry); } try { if (NullValue.IsNull(entry.Id)) { SubtextContext.Repository.Create(entry, categoryIds); } else { SubtextContext.Repository.Update(entry, categoryIds); } } catch (DbException e) { if (e.Message.Contains("pick a unique EntryName")) { throw new DuplicateEntryException(Resources.DuplicateEntryException_EntryNameAlreadyExists, e); } throw; } ValidateEntry(entry); IList <string> tags = entry.Body.ParseTags(); SubtextContext.Repository.SetEntryTagList(entry.Id, tags); IndexingService.AddPost(entry, tags); return(entry.Id); }
/// <summary> /// Build tooltip for data row /// </summary> /// <param name="dri">Data row index</param> /// <returns></returns> internal SuperToolTip BuildDataRowTooltip( TooltipDimensionDef ttDim, int dri) { ColumnMapMsx cm; QueryTable qt; QueryColumn qc; MetaTable mt; MetaColumn mc; int i1, i2; if (BaseQuery == null || BaseQuery.Tables.Count == 0 || Dtm == null) { return(null); } qt = BaseQuery.Tables[0]; SuperToolTip s = new SuperToolTip(); s.MaxWidth = 200; s.AllowHtmlText = DefaultBoolean.True; ToolTipItem i = new ToolTipItem(); i.AllowHtmlText = DefaultBoolean.True; i.Appearance.TextOptions.WordWrap = WordWrap.Wrap; ColumnMapCollection cml2 = new ColumnMapCollection(); // list of fields we'll actually display int strPos = -1; ColumnMapCollection cml = ttDim.Fields; if (cml.Count == 0) { return(s); } for (i1 = 0; i1 < cml.Count; i1++) { cm = cml[i1]; qc = cm.QueryColumn; if (qc == null || !cm.Selected) { continue; } //if (qc.IsKey) continue; if (qc.MetaColumn.DataType == MetaColumnType.Structure) { strPos = i1; } for (i2 = 0; i2 < cml2.Count; i2++) // see if already have the column { if (qc == cml2[i2].QueryColumn) { break; } } if (i2 < cml2.Count) { continue; } cml2.Add(cm); } if (cml2.Count == 0) { return(null); // no fields } if (strPos < 0 && ttDim.IncludeStructure) { // include str if requested & not already included qc = qt.FirstStructureQueryColumn; strPos = cml2.Count; // put str at end //strPos = keyPos + 1; // place str after key if (qc != null && qc.Selected) // regular selected Qc? { cml2.ColumnMapList.Insert(strPos, ColumnMapMsx.BuildFromQueryColumn(qc)); } else // look in root table for a structure { mt = qt.MetaTable.Root; if (mt.FirstStructureMetaColumn != null) { qt = new QueryTable(mt); qc = new QueryColumn(); // add qc with no vo pos as indicator that must be selected qc.MetaColumn = mt.FirstStructureMetaColumn; qc.Selected = true; qt.AddQueryColumn(qc); cml2.ColumnMapList.Insert(strPos, ColumnMapMsx.BuildFromQueryColumn(qc)); } } } string keyVal = ""; foreach (ColumnMapMsx fli0 in cml2.ColumnMapList) // format each field { qc = fli0.QueryColumn; mc = qc.MetaColumn; i.Text += "<b>"; // build label if (!Lex.IsNullOrEmpty(fli0.ParameterName)) { i.Text += fli0.ParameterName; } else { i.Text += fli0.QueryColumn.ActiveLabel; } i.Text += ": </b>"; if (qc.VoPosition >= 0) { int ti = qc.QueryTable.TableIndex; int dri2 = Dtm.AdjustDataRowToCurrentDataForTable(dri, ti, true); DataRowMx dr = Qm.DataTable.Rows[dri2]; if (dr == null) { continue; } ResultsTable rt = Rf.Tables[ti]; object fieldValue = dr[qc.VoPosition]; if (!NullValue.IsNull(fieldValue)) { if (qc.IsKey) { keyVal = fieldValue.ToString(); } MobiusDataType mdt = MobiusDataType.ConvertToMobiusDataType(qc.MetaColumn.DataType, fieldValue); FormattedFieldInfo ffi = Qm.ResultsFormatter.FormatField(qc, mdt); if (mc.DataType != MetaColumnType.Structure) { i.Text += ffi.FormattedText; i.Text += "<br>"; } else { i = ToolTipUtil.AppendBitmapToToolTip(s, i, ffi.FormattedBitmap); } } else { i.Text += "<br>"; // no data } } else if (!Lex.IsNullOrEmpty(keyVal)) // select structure from db (may already have) { MoleculeMx cs = MoleculeUtil.SelectMoleculeForCid(keyVal, qc.MetaColumn.MetaTable); if (cs != null) { int width = ResultsFormatFactory.QcWidthInCharsToDisplayColWidthInMilliinches(mc.Width, ResultsFormat); FormattedFieldInfo ffi = Qm.ResultsFormatter.FormatStructure(cs, new CellStyleMx(), 's', 0, width, -1); i = ToolTipUtil.AppendBitmapToToolTip(s, i, ffi.FormattedBitmap); } } } if (i.Text.Length > 0) { s.Items.Add(i); } if (s.Items.Count == 0) { // show something by default i = new ToolTipItem(); i.Text = "No fields selected"; i.LeftIndent = 6; i.Appearance.TextOptions.WordWrap = WordWrap.Wrap; s.Items.Add(i); } //ToolTipTitleItem ti = new ToolTipTitleItem(); //ti.Text = "Dude"; //s.Items.Add(ti); //ToolTipItem i = new ToolTipItem(); //i.Text = "Subtext that is fairly long longer longest"; //i.LeftIndent = 6; //i.Appearance.TextOptions.WordWrap = WordWrap.Wrap; //s.Items.Add(i); //i = new ToolTipItem(); //Image img = Bitmap.FromFile(@"C:\Mobius_OpenSource\Mobius-3.0\ClientComponents\Resources\Mobius76x76DkBlueBack.bmp"); //i.Image = img; //s.Items.Add(i); //ToolTipSeparatorItem si = new ToolTipSeparatorItem(); return(s); //ChartPanel.ToolTipController.ToolTipLocation = ToolTipLocation.TopCenter; //ChartPanel.ToolTipController.AllowHtmlText = true; //string s = point.SeriesPointID.ToString(); //s = "This <b>SuperToolTip</b> supports <i>HTML formatting</i>"; }
private void UpdatePost() { DateTime postDate = NullValue.NullDateTime; vCustomPostDate.IsValid = string.IsNullOrEmpty(txtPostDate.Text) || DateTime.TryParse(txtPostDate.Text, out postDate); EnableEnclosureValidation(EnclosureEnabled()); if (Page.IsValid) { string successMessage = Constants.RES_SUCCESSNEW; try { Entry entry; if (PostId == null) { ValidateEntryTypeIsNotNone(EntryType); entry = new Entry(EntryType); } else { entry = GetEntryForEditing(PostId.Value); if (entry.PostType != EntryType) { EntryType = entry.PostType; } } entry.Title = txbTitle.Text; entry.Body = richTextEditor.Xhtml; entry.Author = Config.CurrentBlog.Author; entry.Email = Config.CurrentBlog.Email; entry.BlogId = Config.CurrentBlog.Id; //Enclosure int enclosureId = 0; if (entry.Enclosure != null) { enclosureId = entry.Enclosure.Id; } if (EnclosureEnabled()) { if (entry.Enclosure == null) { entry.Enclosure = new Enclosure(); } Enclosure enc = entry.Enclosure; enc.Title = txbEnclosureTitle.Text; enc.Url = txbEnclosureUrl.Text; enc.MimeType = ddlMimeType.SelectedValue.Equals("other") ? txbEnclosureOtherMimetype.Text : ddlMimeType.SelectedValue; long size; Int64.TryParse(txbEnclosureSize.Text, out size); enc.Size = size; enc.AddToFeed = Boolean.Parse(ddlAddToFeed.SelectedValue); enc.ShowWithPost = Boolean.Parse(ddlDisplayOnPost.SelectedValue); } else { entry.Enclosure = null; } // Advanced options entry.IsActive = ckbPublished.Checked; entry.AllowComments = chkComments.Checked; entry.CommentingClosed = chkCommentsClosed.Checked; entry.DisplayOnHomePage = chkDisplayHomePage.Checked; entry.IncludeInMainSyndication = chkMainSyndication.Checked; entry.SyndicateDescriptionOnly = chkSyndicateDescriptionOnly.Checked; entry.IsAggregated = chkIsAggregated.Checked; entry.EntryName = txbEntryName.Text.NullIfEmpty(); entry.Description = txbExcerpt.Text.NullIfEmpty(); entry.Categories.Clear(); ReplaceSelectedCategoryNames(entry.Categories); if (!NullValue.IsNull(postDate)) { entry.DateSyndicated = postDate; } if (PostId != null) { successMessage = Constants.RES_SUCCESSEDIT; entry.DateModified = Config.CurrentBlog.TimeZone.Now; entry.Id = PostId.Value; var entryPublisher = SubtextContext.ServiceLocator.GetService <IEntryPublisher>(); entryPublisher.Publish(entry); if (entry.Enclosure == null && enclosureId != 0) { Enclosures.Delete(enclosureId); } else if (entry.Enclosure != null && entry.Enclosure.Id != 0) { Enclosures.Update(entry.Enclosure); } else if (entry.Enclosure != null && entry.Enclosure.Id == 0) { entry.Enclosure.EntryId = entry.Id; Enclosures.Create(entry.Enclosure); } UpdateCategories(); } else { var entryPublisher = SubtextContext.ServiceLocator.GetService <IEntryPublisher>(); _postId = entryPublisher.Publish(entry); NotificationServices.Run(entry, Blog, Url); if (entry.Enclosure != null) { entry.Enclosure.EntryId = PostId.Value; Enclosures.Create(entry.Enclosure); } UpdateCategories(); AddCommunityCredits(entry); } } catch (Exception ex) { Messages.ShowError(String.Format(Constants.RES_EXCEPTION, Constants.RES_FAILUREEDIT, ex.Message)); successMessage = string.Empty; } //Prepared success messages were reset in the catch block because of some error on posting the content if (!String.IsNullOrEmpty(successMessage)) { ReturnToOrigin(successMessage); } } }