static void Test <T>(T instance) { byte[] expectedResult = { 4, 0, 0, 0, // offset to table start 248, 255, 255, 255, // soffset to vtable (-8) 12, 0, 0, 0, // uoffset_t to vector 6, 0, // vtable length 8, 0, // table length 4, 0, // offset of index 0 field 0, 0, // padding to 4-byte alignment 0, 0, 0, 0, // vector length }; var root = new RootTable <T> { Vector = instance }; Span <byte> target = new byte[1024]; int offset = FlatBufferSerializer.Default.Serialize(root, target); string csharp = FlatBufferSerializer.Default.Compile(root).CSharp; target = target.Slice(0, offset); Assert.True(expectedResult.AsSpan().SequenceEqual(target)); }
public uint GetHeapSize() { int heapValCount = RootTable.GetAllUniqueChildValues().Count; HashSet <string> uniqueExternCount = new HashSet <string>(); foreach (AssemblyInstruction instruction in _instructions) { switch (instruction) { case ExternInstruction externMethodSymbol: uniqueExternCount.Add(externMethodSymbol.Extern.ExternSignature); break; case ExternSetInstruction externSetInstruction: uniqueExternCount.Add(externSetInstruction.Extern.ExternSetSignature); break; case ExternGetInstruction externGetInstruction: uniqueExternCount.Add(externGetInstruction.Extern.ExternGetSignature); break; } } return((uint)(heapValCount + uniqueExternCount.Count)); }
public void MemoryVector_LazyDeserialize() { RootTable <Memory <byte> > root = new RootTable <Memory <byte> >() { Vector = new Memory <byte>(new byte[100]) }; root.Vector.Span.Fill(1); byte[] buffer = new byte[1024]; var options = new FlatBufferSerializerOptions(FlatBufferDeserializationOption.Lazy); var serializer = new FlatBufferSerializer(options); serializer.Serialize(root, buffer.AsSpan()); var parsed1 = serializer.Parse <RootTable <Memory <byte> > >(buffer); var parsed2 = serializer.Parse <RootTable <Memory <byte> > >(buffer); Assert.AreEqual((byte)1, parsed1.Vector.Span[0]); Assert.AreEqual((byte)1, parsed2.Vector.Span[0]); // Asser that this change affects both objects. parsed1.Vector.Span[0] = 2; Assert.AreEqual((byte)2, parsed1.Vector.Span[0]); Assert.AreEqual((byte)2, parsed2.Vector.Span[0]); }
public void EmitReturn(BoundExpression returnExpression) { if (returnExpression == null) { EmitReturn(); return; } MethodLinkage currentMethodLinkage = GetMethodLinkage(CurrentEmitMethod, false); if (currentMethodLinkage.ReturnValue != null) { EmitValueAssignment(currentMethodLinkage.ReturnValue, returnExpression); if (CurrentEmitMethod.Name == "OnOwnershipRequest" && !CurrentEmitMethod.IsExtern && GetMostDerivedMethod(CurrentEmitMethod) == CurrentEmitMethod) { if (_udonReturnValue == null) { _udonReturnValue = RootTable.CreateParameterValue("__returnValue", GetTypeSymbol(SpecialType.System_Object)); } Module.AddCopy(currentMethodLinkage.ReturnValue, _udonReturnValue); } } else { Emit(returnExpression); } EmitReturn(); }
private void InitConstFields() { foreach (var field in DeclaredFields) { Value fieldVal = RootTable.GetUserValue(field); // if (field.IsConstInitialized) // { // fieldVal.DefaultValue = field.InitializerExpression.ConstantValue.Value; // } if (field.InitializerExpression == null) { if (field.IsSerialized) { if (field.Type.IsArray) { fieldVal.DefaultValue = Activator.CreateInstance(fieldVal.UdonType.SystemType, 0); continue; } if (field.Type.UdonType.SystemType == typeof(string)) { fieldVal.DefaultValue = ""; continue; } } if (field.IsSynced && field.Type.UdonType.SystemType == typeof(string)) { fieldVal.DefaultValue = ""; } } } }
private void TestType <T>(bool listCache, Func <T> generator) where T : IEquatable <T> { var options = new FlatBufferSerializerOptions(listCache ? FlatBufferDeserializationOption.VectorCache : FlatBufferDeserializationOption.Lazy); FlatBufferSerializer serializer = new FlatBufferSerializer(options); { var memoryTable = new RootTable <IList <T> > { Vector = Enumerable.Range(0, 10).Select(i => generator()).ToArray() }; Span <byte> memory = new byte[10240]; int offset = serializer.Serialize(memoryTable, memory); var memoryTableResult = serializer.Parse <RootTable <IList <T> > >(memory.Slice(0, offset).ToArray()); var resultVector = memoryTableResult.Vector; for (int i = 0; i < memoryTableResult.Vector.Count; ++i) { Assert.AreEqual <T>(memoryTable.Vector[i], resultVector[i]); // reference equality should correspond to the serializer. Assert.AreEqual(listCache, object.ReferenceEquals(resultVector[i], resultVector[i])); } } { var memoryTable = new RootTable <IReadOnlyList <T> > { Vector = Enumerable.Range(0, 10).Select(i => generator()).ToArray() }; Span <byte> memory = new byte[10240]; int offset = serializer.Serialize(memoryTable, memory); var memoryTableResult = serializer.Parse <RootTable <IReadOnlyList <T> > >(memory.Slice(0, offset).ToArray()); var resultVector = memoryTableResult.Vector; for (int i = 0; i < memoryTableResult.Vector.Count; ++i) { Assert.AreEqual(memoryTable.Vector[i], resultVector[i]); // reference equality should correspond to the serializer. Assert.AreEqual(listCache, object.ReferenceEquals(resultVector[i], resultVector[i])); } } { var memoryTable = new RootTable <T[]> { Vector = Enumerable.Range(0, 10).Select(i => generator()).ToArray() }; Span <byte> memory = new byte[10240]; int offset = serializer.Serialize(memoryTable, memory); var memoryTableResult = serializer.Parse <RootTable <T[]> >(memory.Slice(0, offset).ToArray()); var resultVector = memoryTableResult.Vector; for (int i = 0; i < memoryTableResult.Vector.Length; ++i) { Assert.AreEqual(memoryTable.Vector[i], resultVector[i]); } } }
/// <summary> /// Click function to open an external web site when clicking on a CID in a SmallWorld database display /// </summary> /// <param name="args"></param> public static void OpenUrlFromSmallWorldCid( string cid) { string[] px = { "PBCHM", "PDB" }; RootTable rt = CompoundId.GetRootTableFromCid(cid); if (rt == null || Lex.IsUndefined(rt.CidUrl)) { if (rt != null && Lex.Contains(rt.MetaTableName, MetaTable.PrimaryRootTable)) { RelatedCompoundsDialog.Show(cid); return; } MessageBoxMx.ShowError("Unable to determine url link for compound Id: " + cid); return; } string url = rt.CidUrl; foreach (string p in px) // remove unwanted URLs { if (Lex.StartsWith(cid, p)) { cid = cid.Substring(p.Length); } } url = Lex.Replace(url, "[CID]", cid); SystemUtil.StartProcess(url); return; }
public void WriteWithArrayOfTables_ProducesCorrectToml() { // Arrange var root = new RootTable(); root.SubTable.Values.AddRange(new[] { new SubTable.ListTable() { SomeValue = 1 }, new SubTable.ListTable() { SomeValue = 5 } }); const string expected = @" [SubTable] [[SubTable.Values]] SomeValue = 1 [[SubTable.Values]] SomeValue = 5"; // Act var tml = Toml.WriteString(root); // Assert tml.ShouldBeSemanticallyEquivalentTo(expected); }
public void SimpleString() { var root = new RootTable <string> { Vector = new string(new char[] { (char)1, (char)2, (char)3 }), }; Span <byte> target = new byte[10240]; int offset = FlatBufferSerializer.Default.Serialize(root, target); target = target.Slice(0, offset); byte[] expectedResult = { 4, 0, 0, 0, // offset to table start 248, 255, 255, 255, // soffset to vtable (-8) 12, 0, 0, 0, // uoffset_t to vector 6, 0, // vtable length 8, 0, // table length 4, 0, // offset of index 0 field 0, 0, // padding to 4-byte alignment 3, 0, 0, 0, // vector length 1, 2, 3, 0, // data + null terminator (special case for string vectors). }; Assert.True(expectedResult.AsSpan().SequenceEqual(target)); }
public void EmptyString() { var root = new RootTable <string> { Vector = string.Empty, }; Span <byte> target = new byte[10240]; int offset = FlatBufferSerializer.Default.Serialize(root, target); target = target.Slice(0, offset); byte[] expectedResult = { 4, 0, 0, 0, // offset to table start 248, 255, 255, 255, // soffset to vtable (-8) 12, 0, 0, 0, // uoffset_t to string 6, 0, // vtable length 8, 0, // table length 4, 0, // offset of index 0 field 0, 0, // padding to 4-byte alignment 0, 0, 0, 0, // vector length 0, // null terminator (special case for strings). }; Assert.True(expectedResult.AsSpan().SequenceEqual(target)); }
public void SimpleListVector() { var root = new RootTable <IList <short> > { Vector = new short[] { 1, 2, 3, } }; Span <byte> target = new byte[10240]; int offset = FlatBufferSerializer.Default.Serialize(root, target); target = target.Slice(0, offset); byte[] expectedResult = { 4, 0, 0, 0, // offset to table start 248, 255, 255, 255, // soffset to vtable (-8) 12, 0, 0, 0, // uoffset_t to vector 6, 0, // vtable length 8, 0, // table length 4, 0, // offset of index 0 field 0, 0, // padding to 4-byte alignment 3, 0, 0, 0, // vector length // vector data 1, 0, 2, 0, 3, 0 }; Assert.IsTrue(expectedResult.AsSpan().SequenceEqual(target)); }
/// <summary> /// Main tool entry point /// </summary> /// <param name="args"></param> /// <returns></returns> public string Run( string args) { QbUtil.SetMode(QueryMode.Build); // be sure in build mode //List<StructureDbInfo> dbInfo = StructureDbInfo.GetList(); // get list of root structure tables //MetaTable mt = MetaTableCollection.Get(dbInfo[0].StructureTable); // use first structure table if (DatabasesToSearch.Text == "") { // default to first structure table List <RootTable> dbInfo = RootTable.GetList(); // get list of root structure tables if (dbInfo != null && dbInfo.Count > 0) { DatabasesToSearch.Text = dbInfo[0].Label; } } if (ServicesIniFile.Read("MultStructSearchHelpUrl") != "") { Help.Enabled = true; } DialogResult dr = ShowDialog(SessionManager.ActiveForm); return(""); }
internal static RootTable From <T>(TomlSettings settings, T obj) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } if (obj == null) { throw new ArgumentNullException(nameof(obj)); } if ((object)obj is RootTable rt) { return(rt); } var tt = new RootTable(settings); if ((object)obj is IDictionary dict) { CreateFromDictionary(); } else { CreateFromCustomClrObject(); } return(tt); void CreateFromDictionary() { foreach (DictionaryEntry r in dict) { tt.AddRow(new TomlKey((string)r.Key), TomlObject.CreateFrom(tt, r.Value)); } } void CreateFromCustomClrObject() { var t = obj.GetType(); var members = settings.GetSerializationMembers(t); foreach (var m in members) { object val = m.GetValue(obj); if (val != null) { TomlObject to = TomlObject.CreateFrom(tt, val); to.AddComments(settings.GetComments(t, m.Member)); tt.AddRow(m.Key, to); } } } }
private void BuildDataBlock(StringBuilder builder) { List <Value> allValues = RootTable.GetAllUniqueChildValues(); builder.Append(".data_start\n"); foreach (Value value in allValues) { if (value.AssociatedSymbol is FieldSymbol fieldSymbol) { if (fieldSymbol.IsSerialized) { builder.AppendFormat(" .export {0}\n", value.UniqueID); } UdonSyncMode?syncMode = fieldSymbol.SyncMode; switch (syncMode) { case UdonSyncMode.None: builder.AppendFormat(" .sync {0}, none\n", value.UniqueID); break; case UdonSyncMode.Linear: builder.AppendFormat(" .sync {0}, linear\n", value.UniqueID); break; case UdonSyncMode.Smooth: builder.AppendFormat(" .sync {0}, smooth\n", value.UniqueID); break; } } } foreach (Value value in allValues) { builder.AppendFormat(" {0}\n", value.GetDeclarationStr()); } builder.Append(".data_end\n"); }
public void StringVector_GreedyDeserialize_NotMutable() { RootTable <IList <string> > root = new RootTable <IList <string> > { Vector = new List <string> { "one", "two", "three" } }; var options = new FlatBufferSerializerOptions(FlatBufferDeserializationOption.Greedy); FlatBufferSerializer serializer = new FlatBufferSerializer(options); byte[] buffer = new byte[100]; serializer.Serialize(root, buffer); var parsed = serializer.Parse <RootTable <IList <string> > >(buffer); Assert.AreEqual(typeof(ReadOnlyCollection <string>), parsed.Vector.GetType()); Assert.IsTrue(parsed.Vector.IsReadOnly); Assert.ThrowsException <NotSupportedException>(() => parsed.Vector.Add("four")); }
public void NullListVector() { var root = new RootTable <IList <short> > { Vector = null }; Span <byte> target = new byte[10240]; int offset = FlatBufferSerializer.Default.Serialize(root, target); target = target.Slice(0, offset); byte[] expectedResult = { 4, 0, 0, 0, // offset to table start 252, 255, 255, 255, // soffset to vtable (-4) 4, 0, // vtable length 4, 0, // table length }; Assert.IsTrue(expectedResult.AsSpan().SequenceEqual(target)); }
internal static RootTable From <T>(TomlSettings settings, T obj) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } if (obj == null) { throw new ArgumentNullException(nameof(obj)); } var rt = obj as RootTable; if (rt != null) { return(rt); } var tt = new RootTable(settings); var t = obj.GetType(); var props = settings.GetSerializationProperties(t); var allObjects = new List <Tuple <string, TomlObject> >(); foreach (var p in props) { object val = p.GetValue(obj, null); if (val != null) { TomlObject to = TomlObject.CreateFrom(tt, val, p); AddComments(to, p); allObjects.Add(Tuple.Create(p.Name, to)); } } tt.AddScopeTypesLast(allObjects); return(tt); }
public void SerializeAndParse_Full() { ValueStruct vs = new ValueStruct { A = 1, B = 2, C = 3, Inner = new InnerValueStruct { A = 3.14f } }; for (int i = 0; i < vs.D_Length; ++i) { vs.D(i) = (byte)i; } RefStruct rs = new() { A = 1, VS = vs, }; RootTable table = new() { refStruct = rs, union = new TestUnion(vs), valueStruct = vs, valueStructVector = Enumerable.Range(0, 10).Select(x => vs).ToList(), vectorOfUnion = Enumerable.Range(0, 10).Select(x => new TestUnion(vs)).ToList(), }; ISerializer <RootTable> serializer = RootTable.Serializer; int maxBytes = serializer.GetMaxSize(table); byte[] buffer = new byte[maxBytes]; int written = serializer.Write(buffer, table); RootTable parsed = serializer.Parse(buffer[..written]);
public void StringVector_GreedyDeserialize_Mutable() { RootTable <IList <string> > root = new RootTable <IList <string> > { Vector = new List <string> { "one", "two", "three" } }; var options = new FlatBufferSerializerOptions(FlatBufferDeserializationOption.GreedyMutable); FlatBufferSerializer serializer = new FlatBufferSerializer(options); byte[] buffer = new byte[100]; serializer.Serialize(root, buffer); var parsed = serializer.Parse <RootTable <IList <string> > >(buffer); Assert.AreEqual(typeof(List <string>), parsed.Vector.GetType()); Assert.IsFalse(parsed.Vector.IsReadOnly); // Shouldn't throw. parsed.Vector.Add("four"); }
/// <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); }
public void Emit() { _returnValue = RootTable.CreateInternalValue(GetTypeSymbol(SpecialType.System_UInt32), "returnJump"); CurrentNode = EmitType.RoslynSymbol.DeclaringSyntaxReferences.First().GetSyntax(); DefaultExecutionOrder executionOrder = EmitType.GetAttribute <DefaultExecutionOrder>(); if (executionOrder != null) { if (executionOrder.order < (int.MinValue + 1000000)) { throw new CompilerException($"Execution orders below int.MinValue + 1000000 are reserved for internal use in U#"); } Module.ExecutionOrder = executionOrder.order; } TypeSymbol udonSharpBehaviourType = GetTypeSymbol(typeof(UdonSharpBehaviour)); Stack <TypeSymbol> emitTypeBases = new Stack <TypeSymbol>(); TypeSymbol currentEmitType = EmitType; while (currentEmitType.BaseType != null) { emitTypeBases.Push(currentEmitType); currentEmitType = currentEmitType.BaseType; if (currentEmitType == udonSharpBehaviourType) { break; } } if (currentEmitType != udonSharpBehaviourType) { throw new NotSupportedException("U# behaviour must inherit from UdonSharpBehaviour", currentEmitType.RoslynSymbol.DeclaringSyntaxReferences.First().GetSyntax().GetLocation()); } List <MethodSymbol> rootMethods = new List <MethodSymbol>(); List <FieldSymbol> userFields = new List <FieldSymbol>(); HashSet <FieldSymbol> visitedFields = new HashSet <FieldSymbol>(); // Visits each base class and searches for the most derived version of a method if it is overriden // The intention with this is to ensure a consistent ordering between all inheritors of a base class // This means that we can know that all inheritors of a class have the same method names and parameter symbol allocations // which allows people to call virtual methods on UdonSharpBehaviours and have Udon just make it work while (emitTypeBases.Count > 0) { TypeSymbol currentBase = emitTypeBases.Pop(); // Make sure fields get emitted foreach (FieldSymbol field in currentBase.GetMembers <FieldSymbol>(this)) { if (field.IsConst) { continue; } if (!visitedFields.Contains(field)) { userFields.Add(field); visitedFields.Add(field); } GetUserValue(field); } foreach (MethodSymbol methodSymbol in currentBase.GetMembers <MethodSymbol>(this)) { if (methodSymbol.RoslynSymbol.IsImplicitlyDeclared || methodSymbol.RoslynSymbol.IsStatic) { continue; } if (methodSymbol.HasOverrides) { MethodSymbol derivedMethod = GetMostDerivedMethod(methodSymbol); if (derivedMethod.RoslynSymbol.IsAbstract) { continue; } if (!rootMethods.Contains(derivedMethod)) { rootMethods.Add(derivedMethod); } } else if (!rootMethods.Contains(methodSymbol)) { if (methodSymbol.RoslynSymbol.IsAbstract) { continue; } rootMethods.Add(methodSymbol); } } } DeclaredFields = userFields.ToImmutableArray(); InitConstFields(); HashSet <MethodSymbol> emittedSet = new HashSet <MethodSymbol>(); HashSet <MethodSymbol> setToEmit = new HashSet <MethodSymbol>(); // Do not roll this into the while loop, the order must be maintained for the root symbols so calls across behaviours work consistently foreach (MethodSymbol methodSymbol in rootMethods) { using (new MethodEmitScope(methodSymbol, this)) { methodSymbol.Emit(this); } emittedSet.Add(methodSymbol); setToEmit.UnionWith(methodSymbol.DirectDependencies.OfType <MethodSymbol>()); } while (setToEmit.Count > 0) { HashSet <MethodSymbol> newEmitSet = new HashSet <MethodSymbol>(); foreach (var methodSymbol in setToEmit) { if (emittedSet.Contains(methodSymbol)) { continue; } if (methodSymbol.RoslynSymbol != null) { if (methodSymbol.RoslynSymbol.IsAbstract || methodSymbol.IsUntypedGenericMethod) { continue; } } if (!methodSymbol.IsStatic && methodSymbol.ContainingType.IsUdonSharpBehaviour) // Prevent other behaviour type's methods from leaking into this type from calls across behaviours { TypeSymbol topType = EmitType; bool foundType = false; while (topType != udonSharpBehaviourType) { if (methodSymbol.ContainingType == topType) { foundType = true; break; } topType = topType.BaseType; } if (!foundType) { continue; } } using (new MethodEmitScope(methodSymbol, this)) { methodSymbol.Emit(this); } emittedSet.Add(methodSymbol); newEmitSet.UnionWith(methodSymbol.DirectDependencies.OfType <MethodSymbol>()); } setToEmit = newEmitSet; } if (_recursiveStackVal != null) { _recursiveStackVal.DefaultValue = new object[_maxRecursiveStackPush]; } DebugInfo.FinalizeAssemblyInfo(); }
/// <summary> /// See if a ClickFunction command & process if so /// </summary> /// <param name="command"></param> /// <param name="qm"></param> /// <param name="cInf"></param> public static void Process( string command, QueryManager qm, CellInfo cInf = null) { QueryTable rootQt, qt; QueryColumn qc; MetaTable mt; MetaColumn mc; Query q2; string dbName = "", mtName = "", mcName = ""; List <string> args0, args; string funcName, arg1, arg2, arg3, arg4, arg5; string value = "", keyValue = ""; int ai; try { // Parse click function arguments stripping all single quotes. // Arguments may be defined in the clickfunction definition including col values // indicated by field.Value in the metacolumn clickfunction definition. // If no args are defined in the clickfunction definition then a field value // argument will be added by default or the keyValue if [keyvalue] appears in the // ClickFunction definition CurrentClickQueryManager = qm; args0 = Lex.ParseAllExcludingDelimiters(command, "( , )", false); args = new List <string>(); for (ai = 0; ai < args0.Count; ai++) // strip all single quotes { string arg = args0[ai]; if (arg.StartsWith("'")) { arg = Lex.RemoveSingleQuotes(arg); } //if (Lex.Eq(arg, "[rowcol]") && cInf!= null) //{ // pass grid row & col // args.Add(cInf.GridRowHandle.ToString()); // args.Add(cInf.GridColAbsoluteIndex.ToString()); //} //else args.Add(arg); } funcName = args[0]; arg1 = (args.Count >= 2 ? args[1] : ""); // get other args arg2 = (args.Count >= 3 ? args[2] : ""); arg3 = (args.Count >= 4 ? args[3] : ""); arg4 = (args.Count >= 5 ? args[4] : ""); arg5 = (args.Count >= 6 ? args[5] : ""); if (Lex.Eq(funcName, "DisplayAllData")) { // do all data display for supplied root table and key, i.e. DisplayAllData(TableName, KeyColName, KeyValue) ParseMetaTableMetaColumn(arg1, out mt, arg2, out mc); string extKey = arg3; string intKey = CompoundId.Normalize(extKey, mt); Progress.Show("Building Query..."); _query = QueryEngine.GetSelectAllDataQuery(mt.Name, intKey); Progress.Show("Retrieving data..."); // put up progress dialog since this may take a while QbUtil.RunPopupQuery(_query, mt.KeyMetaColumn.Name + " " + extKey); Progress.Hide(); return; } else if (Lex.Eq(funcName, "DisplayAllDataUsingDbName")) { // display all data for supplied database synonym & key value, i.e. DisplayAllData2(DataBaseSynonym, KeyValue) mtName = null; dbName = arg1; RootTable rti = RootTable.GetFromTableLabel(dbName); if (rti != null) { mtName = rti.MetaTableName; } else // try synonyms { DictionaryMx dict = DictionaryMx.Get("Database_Synonyms"); if (dict != null) { mtName = dict.LookupDefinition(dbName); } } if (String.IsNullOrEmpty(mtName)) { MessageBoxMx.ShowError("Unrecognized database: " + dbName); return; } mt = MetaTableCollection.Get(mtName); if (mt == null) { MessageBoxMx.ShowError("Can't find key metatable " + mtName + " for database " + dbName); return; } string extKey = arg2; string intKey = CompoundId.Normalize(extKey, mt); Progress.Show("Building Query..."); _query = QueryEngine.GetSelectAllDataQuery(mt.Name, intKey); Progress.Show("Retrieving data..."); // put up progress dialog since this may take a while QbUtil.RunPopupQuery(_query, mt.KeyMetaColumn.Name + " " + extKey); return; } // Run a query displaying results to a grid or web page and substituting a parameter value else if (Lex.Eq(funcName, "RunHtmlQuery") || Lex.Eq(funcName, "RunGridQuery")) { // command to display to grid or html if (arg1.StartsWith("MetaTreeNode=", StringComparison.OrdinalIgnoreCase)) { // query based on metatables under a tree node string nodeName = arg1.Substring("MetaTreeNode=".Length).Trim(); _cid = arg2; MetaTreeNode mtn = MetaTree.GetNode(nodeName); if (mtn == null) { MessageBoxMx.ShowError("Can't find tree node referenced in ClickFunction: " + nodeName); return; } _query = new Query(); MetaTable rootMt = null; foreach (MetaTreeNode mtn_ in mtn.Nodes) { if (!mtn_.IsDataTableType) { continue; } mt = MetaTableCollection.Get(mtn_.Target); if (mt == null) { continue; } if (rootMt == null) { rootMt = mt.Root; rootQt = new QueryTable(_query, rootMt); } if (mt == rootMt) { continue; } qt = new QueryTable(_query, mt); } if (_query.Tables.Count == 0) { MessageBoxMx.ShowError("No valid data tables found: " + nodeName); return; } _query.KeyCriteria = "= " + _cid; _title = mtn.Label + " for " + _query.Tables[0].MetaTable.MetaColumns[0].Label + " " + CompoundId.Format(_cid); } else if (arg1.StartsWith("Query=", StringComparison.OrdinalIgnoreCase)) { // query based on saved query string qIdString = arg1.Substring("Query=".Length).Trim(); if (qIdString.StartsWith("Query_", StringComparison.OrdinalIgnoreCase)) { qIdString = qIdString.Substring("Query_".Length).Trim(); } int qId = int.Parse(qIdString); _query = QbUtil.ReadQuery(qId); _cid = arg2; _query.KeyCriteria = "= " + _cid; _title = _query.UserObject.Name + " for " + _query.Tables[0].MetaTable.MetaColumns[0].Label + " " + CompoundId.Format(_cid); } else // explicit mql string to execute { _mql = arg1; // mql to execute if (Lex.IsUndefined(_mql)) { throw new Exception("Expected MQL query not found: " + command); } mt = null; mc = null; if (Lex.IsDefined(arg2) && Lex.IsDefined(arg3)) { mtName = arg2; mcName = arg3; value = arg4; // value to plug in to mql keyValue = value; ParseMetaTableMetaColumn(arg2, out mt, arg3, out mc); } else if (cInf != null) { mt = cInf.Mt; mc = cInf.Mc; value = cInf?.DataValue?.ToString(); keyValue = qm?.DataTableManager?.GetRowKey(cInf.DataRowIndex); } if (mt == null || mc == null) { throw new Exception("Invalid MetaTable or MetaColumn name(s): " + command); } if (!mc.IsNumeric) { value = Lex.AddSingleQuotes(value); // quote if not numeric } int i1 = _mql.ToLower().IndexOf("[value]"); // see if a value parameter if (i1 >= 0) { string value2 = value; _mql = _mql.Replace(_mql.Substring(i1, 7), value); _title = mc.Label + " " + value; } i1 = _mql.ToLower().IndexOf("[keyvalue]"); // see if a key value parameter if (i1 >= 0) { _mql = _mql.Replace(_mql.Substring(i1, 10), keyValue); _title = mt.KeyMetaColumn.Label + " " + keyValue; } try { _query = MqlUtil.ConvertMqlToQuery(_mql); } catch (Exception ex) { MessageBoxMx.ShowError("Error converting Mql to query: " + ex.Message); return; } } if (Lex.Eq(funcName, "RunHtmlQuery")) { QbUtil.RunPopupQuery(_query, _title, OutputDest.Html); } else // output to grid { QbUtil.RunPopupQuery(_query, _title, OutputDest.WinForms); } //else // create new grid query & run (will lose results for current query) //{ // QbUtil.NewQuery(_title); // show in query builder // QbUtil.SetCurrentQueryInstance(_query); // QbUtil.RenderQuery(); // string nextCommand = QueryExec.RunQuery(_query, OutputDest.Grid); //} return; } // Open a URL, normally substituting parameter value else if (Lex.Eq(funcName, "OpenUrl")) { string url = arg1; // url to execute value = arg2; // value to plug in to url int i1 = Lex.IndexOf(url, "[value]"); // fill in one of the value place holders if (i1 >= 0) { string value2 = value; url = url.Replace(url.Substring(i1, 7), value); } else // check to see if we are matching on key { i1 = Lex.IndexOf(url, "[keyvalue]"); if (i1 >= 0) { url = url.Replace(url.Substring(i1, 10), value); } } SystemUtil.StartProcess(url); return; } else if (Lex.Eq(funcName, "OpenUrlFromSmallWorldCid")) { SmallWorldDepictions.OpenUrlFromSmallWorldCid(arg1); return; } else if (Lex.Eq(funcName, "ShowProjectDescription")) { string projName = arg1; QbUtil.ShowProjectDescription(projName); return; } else if (Lex.Eq(funcName, "ShowTableDescription")) { mtName = arg1; QbUtil.ShowTableDescription(mtName); return; } else if (Lex.Eq(funcName, "DisplayDrilldownDetail")) { // drill down into a result value mtName = arg1; // table mcName = arg2; // column int level = Int32.Parse(arg3); string resultId = arg4; // quoted resultId to get q2 = QueryEngine.GetSummarizationDetailQuery(mtName, mcName, level, resultId); if (q2 == null) { throw new Exception("Unable to build drill-down query for: " + mtName + "." + mcName); } bool success = QbUtil.RunPopupQuery(q2, "Result Detail", OutputDest.WinForms); return; } //else if (Lex.Eq(funcName, "PopupSmilesStructure")) // display structure for a Smiles string (still needs some work...) //{ // string molString = arg1.ToString(); // ChemicalStructure cs = new ChemicalStructure(StructureFormat.Smiles, molString); // ToolHelper.DisplayStructureInPopupGrid("Title...", "Smiles", "Structure", cs); //} //else if (Lex.Eq(funcName, "PopupChimeStructure")) // display structure for a Chime string //{ // string molString = arg1.ToString(); // ChemicalStructure cs = new ChemicalStructure(StructureFormat.Smiles, molString); // ToolHelper.DisplayStructureInPopupGrid("Title...", "Smiles", "Structure", cs); //} else if (Lex.Eq(funcName, "DisplayWebPage")) { // substitute a field value into a url & display associated web page string url = arg1; ParseMetaTableMetaColumn(arg2, out mt, arg3, out mc); value = arg4; // value to plug in to mql // value = "{6E9C28EF-407E-44A0-9007-5FFB735A5C6C}"; // debug // value = "{0AC17903-E551-445E-BFAA-860023D2884F}"; // debug // value = "{63EE71F9-15BA-42FB-AFDC-C399103707B1}"; // debug // value = "{80591183-B7BA-4669-8C5F-7E7F53D981CE}"; //lex.OpenString(mc.ClickFunction); // reparse url to get proper case //funcName = lex.GetNonDelimiter(); //url = Lex.RemoveAllQuotes(lex.GetNonDelimiter()); _title = mc.Label + " " + value; int i1 = url.ToLower().IndexOf("[value]"); // fill in one of the value place holders if (i1 >= 0) { url = url.Replace(url.Substring(i1, 7), value); } else // check to see if we are matching on key { i1 = url.ToLower().IndexOf("[keyvalue]"); if (i1 >= 0) { url = url.Replace(url.Substring(i1, 10), value); _title = mt.KeyMetaColumn.Label + " " + value; } } UIMisc.ShowHtmlPopupFormDocument(url, _title); return; } else if (Lex.Eq(funcName, "DisplayOracleBlobDocument")) // display a document contained in an Oracle blob column { // Syntax: DisplayOracleBlobDocument(<table-to-lookup>, <value_match_column>, <file-name-or-type-col>, <content-column>) string table = arg1; string matchCol = arg2; string typeCol = arg3; string contentCol = arg4; string matchVal = arg5; // value to match try { string typeName; byte[] ba; UalUtil.SelectOracleBlob(table, matchCol, typeCol, contentCol, matchVal, out typeName, out ba); if (ba == null || ba.Length == 0) { return; } UIMisc.SaveAndOpenBinaryDocument(typeName, ba); } catch (Exception ex) { MessageBoxMx.ShowError("Error retrieving document: " + ex.Message); return; } return; } else if (Lex.Eq(funcName, "DisplayOracleClobDocument")) // display a document contained in an Oracle clob column { // Syntax: DisplayOracleBlobDocument(<table-to-lookup>, <value_match_column>, <file-name-or-type-col>, <content-column>) string table = arg1; string matchCol = arg2; string typeCol = arg3; string contentCol = arg4; string matchVal = arg5; // value to match try { string typeName, clobString; UalUtil.SelectOracleClob(table, matchCol, typeCol, contentCol, matchVal, out typeName, out clobString); if (Lex.IsUndefined(clobString)) { return; } UIMisc.SaveAndOpenBase64BinaryStringDocument(typeName, clobString); // assume clob string is a Base64Binary string } catch (Exception ex) { MessageBoxMx.ShowError("Error retrieving document: " + ex.Message); return; } return; } else if (Plugins.IsMethodExtensionPoint(funcName)) { List <object> objArgs = new List <object>(); for (ai = 1; ai < args.Count; ai++) // build list of object arguments { objArgs.Add(args[ai]); } Plugins.CallStringExtensionPointMethod(funcName, objArgs); } else if (Lex.Eq(funcName, "None")) // dummy click function { return; } else { MessageBoxMx.ShowError("Unrecogized click function: " + funcName); return; } } catch (Exception ex) { Exception ex2 = ex; if (ex.InnerException != null) { ex2 = ex.InnerException; } string msg = "Error executing ClickFunction: " + command + "\r\n" + DebugLog.FormatExceptionMessage(ex); MessageBoxMx.ShowError(msg); ServicesLog.Message(msg); } }
public Value GetUdonThisValue(TypeSymbol type) { return(RootTable.GetUdonThisValue(type)); }
public Value GetConstantValue(TypeSymbol type, object value) { return(RootTable.GetConstantValue(type, value)); }
private void TestType <T>(Func <T> generator, int length) { if (typeof(T) == typeof(byte)) { var memoryTable = new RootTable <Memory <T> > { Vector = Enumerable.Range(0, length).Select(i => generator()).ToArray(), Inner = new InnerTable <Memory <T> > { Vector = Enumerable.Range(0, length).Select(i => generator()).ToArray(), } }; Span <byte> memory = new byte[10240]; int offset = FlatBufferSerializer.Default.Serialize(memoryTable, memory); var memoryTableResult = FlatBufferSerializer.Default.Parse <RootTable <Memory <T> > >(memory.Slice(0, offset).ToArray()); var resultVector = memoryTableResult.Vector; Assert.AreEqual(length, resultVector.Length); for (int i = 0; i < memoryTableResult.Vector.Length; ++i) { Assert.AreEqual(memoryTable.Vector.Span[i], resultVector.Span[i]); } } if (typeof(T) == typeof(byte)) { var memoryTable = new RootTable <ReadOnlyMemory <T> > { Vector = Enumerable.Range(0, length).Select(i => generator()).ToArray(), Inner = new InnerTable <ReadOnlyMemory <T> > { Vector = Enumerable.Range(0, length).Select(i => generator()).ToArray(), } }; Span <byte> memory = new byte[10240]; int offset = FlatBufferSerializer.Default.Serialize(memoryTable, memory); var memoryTableResult = FlatBufferSerializer.Default.Parse <RootTable <ReadOnlyMemory <T> > >(memory.Slice(0, offset).ToArray()); var resultVector = memoryTableResult.Vector; Assert.AreEqual(length, resultVector.Length); for (int i = 0; i < memoryTableResult.Vector.Length; ++i) { Assert.AreEqual(memoryTable.Vector.Span[i], resultVector.Span[i]); } } { var memoryTable = new RootTable <IList <T> > { Vector = Enumerable.Range(0, length).Select(i => generator()).ToArray(), Inner = new InnerTable <IList <T> > { Vector = Enumerable.Range(0, length).Select(i => generator()).ToArray(), } }; Span <byte> memory = new byte[10240]; int offset = FlatBufferSerializer.Default.Serialize(memoryTable, memory); var memoryTableResult = FlatBufferSerializer.Default.Parse <RootTable <IList <T> > >(memory.Slice(0, offset).ToArray()); var resultVector = memoryTableResult.Vector; Assert.AreEqual(length, resultVector.Count); for (int i = 0; i < memoryTableResult.Vector.Count; ++i) { Assert.AreEqual(memoryTable.Vector[i], resultVector[i]); } } { var memoryTable = new RootTable <IReadOnlyList <T> > { Vector = Enumerable.Range(0, length).Select(i => generator()).ToArray(), Inner = new InnerTable <IReadOnlyList <T> > { Vector = Enumerable.Range(0, length).Select(i => generator()).ToArray(), } }; Span <byte> memory = new byte[10240]; int offset = FlatBufferSerializer.Default.Serialize(memoryTable, memory); var memoryTableResult = FlatBufferSerializer.Default.Parse <RootTable <IReadOnlyList <T> > >(memory.Slice(0, offset).ToArray()); var resultVector = memoryTableResult.Vector; Assert.AreEqual(length, resultVector.Count); for (int i = 0; i < memoryTableResult.Vector.Count; ++i) { Assert.AreEqual(memoryTable.Vector[i], resultVector[i]); } } { var memoryTable = new RootTable <T[]> { Vector = Enumerable.Range(0, length).Select(i => generator()).ToArray(), Inner = new InnerTable <T[]> { Vector = Enumerable.Range(0, length).Select(i => generator()).ToArray(), } }; Span <byte> memory = new byte[10240]; int offset = FlatBufferSerializer.Default.Serialize(memoryTable, memory); var memoryTableResult = FlatBufferSerializer.Default.Parse <RootTable <T[]> >(memory.Slice(0, offset).ToArray()); var resultVector = memoryTableResult.Vector; Assert.AreEqual(length, resultVector.Length); for (int i = 0; i < memoryTableResult.Vector.Length; ++i) { Assert.AreEqual(memoryTable.Vector[i], resultVector[i]); } var inner = memoryTableResult.Inner; var innerVector = inner.Vector; Assert.AreEqual(length, innerVector.Length); for (int i = 0; i < innerVector.Length; ++i) { Assert.AreEqual(memoryTable.Inner.Vector[i], innerVector[i]); } } }
private void OK_Click(object sender, EventArgs e) { int CnCount; string listName, listText, errMsg = "", tok, cidLo, cidHi, cid = null, cid2 = null; QueryColumn qc = Qc; MetaColumn mc = qc.MetaColumn; MetaTable mt = mc.MetaTable; // Perform validity check on form // Equality if (EQ.Checked) { tok = Cid.Text.ToUpper(); if (tok == "") { XtraMessageBox.Show("Single compound value is missing", UmlautMobius.String, MessageBoxButtons.OK, MessageBoxIcon.None); Cid.Focus(); return; } if (SS.I.ValidateCompoundIds) { if (tok == "") { errMsg = "You must supply a " + qc.ActiveLabel; } else if (RootTable.IsStructureDatabaseRootTable(mt.Root)) { if (!CompoundId.IsValidForDatabase(tok, mt)) { errMsg = tok + " is not a valid " + qc.ActiveLabel; } else { cid = CompoundId.Normalize(tok, mt); tok = CompoundId.Format(cid, mt); errMsg = ""; } } else { cid = tok; // use as is errMsg = ""; // no error } if (errMsg != "") { MessageBoxMx.Show(errMsg, UmlautMobius.String, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } } qc.CriteriaDisplay = "= " + tok; qc.Criteria = mc.Name + " = " + Lex.AddSingleQuotes(cid); CnCount = 1; } // List else if (InList.Checked) { listText = CidListString.Trim(); if (listText == "") { XtraMessageBox.Show("The list must contain one or more items", UmlautMobius.String, MessageBoxButtons.OK, MessageBoxIcon.None); if (CidListDisplayIsEditable()) { CidListDisplay.Focus(); } return; } qc.CriteriaDisplay = CidList.FormatAbbreviatedCidListForDisplay(qc, listText); qc.Criteria = mc.Name + " IN (" + listText + ")"; } // Current list else if (TempList.Checked) { qc.CriteriaDisplay = "In temporary list: " + TempListName.Text; qc.Criteria = mc.Name + " IN LIST " + UserObject.TempFolderNameQualified + TempListName.Text; CnCount = SessionManager.CurrentResultKeysCount; } // Saved list else if (SavedList.Checked) { if (ListName.Text.Trim() == "") { XtraMessageBox.Show("A list name must be supplied", UmlautMobius.String, MessageBoxButtons.OK, MessageBoxIcon.None); ListName.Focus(); return; } string internalName = ResolveSavedListUo(); if (internalName == null) { return; } qc.CriteriaDisplay = "In list: " + SavedListUo.Name; qc.Criteria = mc.Name + " IN LIST " + Lex.AddSingleQuotes("CNLIST_" + SavedListUo.Id.ToString()); // quote list name CnCount = 1; // may be larger } // Between else if (Between.Checked) { cidLo = CidLo.Text.Trim(); cidHi = CidHi.Text.Trim(); if (cidLo == "" || cidHi == "") { XtraMessageBox.Show("Between value is missing", UmlautMobius.String, MessageBoxButtons.OK, MessageBoxIcon.None); if (CidLo.Text.Trim() == "") { CidLo.Focus(); } else if (CidHi.Text.Trim() == "") { CidHi.Focus(); } return; } if (SS.I.ValidateCompoundIds) { errMsg = ""; if (cidLo == "") { errMsg = "You must supply a " + qc.ActiveLabel; } else { if (!CompoundId.IsValidForDatabase(cidLo, mt)) { errMsg = cidLo + " is not a valid " + qc.ActiveLabel; } else { cid = CompoundId.Normalize(cidLo, mt); cidLo = CompoundId.Format(cid); } } if (errMsg != "") { MessageBoxMx.Show(errMsg, UmlautMobius.String, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } } else { cid = cidLo; // use as is } if (SS.I.ValidateCompoundIds) { errMsg = ""; if (cidHi == "") { errMsg = "You must supply a " + qc.ActiveLabel; } else { if (!CompoundId.IsValidForDatabase(cidHi, mt)) { errMsg = cidHi + " is not a valid " + qc.ActiveLabel; } else { cid2 = CompoundId.Normalize(cidHi, mt); cidHi = CompoundId.Format(cid2); } } if (errMsg != "") { MessageBoxMx.Show(errMsg, UmlautMobius.String, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } } else { cid2 = cidHi; // use as is } qc.CriteriaDisplay = "Between " + cidLo + " and " + cidHi; qc.Criteria = mc.Name + " BETWEEN " + Lex.AddSingleQuotes(cid) + " AND " + Lex.AddSingleQuotes(cid2); } else if (None.Checked) { qc.CriteriaDisplay = ""; qc.Criteria = ""; CnCount = 0; } DialogResult = DialogResult.OK; // this.Hide(); }
/// <summary> /// New parent database selected /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ParentCompoundCollection_TextChanged(object sender, EventArgs e) { string colType = ""; if (InSetup) { return; } string parentDb = ParentCompoundCollection.Text; string parentMtName = null; RootTable rti = RootTable.GetFromTableLabel(parentDb); if (rti == null) { return; } if (!Lex.Eq(parentDb, "UserDatabase")) { parentMtName = rti.MetaTableName; } else // prompt user for user database { UserObject ubdbUo = UserObjectOpenDialog.ShowDialog(UserObjectType.UserDatabase, "Select Parent User Database"); if (ubdbUo == null) { return; } List <UserObject> luo = GetUcdbUserObjects(ubdbUo.Id); if (luo == null) { return; } foreach (UserObject uo3 in luo) { if (uo3.Type != UserObjectType.Annotation) { return; // structure or annotation table } MetaTable mt2 = MetaTable.Deserialize(uo3.Content); if (!mt2.IsUserDatabaseStructureTable) { return; // ucdb structure table } InSetup = true; ParentCompoundCollection.Text = "UserDatabase: " + ubdbUo.Name; InSetup = false; parentMtName = mt2.Name; break; } } ParentMt = MetaTableCollection.Get(parentMtName); if (ParentMt == null) { return; } MetaColumn mc = ParentMt.KeyMetaColumn; if (AMt != null) { // if annotation, link in parent & key metacolumn info AMt.Parent = ParentMt; if (AMt.MetaColumns.Count > 0) { AMt.MetaColumns[0] = mc.Clone(); // clone key AMt.MetaColumns[0].MetaTable = AMt; // set proper parent } } ColGridDataTable.Rows[0][0] = mc.Label; // show label in grid also if (mc.DataType == MetaColumnType.CompoundId) { colType = "Compound Identifier"; } else if (mc.IsNumeric) { colType = "Number"; } else { colType = "Text"; } ColGridDataTable.Rows[0][1] = colType; return; }