public void MakeMessage(Message m, string fix) { idx = 0; prevIdx = 0; // Handle first field differently, no SOH at start. StringField sf = new StringField(0); idx = fix.IndexOf('\x01'); if (idx != -1) { field = fix.Substring(prevIdx, (idx - prevIdx)); tagIndex = field.IndexOf('='); sf.Tag = IntParse(field.Substring(0, tagIndex)); sf.Obj = field.Substring(tagIndex + 1); m.setField(sf); } else return; while (idx != -1) { prevIdx = idx; idx = fix.IndexOf('\x01', prevIdx + 1); if (idx == -1) break; StringField sf2 = new StringField(0); field = fix.Substring(prevIdx + 1, (idx - prevIdx) - 1); tagIndex = field.IndexOf('='); sf2.Tag = IntParse(field.Substring(0, tagIndex)); sf2.Obj = field.Substring(tagIndex + 1); m.setField(sf2); } }
public UnifiedField(StringField field) { Name = field.Name; NewValue = field.NewValue; OldValue = field.OldValue; ReferenceName = field.ReferenceName; }
public void StringFieldTest() { StringField field = new StringField(200, "wayner"); Assert.That(field.Obj, Is.EqualTo("wayner")); Assert.That(field.getValue(), Is.EqualTo("wayner")); Assert.That(field.Tag, Is.EqualTo(200)); field.setValue("galway"); Assert.That(field.Obj, Is.EqualTo("galway")); }
public AuditFileFieldInfo(StringField filename, StringField originalName, Int32Field size) { if (ReferenceEquals(null, filename)) throw new ArgumentNullException("filenameField"); Filename = filename; OriginalName = originalName; Size = size; }
public bool ActivateFor(Row row) { if (ReferenceEquals(null, Target)) return false; attr = Target.GetAttribute<ImageUploadEditorAttribute>(); if (attr == null || attr.DisableDefaultBehavior || attr.EditorType != "ImageUpload") return false; if (!(Target is StringField)) throw new ArgumentException(String.Format( "Field '{0}' on row type '{1}' has a UploadEditor attribute but it is not a String field!", Target.PropertyName ?? Target.Name, row.GetType().FullName)); if (!(row is IIdRow)) throw new ArgumentException(String.Format( "Field '{0}' on row type '{1}' has a UploadEditor attribute but Row type doesn't implement IIdRow!", Target.PropertyName ?? Target.Name, row.GetType().FullName)); if (!attr.OriginalNameProperty.IsEmptyOrNull()) { var originalNameField = row.FindFieldByPropertyName(attr.OriginalNameProperty) ?? row.FindField(attr.OriginalNameProperty); if (ReferenceEquals(null, originalNameField)) throw new ArgumentException(String.Format( "Field '{0}' on row type '{1}' has a UploadEditor attribute but " + "a field with OriginalNameProperty '{2}' is not found!", Target.PropertyName ?? Target.Name, row.GetType().FullName, attr.OriginalNameProperty)); this.originalNameField = (StringField)originalNameField; } var format = attr.FilenameFormat; if (format == null) { format = row.GetType().Name; if (format.EndsWith("Row")) format = format.Substring(0, format.Length - 3); format += "/~"; } this.fileNameFormat = format.Replace("~", SplittedFormat); this.replaceFields = ParseReplaceFields(fileNameFormat, row, Target); this.uploadHelper = new UploadHelper((attr.SubFolder.IsEmptyOrNull() ? "" : (attr.SubFolder + "/")) + (this.fileNameFormat)); return true; }
public static Field[] ToFieldArray(this IEnumerable<ICustomFieldDefinition> items, ICollection<Field> collection, string namePrefix, Action<Field, ICustomFieldDefinition> initialize = null) { var result = new List<Field>(); foreach (var item in items) { var flags = item.IsRequired ? Required : NotRequired; var caption = ToLocalText(item.Title); var name = (namePrefix ?? "") + item.Name; Field field; switch (item.FieldType) { case CustomFieldType.Boolean: field = new BooleanField(collection, name, caption, 0, flags); break; case CustomFieldType.Date: field = new DateTimeField(collection, name, caption, 0, flags) { DateTimeKind = DateTimeKind.Unspecified }; break; case CustomFieldType.DateTime: field = new DateTimeField(collection, name, caption, 0, flags) { DateTimeKind = DateTimeKind.Local }; break; case CustomFieldType.Decimal: field = new DecimalField(collection, name, caption, item.Size, flags); break; case CustomFieldType.Int32: field = new Int32Field(collection, name, caption, item.Size, flags); break; case CustomFieldType.Int64: field = new Int64Field(collection, name, caption, item.Size, flags); break; default: field = new StringField(collection, name, caption, item.Size, flags); break; } field.DefaultValue = item.DefaultValue.TrimToNull(); result.Add(field); if (initialize != null) initialize(field, item); } return result.ToArray(); }
public void DefaultValTest() { BooleanField bf = new BooleanField(110); Assert.That(false, Is.EqualTo(bf.Obj)); Assert.That(110, Is.EqualTo(bf.Tag)); CharField cf = new CharField(300); Assert.That('\0', Is.EqualTo(cf.getValue())); Assert.That(300, Is.EqualTo(cf.Tag)); DateTimeField dtf = new DateTimeField(3); Assert.That(3, Is.EqualTo(dtf.Tag)); StringField sf = new StringField(32); Assert.That(32, Is.EqualTo(sf.Tag)); Assert.That("", Is.EqualTo(sf.Obj)); IntField ifld = new IntField(239); Assert.That(239, Is.EqualTo(ifld.Tag)); Assert.That(0, Is.EqualTo(ifld.Obj)); DecimalField df = new DecimalField(1); Assert.That(1, Is.EqualTo(df.Tag)); Assert.That(new Decimal(0.0), Is.EqualTo(df.Obj)); }
public UnifiedField(StringField field) { Name = field.Name; ReferenceName = field.ReferenceName; switch (field.ReferenceName) { case "System.AssignedTo": case "System.ChangedBy": case "System.CreatedBy": case "System.AuthorizedAs": NewValue = GetDisplayName(field.NewValue); OldValue = GetDisplayName(field.OldValue); break; default: NewValue = field.NewValue; OldValue = field.OldValue; break; } }
public override void SetUp() { base.SetUp(); Dir = NewDirectory(); Iw = new RandomIndexWriter(Random(), Dir); Document doc = new Document(); Field idField = new StringField("id", "", Field.Store.NO); doc.Add(idField); // add 500 docs with id 0..499 for (int i = 0; i < 500; i++) { idField.StringValue = Convert.ToString(i); Iw.AddDocument(doc); } // delete 20 of them for (int i = 0; i < 20; i++) { Iw.DeleteDocuments(new Term("id", Convert.ToString(Random().Next(Iw.MaxDoc())))); } Ir = Iw.Reader; @is = NewSearcher(Ir); }
public void Test() { RandomIndexWriter writer; DirectoryReader indexReader; int numParents = AtLeast(200); IndexWriterConfig cfg = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())); cfg.SetMergePolicy(NewLogMergePolicy()); using (writer = new RandomIndexWriter(Random(), NewDirectory(), cfg)) { Document parentDoc = new Document(); NumericDocValuesField parentVal = new NumericDocValuesField("parent_val", 0L); parentDoc.Add(parentVal); StringField parent = new StringField("parent", "true", Field.Store.YES); parentDoc.Add(parent); for (int i = 0; i < numParents; ++i) { List <Document> documents = new List <Document>(); int numChildren = Random().nextInt(10); for (int j = 0; j < numChildren; ++j) { Document childDoc = new Document(); childDoc.Add(new NumericDocValuesField("child_val", Random().nextInt(5))); documents.Add(childDoc); } parentVal.LongValue = (Random().nextInt(50)); documents.Add(parentDoc); writer.AddDocuments(documents); } writer.ForceMerge(1); indexReader = writer.Reader; } AtomicReader reader = GetOnlySegmentReader(indexReader); Filter parentsFilter = new FixedBitSetCachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("parent", "true")))); FixedBitSet parentBits = (FixedBitSet)parentsFilter.GetDocIdSet(reader.AtomicContext, null); NumericDocValues parentValues = reader.GetNumericDocValues("parent_val"); NumericDocValues childValues = reader.GetNumericDocValues("child_val"); Sort parentSort = new Sort(new SortField("parent_val", SortField.Type_e.LONG)); Sort childSort = new Sort(new SortField("child_val", SortField.Type_e.LONG)); Sort sort = new Sort(new SortField("custom", new BlockJoinComparatorSource(parentsFilter, parentSort, childSort))); Sorter sorter = new Sorter(sort); Sorter.DocMap docMap = sorter.Sort(reader); assertEquals(reader.MaxDoc, docMap.Count); int[] children = new int[1]; int numChildren2 = 0; int previousParent = -1; for (int i = 0; i < docMap.Count; ++i) { int oldID = docMap.NewToOld(i); if (parentBits.Get(oldID)) { // check that we have the right children for (int j = 0; j < numChildren2; ++j) { assertEquals(oldID, parentBits.NextSetBit(children[j])); } // check that children are sorted for (int j = 1; j < numChildren2; ++j) { int doc1 = children[j - 1]; int doc2 = children[j]; if (childValues.Get(doc1) == childValues.Get(doc2)) { assertTrue(doc1 < doc2); // sort is stable } else { assertTrue(childValues.Get(doc1) < childValues.Get(doc2)); } } // check that parents are sorted if (previousParent != -1) { if (parentValues.Get(previousParent) == parentValues.Get(oldID)) { assertTrue(previousParent < oldID); } else { assertTrue(parentValues.Get(previousParent) < parentValues.Get(oldID)); } } // reset previousParent = oldID; numChildren2 = 0; } else { children = ArrayUtil.Grow(children, numChildren2 + 1); children[numChildren2++] = oldID; } } indexReader.Dispose(); writer.w.Directory.Dispose(); }
private string GetEnumValueFromField(StringField f, DataDictionary.DDField field) { if (field == null || !field.HasEnums()) return null; else { string enumValue = string.Empty; string[] values = f.getValue().Split(' '); StringBuilder sb = new StringBuilder(); foreach (string val in values) { if (field.EnumDict.TryGetValue(val, out enumValue)) { sb.AppendFormat("{0}, ", enumValue); } } string res = sb.ToString(); if (!string.IsNullOrEmpty(res)) { res = res.TrimEnd(' ', ','); } return res; } }
public override void ApplyData(string data) { if (!includeInSavedGameData) { return; } if (string.IsNullOrEmpty(data)) { return; } try { QuestMachine.isLoadingGame = true; var saveData = SaveSystem.Deserialize <SaveData>(data); if (saveData == null) { return; } // Clear current quest list: DestroyQuestInstances(); // Adds them to deletedStaticQuests, but that's OK since we're going to restore deletedStaticQuests. // Restore dynamic quests: for (int i = 0; i < saveData.proceduralQuests.Count; i++) { try { var questProxy = JsonUtility.FromJson <QuestProxy>(saveData.proceduralQuests[i]); if (questProxy == null) { continue; } var quest = ScriptableObject.CreateInstance <Quest>(); quest.name = questProxy.displayName; questProxy.CopyTo(quest); AddQuest(quest); } catch (Exception e) { if (Debug.isDebugBuild) { Debug.LogWarning("Quest Machine: Unable to restore quest from serialized quest proxy. Message: " + e.Message + "\nData: " + saveData.proceduralQuests[i], this); } } } // Restore list of deleted static quests: deletedStaticQuests.Clear(); deletedStaticQuests.AddRange(saveData.deletedStaticQuests); // Restore static quests: for (int i = 0; i < Mathf.Min(saveData.staticQuestIds.Count, saveData.staticQuestData.Count); i++) { var questID = saveData.staticQuestIds[i]; var questData = saveData.staticQuestData[i]; if (string.IsNullOrEmpty(questID) || questData == null || questData.bytes == null) { continue; } if (deletedStaticQuests.Contains(questID)) { continue; } var quest = QuestMachine.GetQuestAsset(questID); if (quest == null) { quest = originalQuestList.Find(x => string.Equals(StringField.GetStringValue(x.id), questID)); } if (quest == null && Debug.isDebugBuild) { Debug.LogError("Quest Machine: " + name + " Can't find quest " + saveData.staticQuestIds[i] + ". Is it registered with Quest Machine?", this); } if (quest == null) { continue; } quest = quest.Clone(); try { QuestStateSerializer.DeserializeInto(quest, questData.bytes, true); } catch (Exception e) { try { if (Debug.isDebugBuild) { Debug.LogWarning("Quest Machine: Unable to restore quest: " + quest.name + ". Message: " + e.Message, this); } Destroy(quest); } catch (Exception) { } quest = quest.Clone(); } AddQuest(quest); } QuestMachineMessages.RefreshIndicator(this, QuestMachineMessages.GetID(this)); } finally { QuestMachine.isLoadingGame = false; } }
private void Int32Filed_FieldChanged(object sender, EventArgs e) { StringField stringField = sender as StringField; ValueAfterEvent += 5; }
// [Test, LongRunningTest, Timeout(int.MaxValue)] // LUCENENET NOTE: For now, we are overriding this test in every subclass to pull it into the right context for the subclass public virtual void TestBigDocuments() { // "big" as "much bigger than the chunk size" // for this test we force a FS dir // we can't just use newFSDirectory, because this test doesn't really index anything. // so if we get NRTCachingDir+SimpleText, we make massive stored fields and OOM (LUCENE-4484) Directory dir = new MockDirectoryWrapper(Random(), new MMapDirectory(CreateTempDir("testBigDocuments"))); IndexWriterConfig iwConf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())); iwConf.SetMaxBufferedDocs(RandomInts.NextIntBetween(Random(), 2, 30)); RandomIndexWriter iw = new RandomIndexWriter(Random(), dir, iwConf); if (dir is MockDirectoryWrapper) { ((MockDirectoryWrapper)dir).Throttling = MockDirectoryWrapper.Throttling_e.NEVER; } Document emptyDoc = new Document(); // emptyDoc Document bigDoc1 = new Document(); // lot of small fields Document bigDoc2 = new Document(); // 1 very big field Field idField = new StringField("id", "", Field.Store.NO); emptyDoc.Add(idField); bigDoc1.Add(idField); bigDoc2.Add(idField); FieldType onlyStored = new FieldType(StringField.TYPE_STORED); onlyStored.IsIndexed = false; Field smallField = new Field("fld", RandomByteArray(Random().Next(10), 256), onlyStored); int numFields = RandomInts.NextIntBetween(Random(), 500000, 1000000); for (int i = 0; i < numFields; ++i) { bigDoc1.Add(smallField); } Field bigField = new Field("fld", RandomByteArray(RandomInts.NextIntBetween(Random(), 1000000, 5000000), 2), onlyStored); bigDoc2.Add(bigField); int numDocs = AtLeast(5); Document[] docs = new Document[numDocs]; for (int i = 0; i < numDocs; ++i) { docs[i] = RandomInts.RandomFrom(Random(), Arrays.AsList(emptyDoc, bigDoc1, bigDoc2)); } for (int i = 0; i < numDocs; ++i) { idField.SetStringValue("" + i); iw.AddDocument(docs[i]); if (Random().Next(numDocs) == 0) { iw.Commit(); } } iw.Commit(); iw.ForceMerge(1); // look at what happens when big docs are merged DirectoryReader rd = DirectoryReader.Open(dir); IndexSearcher searcher = new IndexSearcher(rd); for (int i = 0; i < numDocs; ++i) { Query query = new TermQuery(new Term("id", "" + i)); TopDocs topDocs = searcher.Search(query, 1); Assert.AreEqual(1, topDocs.TotalHits, "" + i); Document doc = rd.Document(topDocs.ScoreDocs[0].Doc); Assert.IsNotNull(doc); IIndexableField[] fieldValues = doc.GetFields("fld"); Assert.AreEqual(docs[i].GetFields("fld").Length, fieldValues.Length); if (fieldValues.Length > 0) { Assert.AreEqual(docs[i].GetFields("fld")[0].GetBinaryValue(), fieldValues[0].GetBinaryValue()); } } rd.Dispose(); iw.Dispose(); dir.Dispose(); }
protected override void ConstructFields() { TableName = "TBL_PATIENT"; m_fldID = new StringField() { Owner = this, FieldName = "PATIENT_ID", Description = "ID", Size = 12, Required = true, KeyField = true }; m_fldFirstName = new StringField(){ Owner = this, FieldName = "FIRST_NAME", Description = "First Name", Size = 50, Required = true }; m_fldLastName = new StringField() { Owner = this, FieldName = "LAST_NAME", Description = "Last Name", Size = 50, Required = true }; m_fldContactPhone = new StringField() { Owner = this, FieldName = "PHONE_CONTACT", Description = "Contact Phone#", DataEntryFormat = DataEntryFormat.Phone, Size = 25 }; m_fldDOB = new DateTimeField() { Owner = this, FieldName = "DOB", Description = "Date of Birth", Required = true }; m_fldAdmissionDate = new DateTimeField() { Owner = this, FieldName = "ADM_DATE", Description = "Admission Date" }; m_fldMonthlyCost = new DecimalField() { Owner = this, FieldName = "MONTHLY_COST", Description = "Monthly Cost", MinValue = 0, DisplayFormat = "C" }; m_fldClassification = new StringField() { Owner = this, FieldName = "ATTITUDE_CLASSIFICATION", Description = "Classification", Required = true, Size = 3, LookupType = LookupType.Dictionary, DataEntryType = DataEntryType.Lookup, HasDefaultValue = true, DefaultValue = "BUD" }; m_fldClassification.LookupDictionary.Add("MRX, Marxist", "CAP, Capitalist", "NEH, Nehilist", "BUD, Buddhist"); m_fldReligious = new BoolField() { Owner = this, FieldName = "IS_RELIGIOUS", Description = "Religious", Required = true, DefaultValue = false, HasDefaultValue = true }; }
/// <summary> /// Creates a Message from a FIX string /// </summary> /// <param name="msgstr"></param> /// <param name="validate"></param> /// <param name="sessionDD"></param> /// <param name="appDD"></param> /// <param name="msgFactory">If null, any groups will be constructed as generic Group objects</param> /// <param name="ignoreBody">(default false) if true, ignores all non-header non-trailer fields. /// Intended for callers that only need rejection-related information from the header. /// </param> public void FromString(string msgstr, bool validate, DataDictionary.DataDictionary sessionDD, DataDictionary.DataDictionary appDD, IMessageFactory msgFactory, bool ignoreBody) { Clear(); string msgType = ""; bool expectingHeader = true; bool expectingBody = true; int count = 0; int pos = 0; DataDictionary.IFieldMapSpec msgMap = null; while (pos < msgstr.Length) { StringField f = ExtractField(msgstr, ref pos, sessionDD, appDD); if (validate && (count < 3) && (Header.HEADER_FIELD_ORDER[count++] != f.Tag)) { throw new InvalidMessage("Header fields out of order"); } if (IsHeaderField(f.Tag, sessionDD)) { if (!expectingHeader) { if (0 == field_) { field_ = f.Tag; } validStructure_ = false; } if (Tags.MsgType.Equals(f.Tag)) { msgType = string.Copy(f.Obj); if (appDD != null) { msgMap = appDD.GetMapForMessage(msgType); } } if (!this.Header.SetField(f, false)) { this.Header.RepeatedTags.Add(f); } if ((null != sessionDD) && sessionDD.Header.IsGroup(f.Tag)) { pos = SetGroup(f, msgstr, pos, this.Header, sessionDD.Header.GetGroupSpec(f.Tag), sessionDD, appDD, msgFactory); } } else if (IsTrailerField(f.Tag, sessionDD)) { expectingHeader = false; expectingBody = false; if (!this.Trailer.SetField(f, false)) { this.Trailer.RepeatedTags.Add(f); } if ((null != sessionDD) && sessionDD.Trailer.IsGroup(f.Tag)) { pos = SetGroup(f, msgstr, pos, this.Trailer, sessionDD.Trailer.GetGroup(f.Tag), sessionDD, appDD, msgFactory); } } else if (ignoreBody == false) { if (!expectingBody) { if (0 == field_) { field_ = f.Tag; } validStructure_ = false; } expectingHeader = false; if (!SetField(f, false)) { this.RepeatedTags.Add(f); } if ((null != msgMap) && (msgMap.IsGroup(f.Tag))) { pos = SetGroup(f, msgstr, pos, this, msgMap.GetGroupSpec(f.Tag), sessionDD, appDD, msgFactory); } } } if (validate) { Validate(); } }
public void TestMessageParserIntegrity() { string fix = "5=ASDF" + Message.SOH + "10=234" + Message.SOH; Message m = new Message(); StringField sf = new StringField(0); MakeMessage(m, fix); Assert.That(m.GetField(5), Is.EqualTo("ASDF")); Assert.That(m.GetField(10), Is.EqualTo("234")); }
public bool CancelarOrdem(OrdemCancelamentoInfo orderCancelInfo, long ini = 0, long fim = 0, long oriini = 0, long orifim = 0, int delay = 0, string mnemonic = "") { //Cria a mensagem FIX de OrderCancelRequest QuickFix.FIX44.OrderCancelRequest orderCancel = new QuickFix.FIX44.OrderCancelRequest(); if (orderCancelInfo.Account > 0) { orderCancel.Set(new Account(orderCancelInfo.Account.ToString())); } if (!string.IsNullOrEmpty(mnemonic)) { orderCancel.SetField(new Account(mnemonic), true); } orderCancel.Set(new OrigClOrdID(orderCancelInfo.OrigClOrdID)); orderCancel.Set(new ClOrdID(orderCancelInfo.ClOrdID)); if (orderCancelInfo.OrderID != null && orderCancelInfo.OrderID.Length > 0) { orderCancel.Set(new OrderID(orderCancelInfo.OrderID)); } // Instrument Identification Block orderCancel.Set(new Symbol(orderCancelInfo.Symbol)); orderCancel.Set(new SecurityID(orderCancelInfo.SecurityID)); orderCancel.Set(new SecurityIDSource(SecurityIDSource.EXCHANGE_SYMBOL)); if (orderCancelInfo.Side == OrdemDirecaoEnum.Venda) { orderCancel.Set(new Side(Side.SELL)); } else { orderCancel.Set(new Side(Side.BUY)); } orderCancel.Set(new TransactTime(DateTime.Now)); //ATP - 2012-10-29 //Qtde de contratos/papeis a serem cancelados orderCancel.Set(new OrderQty(orderCancelInfo.OrderQty)); // Cliente QuickFix.FIX44.OrderCancelRequest.NoPartyIDsGroup PartyIDGroup1 = new QuickFix.FIX44.OrderCancelRequest.NoPartyIDsGroup(); PartyIDGroup1.Set(new PartyID(orderCancelInfo.ExecBroker)); PartyIDGroup1.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroup1.Set(new PartyRole(PartyRole.ENTERING_TRADER)); // Corretora QuickFix.FIX44.OrderCancelRequest.NoPartyIDsGroup PartyIDGroup2 = new QuickFix.FIX44.OrderCancelRequest.NoPartyIDsGroup(); PartyIDGroup2.Set(new PartyID("227")); PartyIDGroup2.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroup2.Set(new PartyRole(PartyRole.ENTERING_FIRM)); QuickFix.FIX44.OrderCancelRequest.NoPartyIDsGroup PartyIDGroup3 = new QuickFix.FIX44.OrderCancelRequest.NoPartyIDsGroup(); if (orderCancelInfo.SenderLocation != null && orderCancelInfo.SenderLocation.Length > 0) { PartyIDGroup3.Set(new PartyID(orderCancelInfo.SenderLocation)); } else { PartyIDGroup3.Set(new PartyID("GRA")); } PartyIDGroup3.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroup3.Set(new PartyRole(54)); orderCancel.AddGroup(PartyIDGroup1); orderCancel.AddGroup(PartyIDGroup2); orderCancel.AddGroup(PartyIDGroup3); //BEI - 2012-Nov-14 if (orderCancelInfo.ForeignFirm != null && orderCancelInfo.ForeignFirm.Length > 0) { QuickFix.FIX44.OrderCancelRequest.NoPartyIDsGroup PartyIDGroup4 = new QuickFix.FIX44.OrderCancelRequest.NoPartyIDsGroup(); PartyIDGroup4.Set(new PartyID(orderCancelInfo.ForeignFirm)); PartyIDGroup4.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroup4.Set(new PartyRole(PartyRole.FOREIGN_FIRM)); orderCancel.AddGroup(PartyIDGroup4); } if (orderCancelInfo.ExecutingTrader != null && orderCancelInfo.ExecutingTrader.Length > 0) { QuickFix.FIX44.OrderCancelRequest.NoPartyIDsGroup PartyIDGroup7 = new QuickFix.FIX44.OrderCancelRequest.NoPartyIDsGroup(); PartyIDGroup7.Set(new PartyID(orderCancelInfo.ExecutingTrader)); PartyIDGroup7.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroup7.Set(new PartyRole(PartyRole.EXECUTING_TRADER)); orderCancel.AddGroup(PartyIDGroup7); } // Memo Field if (orderCancelInfo.Memo5149 != null && orderCancelInfo.Memo5149.Length > 0) { if (orderCancelInfo.Memo5149.Length > 50) { orderCancelInfo.Memo5149 = orderCancelInfo.Memo5149.Substring(0, 50); } StringField memo5149 = new StringField(5149, orderCancelInfo.Memo5149); orderCancel.SetField(memo5149); } bool bRet = false; if (oriini != 0 && orifim != 0) { long times = fim - ini; logger.Info("=====================================> INICIO CANCELAR ORDEM========> Qtd: " + times); for (long i = 0; i < times; i++) { ClOrdID xx = new ClOrdID(ini.ToString()); OrigClOrdID xx2 = new OrigClOrdID(oriini.ToString()); orderCancel.ClOrdID = xx; orderCancel.OrigClOrdID = xx2; bRet = Session.SendToTarget(orderCancel, _session.SessionID); if (!bRet) { logger.Info("erro"); break; } if (0 != delay) { Thread.Sleep(delay); } ini++; oriini++; //System.Windows.Forms.Application.DoEvents(); } logger.Info("=====================================> FIM CANCELAR ORDEM========> Qtd: " + times); } else { bRet = Session.SendToTarget(orderCancel, _session.SessionID); } return(bRet); }
public bool EnviarOrdemCross(OrdemCrossInfo crossinfo) { OrdemInfo ordemCompra = crossinfo.OrdemInfoCompra; OrdemInfo ordemVenda = crossinfo.OrdemInfoVenda; // Cria mensagem de new order cross - // Essa mensagem nao é padrao do 4.2 - some weird f*****g things can // f*****g happen with this f*****g shit code QuickFix.FIX44.NewOrderCross ordercross = new QuickFix.FIX44.NewOrderCross(); ordercross.Set(new CrossID(crossinfo.CrossID)); // Unico valor aceito 1 - Negocio executado total ou parcial ordercross.Set(new CrossType(1)); // Prioridade de uma das pontas. Unico valor aceito: 0 - nenhuma ordercross.Set(new CrossPrioritization(0)); // Ordem cross, sempre 2 pernas // Informacoes da perna de compra QuickFix.FIX44.NewOrderCross.NoSidesGroup sideGroupC = new QuickFix.FIX44.NewOrderCross.NoSidesGroup(); sideGroupC.Set(new Side(Side.BUY)); sideGroupC.Set(new ClOrdID(ordemCompra.ClOrdID)); if (ordemCompra.Account > 0) { sideGroupC.Set(new Account(ordemCompra.Account.ToString())); } sideGroupC.Set(new OrderQty(ordemCompra.OrderQty)); //sideGroupC.Set(new PositionEffect('C')); if (ordemCompra.PositionEffect != null && ordemCompra.PositionEffect.Equals("C")) { sideGroupC.Set(new PositionEffect('C')); } // PartIDs Compra // Cliente QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup PartyIDGroupC1 = new QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup(); PartyIDGroupC1.Set(new PartyID(ordemCompra.ExecBroker)); PartyIDGroupC1.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroupC1.Set(new PartyRole(PartyRole.ENTERING_TRADER)); // Corretora QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup PartyIDGroupC2 = new QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup(); PartyIDGroupC2.Set(new PartyID("227")); PartyIDGroupC2.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroupC2.Set(new PartyRole(PartyRole.ENTERING_FIRM)); // Sender Location QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup PartyIDGroupC3 = new QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup(); PartyIDGroupC3.Set(new PartyID("GRA")); PartyIDGroupC3.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroupC3.Set(new PartyRole(54)); // Adiciono os partIDs ao Side (perna de Compra) sideGroupC.AddGroup(PartyIDGroupC1); sideGroupC.AddGroup(PartyIDGroupC2); sideGroupC.AddGroup(PartyIDGroupC3); //BEI - 2012-Nov-14 if (ordemCompra.ForeignFirm != null && ordemCompra.ForeignFirm.Length > 0) { QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup PartyIDGroupC4 = new QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup(); PartyIDGroupC4.Set(new PartyID(ordemCompra.ForeignFirm)); PartyIDGroupC4.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroupC4.Set(new PartyRole(PartyRole.FOREIGN_FIRM)); sideGroupC.AddGroup(PartyIDGroupC4); } //SelfTradeProtection - 2012-Nov-27 if (ordemCompra.InvestorID != null && ordemCompra.InvestorID.Length > 0) { QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup PartyIDGroup4 = new QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup(); PartyIDGroup4.Set(new PartyID(ordemCompra.InvestorID)); PartyIDGroup4.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroup4.Set(new PartyRole(PartyRole.INVESTOR_ID)); sideGroupC.AddGroup(PartyIDGroup4); } if (ordemCompra.Account > 0) { QuickFix.FIX44.NewOrderSingle.NoAllocsGroup noAllocsGrpC = new QuickFix.FIX44.NewOrderSingle.NoAllocsGroup(); noAllocsGrpC.Set(new AllocAccount(ordemCompra.Account.ToString())); noAllocsGrpC.Set(new AllocAcctIDSource(99)); sideGroupC.AddGroup(noAllocsGrpC); } // Insere informacoes da perna de venda QuickFix.FIX44.NewOrderCross.NoSidesGroup sideGroupV = new QuickFix.FIX44.NewOrderCross.NoSidesGroup(); sideGroupV.Set(new Side(Side.SELL)); sideGroupV.Set(new ClOrdID(ordemVenda.ClOrdID)); if (ordemVenda.Account > 0) { sideGroupV.Set(new Account(ordemVenda.Account.ToString())); } sideGroupV.Set(new OrderQty(ordemVenda.OrderQty));; sideGroupV.Set(new PositionEffect('C')); if (ordemVenda.PositionEffect != null && ordemVenda.PositionEffect.Equals("C")) { sideGroupV.Set(new PositionEffect('C')); } // Cliente QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup PartyIDGroup1 = new QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup(); PartyIDGroup1.Set(new PartyID(ordemVenda.ExecBroker)); PartyIDGroup1.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroup1.Set(new PartyRole(PartyRole.ENTERING_TRADER)); // Corretora QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup PartyIDGroup2 = new QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup(); PartyIDGroup2.Set(new PartyID("227")); PartyIDGroup2.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroup2.Set(new PartyRole(PartyRole.ENTERING_FIRM)); // Sender Location ID QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup PartyIDGroup3 = new QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup(); PartyIDGroup3.Set(new PartyID("GRA")); PartyIDGroup3.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroup3.Set(new PartyRole(54)); // Adiciono os partIDs ao Side (perna de venda) sideGroupV.AddGroup(PartyIDGroup1); sideGroupV.AddGroup(PartyIDGroup2); sideGroupV.AddGroup(PartyIDGroup3); //BEI - 2012-Nov-14 if (ordemVenda.ForeignFirm != null && ordemVenda.ForeignFirm.Length > 0) { QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup PartyIDGroupV4 = new QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup(); PartyIDGroupV4.Set(new PartyID(ordemVenda.ForeignFirm)); PartyIDGroupV4.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroupV4.Set(new PartyRole(PartyRole.FOREIGN_FIRM)); sideGroupV.AddGroup(PartyIDGroupV4); } //SelfTradeProtection - 2012-Nov-27 if (ordemVenda.InvestorID != null && ordemVenda.InvestorID.Length > 0) { QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup PartyIDGroup4 = new QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup(); PartyIDGroup4.Set(new PartyID(ordemVenda.InvestorID)); PartyIDGroup4.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroup4.Set(new PartyRole(PartyRole.INVESTOR_ID)); sideGroupV.AddGroup(PartyIDGroup4); } if (ordemVenda.Account > 0) { QuickFix.FIX44.NewOrderSingle.NoAllocsGroup noAllocsGrpV = new QuickFix.FIX44.NewOrderSingle.NoAllocsGroup(); noAllocsGrpV.Set(new AllocAccount(ordemVenda.Account.ToString())); noAllocsGrpV.Set(new AllocAcctIDSource(99)); sideGroupV.AddGroup(noAllocsGrpV); } // Insere os grupos das 2 pernas ordercross.AddGroup(sideGroupC); ordercross.AddGroup(sideGroupV); ordercross.Set(new Symbol(crossinfo.Symbol)); if (crossinfo.SecurityID != null && crossinfo.SecurityID.Length > 0) { ordercross.Set(new SecurityID(crossinfo.SecurityID)); ordercross.Set(new SecurityIDSource("8")); } OrdType ordType = FixMessageUtilities.deOrdemTipoParaOrdType(crossinfo.OrdType); if (ordType != null) { ordercross.Set(ordType); } ordercross.Set(new Price(Convert.ToDecimal(crossinfo.Price))); ordercross.Set(new TransactTime(DateTime.Now)); // Memo Field if (crossinfo.Memo5149 != null && crossinfo.Memo5149.Length > 0) { if (crossinfo.Memo5149.Length > 50) { crossinfo.Memo5149 = crossinfo.Memo5149.Substring(0, 50); } StringField memo5149 = new StringField(5149, crossinfo.Memo5149); ordercross.SetField(memo5149); } bool bRet = Session.SendToTarget(ordercross, _session.SessionID); return(bRet); }
/* * public void ExecOrders(object arg) * { * NewOrderSingle ordem = (NewOrderSingle)arg; * long clordid = Convert.ToInt64(DateTime.Now.ToString("yyyyMMddhhmmssfff")); * bool bRet; * logger.Info("=====================================> INICIO ========> Regs: " + _times); * for (int i =0; i<_times; i++) * { * ClOrdID xx = new ClOrdID(clordid++.ToString()); * ordem.ClOrdID = xx; * //Thread.Sleep(1); * bRet = Session.SendToTarget(ordem, _session.SessionID); * } * logger.Info("=====================================> FIM ========> Regs: " + _times); * } */ public bool AlterarOrdem(OrdemInfo ordem, long ini = 0, long fim = 0, long oriini = 0, long orifim = 0, int delay = 0, string mnemonic = "") { //Cria a mensagem FIX de NewOrderSingle QuickFix.FIX44.OrderCancelReplaceRequest orderCancelReplaceReq = new QuickFix.FIX44.OrderCancelReplaceRequest(); orderCancelReplaceReq.Set(new OrigClOrdID(ordem.OrigClOrdID)); if (ordem.Account > 0) { orderCancelReplaceReq.Set(new Account(ordem.Account.ToString())); } if (!string.IsNullOrEmpty(mnemonic)) { orderCancelReplaceReq.SetField(new Account(mnemonic), true); } // Instrument Identification Block orderCancelReplaceReq.Set(new Symbol(ordem.Symbol)); orderCancelReplaceReq.Set(new SecurityID(ordem.SecurityID)); orderCancelReplaceReq.Set(new SecurityIDSource(SecurityIDSource.EXCHANGE_SYMBOL)); if (ordem.ExchangeNumberID != null && ordem.ExchangeNumberID.Length > 0) { orderCancelReplaceReq.Set(new OrderID(ordem.ExchangeNumberID)); } orderCancelReplaceReq.Set(new ClOrdID(ordem.ClOrdID)); //ordersingle.set(new IDSource()); if (ordem.Side == OrdemDirecaoEnum.Venda) { orderCancelReplaceReq.Set(new Side(Side.SELL)); } else { orderCancelReplaceReq.Set(new Side(Side.BUY)); } orderCancelReplaceReq.Set(new Price(Convert.ToDecimal(ordem.Price))); TimeInForce tif = FixMessageUtilities.deOrdemValidadeParaTimeInForce(ordem.TimeInForce); if (tif != null) { orderCancelReplaceReq.Set(tif); } orderCancelReplaceReq.Set(new OrderQty(ordem.OrderQty)); if (ordem.TimeInForce == OrdemValidadeEnum.ValidoAteDeterminadaData) { DateTime expiredate = Convert.ToDateTime(ordem.ExpireDate); orderCancelReplaceReq.Set(new ExpireDate(expiredate.ToString("yyyyMMdd"))); } OrdType ordType = FixMessageUtilities.deOrdemTipoParaOrdType(ordem.OrdType); if (ordType != null) { orderCancelReplaceReq.Set(ordType); } //if (ordem.OrdType == OrdemTipoEnum.StopLimitada ) //{ // ordersingle.set(new StopPx(ordem.StopPx)); //} orderCancelReplaceReq.Set(new TransactTime(DateTime.Now)); // Cliente QuickFix.FIX44.OrderCancelReplaceRequest.NoPartyIDsGroup PartyIDGroup1 = new QuickFix.FIX44.OrderCancelReplaceRequest.NoPartyIDsGroup(); PartyIDGroup1.Set(new PartyID(ordem.ExecBroker)); PartyIDGroup1.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroup1.Set(new PartyRole(PartyRole.ENTERING_TRADER)); // Corretora QuickFix.FIX44.OrderCancelReplaceRequest.NoPartyIDsGroup PartyIDGroup2 = new QuickFix.FIX44.OrderCancelReplaceRequest.NoPartyIDsGroup(); PartyIDGroup2.Set(new PartyID("227")); PartyIDGroup2.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroup2.Set(new PartyRole(PartyRole.ENTERING_FIRM)); // Location ID QuickFix.FIX44.OrderCancelReplaceRequest.NoPartyIDsGroup PartyIDGroup3 = new QuickFix.FIX44.OrderCancelReplaceRequest.NoPartyIDsGroup(); if (ordem.SenderLocation != null && ordem.SenderLocation.Length > 0) { PartyIDGroup3.Set(new PartyID(ordem.SenderLocation)); } else { PartyIDGroup3.Set(new PartyID("GRA")); } PartyIDGroup3.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroup3.Set(new PartyRole(54)); orderCancelReplaceReq.AddGroup(PartyIDGroup1); orderCancelReplaceReq.AddGroup(PartyIDGroup2); orderCancelReplaceReq.AddGroup(PartyIDGroup3); //BEI - 2012-Nov-14 if (ordem.ForeignFirm != null && ordem.ForeignFirm.Length > 0) { QuickFix.FIX44.OrderCancelReplaceRequest.NoPartyIDsGroup PartyIDGroup4 = new QuickFix.FIX44.OrderCancelReplaceRequest.NoPartyIDsGroup(); PartyIDGroup4.Set(new PartyID(ordem.ForeignFirm)); PartyIDGroup4.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroup4.Set(new PartyRole(PartyRole.FOREIGN_FIRM)); orderCancelReplaceReq.AddGroup(PartyIDGroup4); } if (ordem.Account > 0) { QuickFix.FIX44.OrderCancelReplaceRequest.NoAllocsGroup noAllocsGrp = new QuickFix.FIX44.OrderCancelReplaceRequest.NoAllocsGroup(); noAllocsGrp.Set(new AllocAccount(ordem.Account.ToString())); noAllocsGrp.Set(new AllocAcctIDSource(99)); orderCancelReplaceReq.AddGroup(noAllocsGrp); } //SelfTradeProtection - 2012-Nov-27 if (ordem.InvestorID != null && ordem.InvestorID.Length > 0) { QuickFix.FIX44.OrderCancelReplaceRequest.NoPartyIDsGroup PartyIDGroup5 = new QuickFix.FIX44.OrderCancelReplaceRequest.NoPartyIDsGroup(); PartyIDGroup5.Set(new PartyID(ordem.InvestorID)); PartyIDGroup5.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroup5.Set(new PartyRole(PartyRole.INVESTOR_ID)); orderCancelReplaceReq.AddGroup(PartyIDGroup5); } if (ordem.ExecutingTrader != null && ordem.ExecutingTrader.Length > 0) { QuickFix.FIX44.OrderCancelReplaceRequest.NoPartyIDsGroup PartyIDGroup7 = new QuickFix.FIX44.OrderCancelReplaceRequest.NoPartyIDsGroup(); PartyIDGroup7.Set(new PartyID(ordem.ExecutingTrader)); PartyIDGroup7.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroup7.Set(new PartyRole(PartyRole.EXECUTING_TRADER)); orderCancelReplaceReq.AddGroup(PartyIDGroup7); } // Memo Field if (ordem.Memo5149 != null && ordem.Memo5149.Length > 0) { if (ordem.Memo5149.Length > 50) { ordem.Memo5149 = ordem.Memo5149.Substring(0, 50); } StringField memo5149 = new StringField(5149, ordem.Memo5149); orderCancelReplaceReq.SetField(memo5149); } bool bRet = false; if (oriini != 0 && orifim != 0) { long times = fim - ini; logger.Info("=====================================> INICIO ALTERAR ORDEM========> Qtd: " + times); for (long i = 0; i < times; i++) { ClOrdID xx = new ClOrdID(ini.ToString()); OrigClOrdID xx2 = new OrigClOrdID(oriini.ToString()); orderCancelReplaceReq.ClOrdID = xx; orderCancelReplaceReq.OrigClOrdID = xx2; bRet = Session.SendToTarget(orderCancelReplaceReq, _session.SessionID); if (!bRet) { logger.Info("erro"); break; } if (0 != delay) { Thread.Sleep(delay); } ini++; oriini++; //System.Windows.Forms.Application.DoEvents(); } logger.Info("=====================================> FIM ALTERAR ORDEM========> Qtd: " + times); } else { bRet = Session.SendToTarget(orderCancelReplaceReq, _session.SessionID); } return(bRet); }
public bool EnviarOrdem(OrdemInfo ordem, long ini = 0, long fim = 0, int delay = 0, string mnemonic = "") { //Cria a mensagem FIX de NewOrderSingle QuickFix.FIX44.NewOrderSingle ordersingle = new QuickFix.FIX44.NewOrderSingle(); if (ordem.Account > 0) { ordersingle.Set(new Account(ordem.Account.ToString())); } if (!string.IsNullOrEmpty(mnemonic)) { ordersingle.SetField(new Account(mnemonic), true); } // Instrument Identification Block ordersingle.Set(new Symbol(ordem.Symbol)); if (!string.IsNullOrEmpty(ordem.SecurityID)) { ordersingle.Set(new SecurityID(ordem.SecurityID)); } ordersingle.Set(new SecurityIDSource(SecurityIDSource.EXCHANGE_SYMBOL)); //long clOrd =0; ordersingle.Set(new ClOrdID(ordem.ClOrdID)); if (ordem.Side == OrdemDirecaoEnum.Venda) { ordersingle.Set(new Side(Side.SELL)); } else { ordersingle.Set(new Side(Side.BUY)); } TimeInForce tif = FixMessageUtilities.deOrdemValidadeParaTimeInForce(ordem.TimeInForce); if (tif != null) { ordersingle.Set(tif); } ordersingle.Set(new OrderQty(ordem.OrderQty)); if (ordem.TimeInForce == OrdemValidadeEnum.ValidoAteDeterminadaData) { DateTime expiredate = Convert.ToDateTime(ordem.ExpireDate); ordersingle.Set(new ExpireDate(expiredate.ToString("yyyyMMdd"))); } OrdType ordType = FixMessageUtilities.deOrdemTipoParaOrdType(ordem.OrdType); if (ordType != null) { ordersingle.Set(ordType); } // Verifica envio do preco switch (ordem.OrdType) { case OrdemTipoEnum.Limitada: case OrdemTipoEnum.MarketWithLeftOverLimit: ordersingle.Set(new Price(Convert.ToDecimal(ordem.Price))); break; case OrdemTipoEnum.StopLimitada: case OrdemTipoEnum.StopStart: ordersingle.Set(new Price(Convert.ToDecimal(ordem.Price))); ordersingle.Set(new StopPx(Convert.ToDecimal(ordem.StopPrice))); break; case OrdemTipoEnum.Mercado: case OrdemTipoEnum.OnClose: break; default: ordersingle.Set(new Price(Convert.ToDecimal(ordem.Price))); break; } ordersingle.Set(new TransactTime(DateTime.Now)); ordersingle.Set(new HandlInst('1')); if (ordem.MaxFloor > 0) { ordersingle.Set(new MaxFloor(Convert.ToDecimal(ordem.MaxFloor))); } if (ordem.MinQty > 0) { ordersingle.Set(new MinQty(Convert.ToDecimal(ordem.MinQty))); } // Cliente QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup PartyIDGroup1 = new QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup(); //PartyIDGroup1.set(new PartyID(ordem.Account.ToString())); PartyIDGroup1.Set(new PartyID(ordem.ExecBroker)); PartyIDGroup1.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroup1.Set(new PartyRole(PartyRole.ENTERING_TRADER)); // Corretora QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup PartyIDGroup2 = new QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup(); PartyIDGroup2.Set(new PartyID("227")); PartyIDGroup2.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroup2.Set(new PartyRole(PartyRole.ENTERING_FIRM)); // Location ID QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup PartyIDGroup3 = new QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup(); if (ordem.SenderLocation != null && ordem.SenderLocation.Length > 0) { PartyIDGroup3.Set(new PartyID(ordem.SenderLocation)); } else { PartyIDGroup3.Set(new PartyID("GRA")); } PartyIDGroup3.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroup3.Set(new PartyRole(PartyRole.SENDER_LOCATION)); // Corretora QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup PartyIDGroup4 = new QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup(); PartyIDGroup4.Set(new PartyID("245427")); PartyIDGroup4.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroup4.Set(new PartyRole(PartyRole.ENTERING_FIRM)); ordersingle.AddGroup(PartyIDGroup1); ordersingle.AddGroup(PartyIDGroup2); ordersingle.AddGroup(PartyIDGroup3); //ordersingle.AddGroup(PartyIDGroup4); //BEI - 2012-Nov-13 if (ordem.ForeignFirm != null && ordem.ForeignFirm.Length > 0) { QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup PartyIDGroup5 = new QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup(); PartyIDGroup5.Set(new PartyID(ordem.ForeignFirm)); PartyIDGroup5.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroup5.Set(new PartyRole(PartyRole.FOREIGN_FIRM)); ordersingle.AddGroup(PartyIDGroup5); } //SelfTradeProtection - 2012-Nov-27 if (ordem.InvestorID != null && ordem.InvestorID.Length > 0) { QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup PartyIDGroup6 = new QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup(); PartyIDGroup6.Set(new PartyID(ordem.InvestorID)); PartyIDGroup6.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroup6.Set(new PartyRole(PartyRole.INVESTOR_ID)); ordersingle.AddGroup(PartyIDGroup6); } if (ordem.ExecutingTrader != null && ordem.ExecutingTrader.Length > 0) { QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup PartyIDGroup7 = new QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup(); PartyIDGroup7.Set(new PartyID(ordem.ExecutingTrader)); PartyIDGroup7.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE)); PartyIDGroup7.Set(new PartyRole(PartyRole.EXECUTING_TRADER)); ordersingle.AddGroup(PartyIDGroup7); } //if (ordem.Account > 0) //{ // QuickFix.FIX44.NewOrderSingle.NoAllocsGroup noAllocsGrp = new QuickFix.FIX44.NewOrderSingle.NoAllocsGroup(); // noAllocsGrp.Set(new AllocAccount(ordem.Account.ToString())); // noAllocsGrp.Set(new AllocAcctIDSource(99)); // ordersingle.AddGroup(noAllocsGrp); //} if (ordem.PositionEffect != null && ordem.PositionEffect.Equals("C")) { ordersingle.Set(new PositionEffect('C')); } // Memo Field if (ordem.Memo5149 != null && ordem.Memo5149.Length > 0) { if (ordem.Memo5149.Length > 50) { ordem.Memo5149 = ordem.Memo5149.Substring(0, 50); } StringField memo5149 = new StringField(5149, ordem.Memo5149); ordersingle.SetField(memo5149); } // AccountType if (ordem.AcountType == ContaTipoEnum.REMOVE_ACCOUNT_INFORMATION) { IntField int581 = new IntField(581, 38); ordersingle.SetField(int581); } else if (ordem.AcountType == ContaTipoEnum.GIVE_UP_LINK_IDENTIFIER) { IntField int581 = new IntField(581, 40); ordersingle.SetField(int581); } bool bRet = false; if (ini == 0) { bRet = Session.SendToTarget(ordersingle, _session.SessionID); } else { //_times = times; //Thread th = new Thread(new ParameterizedThreadStart(ExecOrders)); //th.Start(ordersingle); long times = fim - ini; logger.Info("=====================================> INICIO ========> Qtd: " + times); for (long i = 0; i < times; i++) { //logger.Info("XXX: " + i); ClOrdID xx = new ClOrdID(ini.ToString()); ordersingle.ClOrdID = xx; bRet = Session.SendToTarget(ordersingle, _session.SessionID); if (!bRet) { logger.Info("erro"); break; } if (0 != delay) { Thread.Sleep(delay); } ini++; //System.Windows.Forms.Application.DoEvents(); } logger.Info("=====================================> FIM ========> Qtd: " + times); } return(bRet); }
private UserControl BuildControl(FormControlSettings formControlSettings) { UserControl userControl = null; switch (formControlSettings.ObjectType) { case ObjectTypes.String: var stringField = new StringField(); stringField.BuildDisplay(formControlSettings); if (formControlSettings.Required) { OnValidate += stringField.Validate; } stringField.OnControlModified += s => OnPropertyModified?.Invoke(formControlSettings.FieldFullName, s); stringField.OnControlFinishedEditing += s => OnPropertyFinishedEditing?.Invoke(formControlSettings.FieldFullName, s); OnAddFieldInsertItems += (Name, Items) => { if (Name == formControlSettings.FieldFullName) { stringField.AddDropdownItems(Items, formControlSettings.Value); } }; //OnSpecialDropdownDisplaying?.Invoke(formControlSettings.FieldFullName); userControl = stringField; break; case ObjectTypes.Password: var passwordField = new PasswordField(); passwordField.BuildDisplay(formControlSettings); if (formControlSettings.Required) { OnValidate += passwordField.Validate; } passwordField.OnControlModified += s => OnPropertyModified?.Invoke(formControlSettings.FieldFullName, s); passwordField.OnControlFinishedEditing += s => OnPropertyFinishedEditing?.Invoke(formControlSettings.FieldFullName, s); userControl = passwordField; break; case ObjectTypes.Double: var doubleField = new DoubleField(); doubleField.BuildDisplay(formControlSettings); if (formControlSettings.Required) { OnValidate += doubleField.Validate; } doubleField.OnControlModified += s => OnPropertyModified?.Invoke(formControlSettings.FieldFullName, s); doubleField.OnControlFinishedEditing += s => OnPropertyFinishedEditing?.Invoke(formControlSettings.FieldFullName, s); userControl = doubleField; break; case ObjectTypes.Int32: var intField = new IntField(); intField.BuildDisplay(formControlSettings); if (formControlSettings.Required) { OnValidate += intField.Validate; } intField.OnControlModified += s => OnPropertyModified?.Invoke(formControlSettings.FieldFullName, s); intField.OnControlFinishedEditing += s => OnPropertyFinishedEditing?.Invoke(formControlSettings.FieldFullName, s); userControl = intField; break; case ObjectTypes.Single: var floatField = new FloatField(); floatField.BuildDisplay(formControlSettings); if (formControlSettings.Required) { OnValidate += floatField.Validate; } floatField.OnControlModified += s => OnPropertyModified?.Invoke(formControlSettings.FieldFullName, s); floatField.OnControlFinishedEditing += s => OnPropertyFinishedEditing?.Invoke(formControlSettings.FieldFullName, s); userControl = floatField; break; case ObjectTypes.Boolean: var booleanField = new BooleanField(); booleanField.BuildDisplay(formControlSettings); if (formControlSettings.Required) { OnValidate += booleanField.Validate; } booleanField.OnControlModified += s => OnPropertyModified?.Invoke(formControlSettings.FieldFullName, s); booleanField.OnControlFinishedEditing += s => OnPropertyFinishedEditing?.Invoke(formControlSettings.FieldFullName, s); userControl = booleanField; break; case ObjectTypes.SpecialDropdown: var specialDropdown = new SpecialDropdownField(); specialDropdown.BuildDisplay(formControlSettings); if (formControlSettings.Required) { OnValidate += specialDropdown.Validate; } OnAddSpecialDropdownItems += (Name, Items) => { if (Name == formControlSettings.FieldFullName) { specialDropdown.AddDropdownItems(Items, formControlSettings.Value); } }; OnSpecialDropdownDisplaying?.Invoke(formControlSettings.FieldFullName, (Name, Items) => { if (Name == formControlSettings.FieldFullName) { specialDropdown.AddDropdownItems(Items, formControlSettings.Value); } }); specialDropdown.OnControlModified += s => OnPropertyModified?.Invoke(formControlSettings.FieldFullName, s); specialDropdown.OnControlFinishedEditing += s => OnPropertyFinishedEditing?.Invoke(formControlSettings.FieldFullName, s); userControl = specialDropdown; break; case ObjectTypes.FolderBrowser: var folderStringField = new FolderBrowserField(); folderStringField.BuildDisplay(formControlSettings); if (formControlSettings.Required) { OnValidate += folderStringField.Validate; } folderStringField.OnControlModified += s => OnPropertyModified?.Invoke(formControlSettings.FieldFullName, s); folderStringField.OnControlFinishedEditing += s => OnPropertyFinishedEditing?.Invoke(formControlSettings.FieldFullName, s); userControl = folderStringField; break; case ObjectTypes.TimePicker: var timePickerField = new TimePickerField(); timePickerField.BuildDisplay(formControlSettings); timePickerField.OnControlModified += s => OnPropertyModified?.Invoke(formControlSettings.FieldFullName, s); timePickerField.OnControlFinishedEditing += s => OnPropertyFinishedEditing?.Invoke(formControlSettings.FieldFullName, s); userControl = timePickerField; break; case ObjectTypes.Custom: if (formControlSettings.FormField.CustomControl != null && formControlSettings.FormField.CustomControl.GetInterface(typeof(ICustomControl).FullName) != null) { var customControlClass = (ICustomControl)Activator.CreateInstance(formControlSettings.FormField.CustomControl); if (!(customControlClass is UserControl)) { break; } var customControlBase = new CustomControlBase(); customControlBase.BuildDisplay(formControlSettings, customControlClass); customControlBase.OnControlModified += s => OnPropertyModified?.Invoke(formControlSettings.FieldFullName, s); customControlBase.OnControlFinishedEditing += s => OnPropertyFinishedEditing?.Invoke(formControlSettings.FieldFullName, s); userControl = customControlBase; } break; } return(userControl); }
public void EqualsTest() { StringField a1 = new StringField(123, "a"); StringField aSame = a1; StringField a2 = new StringField(123, "a"); StringField diffValue = new StringField(123, "b"); StringField diffTag = new StringField(999, "a"); IField diffType = new CharField(123, 'a'); Assert.True(a1.Equals(aSame)); Assert.True(a1.Equals(a2)); Assert.False(a1.Equals(diffValue)); Assert.False(a1.Equals(diffTag)); Assert.False(a1.Equals(diffType)); }
protected int SetGroup(StringField grpNoFld, string msgstr, int pos, FieldMap fieldMap, DataDictionary.IGroupSpec dd, DataDictionary.DataDictionary sessionDataDictionary, DataDictionary.DataDictionary appDD) { return(SetGroup(grpNoFld, msgstr, pos, fieldMap, dd, sessionDataDictionary, appDD, null)); }
public void StringFieldTest_NonAscii() { // technically, non-ascii shouldn't be in a StringField, but sometimes it happens, so let's not freak out. StringField obj = new StringField(359, "olé!"); Assert.AreEqual(839, obj.getTotal()); // sum of all bytes in "359=olé!"+nul Assert.AreEqual(10, obj.getLength()); // 7 single-byte chars + 1 double=byte char + nul = 10 bytes }
/// <summary> /// Constructs a group and stores it in this Message object /// </summary> /// <param name="grpNoFld">the group's counter field</param> /// <param name="msgstr">full message string</param> /// <param name="pos">starting character position of group</param> /// <param name="fieldMap">full message as FieldMap</param> /// <param name="dd">group definition structure from dd</param> /// <param name="sessionDataDictionary"></param> /// <param name="appDD"></param> /// <param name="msgFactory">if null, then this method will use the generic Group class constructor</param> /// <returns></returns> protected int SetGroup( StringField grpNoFld, string msgstr, int pos, FieldMap fieldMap, DataDictionary.IGroupSpec dd, DataDictionary.DataDictionary sessionDataDictionary, DataDictionary.DataDictionary appDD, IMessageFactory msgFactory) { int grpEntryDelimiterTag = dd.Delim; int grpPos = pos; Group grp = null; // the group entry being constructed while (pos < msgstr.Length) { grpPos = pos; StringField f = ExtractField(msgstr, ref pos, sessionDataDictionary, appDD); if (f.Tag == grpEntryDelimiterTag) { // This is the start of a group entry. if (grp != null) { // We were already building an entry, so the delimiter means it's done. fieldMap.AddGroup(grp, false); grp = null; // prepare for new Group } // Create a new group! if (msgFactory != null) { grp = msgFactory.Create(Message.ExtractBeginString(msgstr), Message.GetMsgType(msgstr), grpNoFld.Tag); } //If above failed (shouldn't ever happen), just use a generic Group. if (grp == null) { grp = new Group(grpNoFld.Tag, grpEntryDelimiterTag); } } else if (!dd.IsField(f.Tag)) { // This field is not in the group, thus the repeating group is done. if (grp != null) { fieldMap.AddGroup(grp, false); } return(grpPos); } if (grp == null) { // This means we got into the group's fields without finding a delimiter tag. throw new GroupDelimiterTagException(grpNoFld.Tag, grpEntryDelimiterTag); } // f is just a field in our group entry. Add it and iterate again. grp.SetField(f); if (dd.IsGroup(f.Tag)) { // f is a counter for a nested group. Recurse! pos = SetGroup(f, msgstr, pos, grp, dd.GetGroupSpec(f.Tag), sessionDataDictionary, appDD, msgFactory); } } return(grpPos); }
public RowFields() { Overriden = new StringField(this, "ManualName", "ManualCaption", 999, FieldFlags.Default) { Expression = "T0.ManualExpression" }; }
static int Main(string[] args) { if (args.Length < 1) { Console.WriteLine("usage reply_open_resp.exe mw-id=<middleware ID>"); return(-1); } //o Load the command-line input into a GMSEC Config object // A Config object is basically a key-value pair map which is used to // pass configuration options into objects such as Connections, // ConnectionManagers, Subscribe and Publish function calls, Messages, // etc. Config config = new Config(args); // If it was not specified in the command-line arguments, set LOGLEVEL // to 'INFO' and LOGFILE to 'stdout' to allow the program report output // on the terminal/command line InitializeLogging(config); //o Ensure that the open-response is enabled config.AddValue("GMSEC-REQ-RESP", "OPEN-RESP"); //o Output GMSEC API version // TODO: Once available, replace this statement with usage of // ConnectionManager::getAPIVersion (See RTC 4798) Log.Info(Connection.GetAPIVersion()); try { //o Create the Connection ConnectionManager connMgr = new ConnectionManager(config); //o Open the connection to the middleware Log.Info("Opening the connection to the middleware server"); connMgr.Initialize(); //o Output middleware client/wrapper version Log.Info(connMgr.GetLibraryVersion()); connMgr.Subscribe(OPEN_RESP_REQUEST_SUBJECT); //o Call receive() to synchronously retrieve a message that has // been received by the middleware client libraries // Timeout periods: // -1 - Wait forever // 0 - Return immediately // >0 - Time in milliseconds before timing out Message requestMsg = connMgr.Receive(-1); // Example error handling for calling receive() with a timeout if (requestMsg != null) { //o Display the XML representation of the received message Log.Info("Received a message\n" + requestMsg.ToXML()); //o Double-check the Message type to ensure that it is a request if (requestMsg.GetKind() == Message.MessageKind.REQUEST) { //o Get the name of the component who issued the request String component = ""; //o Construct a Reply message try { StringField compField = requestMsg.GetStringField("COMPONENT"); component = compField.GetValue(); } catch (Exception e) { Log.Warning(e.ToString()); } //o Set Status Code to indicate Successful Completion. // The GMSEC Interface Specification Document defines 6 // unique STATUS-CODE values: // 1 - Acknowledgement // 2 - Working/keep alive // 3 - Successful completion // 4 - Failed completion // 5 - Invalid request // 6 - Final message // If an asynchronous requestor is awaiting a reply, the // ReplyCallback in use will remain active for multiple // messages, so long as the messages it receives contain // a STATUS-CODE of either 1 or 2. String status_code = "3"; //o Set the reply subject. // See API Interface Specificaiton Document for // more information on Reply Message subjects. // Generally speaking, they are composed // accordingly: // [Spec].[Mission].[Satellite ID]. // [Message Type].[Component Name].[Status Code] String reply_subject = OPEN_RESP_REPLY_SUBJECT + "." + status_code; //o Create reply message using (Message replyMsg = new Message(reply_subject, Message.MessageKind.REPLY)) { //o Add fields to the reply message replyMsg.AddField(new StringField("ANSWER", "Yup, I'm here!")); replyMsg.AddField(new StringField("COMPONENT", component)); //o Display XML representation of the reply message Log.Info("Prepared Reply:\n" + replyMsg.ToXML()); //o Send Reply connMgr.Reply(requestMsg, replyMsg); } //o Wait for a moment to ensure that the reply is sent out for (int i = 0; i < 10; i++) { Thread.Sleep(100); } } //o Destroy request message to release its memory connMgr.Release(ref requestMsg); } } catch (Exception e) { Log.Error(e.ToString()); return(-1); } return(0); }
protected int SetGroup(StringField grpNoFld, string msgstr, int pos, FieldMap fieldMap, DataDictionary.IGroupSpec dd, DataDictionary.DataDictionary sessionDataDictionary, DataDictionary.DataDictionary appDD) { int delim = dd.Delim; int grpPos = pos; Group grp = null; while (pos < msgstr.Length) { grpPos = pos; StringField f = ExtractField(msgstr, ref pos, sessionDataDictionary, appDD); if (f.Tag == delim) { if (grp != null) { fieldMap.AddGroup(grp, false); } grp = new Group(grpNoFld.Tag, delim); } else if (!dd.IsField(f.Tag)) { if (grp != null) { fieldMap.AddGroup(grp, false); } return grpPos; } grp.SetField(f); if(dd.IsGroup(f.Tag)) { pos = SetGroup(f, msgstr, pos, grp, dd.GetGroupSpec(f.Tag), sessionDataDictionary, appDD); } } return grpPos; }
/// <summary> /// Creates a field for a DataMember /// </summary> public FormField AddField(MemberInfo member) { //if there's no values defined, exit if (member == null) { throw new ArgumentNullException(nameof(member)); } //field FormField field; Type returnType = MemberExpression.GetReturnType(member); //String if (returnType.Equals(typeof(string))) { field = new StringField(); //set max lenght, if defined int maxLenght = (int)StringLengthValidator.GetMaxLength(member); if (maxLenght == 0) { field.TableWide = true; } else { ((StringField)field).MaxLenght = maxLenght; } //set regular expression validation, if defined var regex = member.CustomAttributes.Where(att => att.AttributeType.Equals(typeof(RegexValidator))).SingleOrDefault(); if (regex != null) { ((StringField)field).RegularExpression = (string)regex.ConstructorArguments[0].Value; } } //DataType else if (returnType.Equals(typeof(DataType))) { field = new DataTypeField(); } //otherwise delegate to the static method to create the field from the return type else { field = CreateField(returnType); } field.Name = member.Name; field.Container = this; field.Required = RequiredValidator.IsRequired(member); field.CaptionControl.Text = Translator.Translate(member); //if (member.Column.IsPrimaryKey) field.SortOrder = 0; //add to fields collection Fields.Add(field); return(field); }
public virtual void DeleteQuest(StringField questID) { DeleteQuest(FindQuest(questID)); }
static private int HB_PUBLISH_RATE = 5; // in seconds static int Main(string[] args) { if (args.Length < 1) { Console.WriteLine("usage heartbeat_service.exe mw-id=<middleware ID>"); return(-1); } Config config = new Config(args); InitializeLogging(config); Log.Info("API version: " + ConnectionManager.GetAPIVersion()); try { ConnectionManager connManager = new ConnectionManager(config); Log.Info("Opening the connection to the middleware server"); connManager.Initialize(); Log.Info("Middleware version: " + connManager.GetLibraryVersion()); //o Create all of the GMSEC Message header Fields which will // be used by all GMSEC Messages FieldList headerFields = new FieldList(); uint version = connManager.GetSpecification().GetVersion(); StringField missionField = new StringField("MISSION-ID", "MY-MISSION"); StringField facilityField = new StringField("FACILITY", "MY-FACILITY"); StringField componentField = new StringField("COMPONENT", "HEARTBEAT-SERVICE"); StringField domain1Field = new StringField("DOMAIN1", "MY-DOMAIN-1"); StringField domain2Field = new StringField("DOMAIN2", "MY-DOMAIN-2"); StringField msgID = new StringField("MSG-ID", "MY-MSG-ID"); headerFields.Add(missionField); headerFields.Add(facilityField); headerFields.Add(componentField); if (version == 201400) { headerFields.Add(msgID); } else if (version >= 201800) { headerFields.Add(domain1Field); headerFields.Add(domain2Field); } //o Use setStandardFields to define a set of header fields for // all messages which are created or published on the // ConnectionManager using the following functions: // createLogMessage, publishLog, createHeartbeatMessage, // startHeartbeatService, createResourceMessage, // publishResourceMessage, or startResourceMessageService connManager.SetStandardFields(headerFields); // Note: Fields are immutable, so plan appropriately if you wish // to re-use variable names! { //o Create all of the GMSEC Message header Fields which // will be used by all GMSEC HB Messages FieldList hbStandardFields = new FieldList(); //o Determine which version of the GMSEC message specification // the ConnectionManager was initialized with and add // the correctly typed Fields to the Message if (version >= 201600) { hbStandardFields.Add(new U16Field("PUB-RATE", (UInt16)HB_PUBLISH_RATE)); hbStandardFields.Add(new U16Field("COUNTER", (UInt16)1)); } else if (version == 201400) { hbStandardFields.Add(new I16Field("PUB-RATE", (short)HB_PUBLISH_RATE)); hbStandardFields.Add(new I16Field("COUNTER", (short)1)); } //o Note: COMPONENT-STATUS is an optional field used to // denote the operating status of the component, the // values are as follows: // 0 - Debug // 1 - Normal / Green // 2 - Warning / Yellow // 3 - Orange // 4 - Error / Red I16Field componentStatusField = new I16Field("COMPONENT-STATUS", (short)0); hbStandardFields.Add(componentStatusField); //o Create and publish a Heartbeat message using // createLogMessage() and publish() // // Note: This is useful for applications which may need // to create proxy heartbeats on behalf of a subsystem, // as creating multiple ConnectionManagers can consume // more memory than necessary. In this case, extra // logic would need to be added to handle the timing of // the publications. Message hbMsg = connManager.CreateHeartbeatMessage(HB_MESSAGE_SUBJECT, hbStandardFields); Log.Info("Publishing the GMSEC C2CX HB message which was just created using createHeartbeatMessage():\n" + hbMsg.ToXML()); connManager.Publish(hbMsg); //o Kick off the Heartbeat Service -- This will publish // heartbeat messages automatically every X seconds, // where Xis the value which was provided for PUB-RATE // Note: If PUB-RATE was not provided, it will default // to 30 seconds per automatic Heartbeat publication Log.Info("Starting the Heartbeat service, a message will be published every " + hbStandardFields[0].GetStringValue() + " seconds"); connManager.StartHeartbeatService(HB_MESSAGE_SUBJECT, hbStandardFields); } { //o Use setHeartbeatServiceField to change the state of the // COMPONENT-STATUS Field to indicate that the component has // transitioned from a startup/debug state to a running/green // state. I16Field componentStatusField = new I16Field("COMPONENT-STATUS", (short)1); connManager.SetHeartbeatServiceField(componentStatusField); } //o Wait for user input to end the program Log.Info("Publishing C2CX Heartbeat Messages indefinitely, press <enter> to exit the program"); Console.ReadLine(); //o Stop the Heartbeat Service connManager.StopHeartbeatService(); connManager.Cleanup(); } catch (GmsecException e) { Log.Error(e.ToString()); return(-1); } return(0); }
public bool ActivateFor(Row row) { if (ReferenceEquals(null, Target)) { return(false); } attr = Target.GetAttribute <ImageUploadEditorAttribute>(); if (attr == null || attr.DisableDefaultBehavior || attr.EditorType != "ImageUpload") { return(false); } if (!(Target is StringField)) { throw new ArgumentException(String.Format( "Field '{0}' on row type '{1}' has a UploadEditor attribute but it is not a String field!", Target.PropertyName ?? Target.Name, row.GetType().FullName)); } if (!(row is IIdRow)) { throw new ArgumentException(String.Format( "Field '{0}' on row type '{1}' has a UploadEditor attribute but Row type doesn't implement IIdRow!", Target.PropertyName ?? Target.Name, row.GetType().FullName)); } if (!attr.OriginalNameProperty.IsEmptyOrNull()) { var originalNameField = row.FindFieldByPropertyName(attr.OriginalNameProperty) ?? row.FindField(attr.OriginalNameProperty); if (ReferenceEquals(null, originalNameField)) { throw new ArgumentException(String.Format( "Field '{0}' on row type '{1}' has a UploadEditor attribute but " + "a field with OriginalNameProperty '{2} is not found!'", Target.PropertyName ?? Target.Name, row.GetType().FullName, attr.OriginalNameProperty)); } this.originalNameField = (StringField)originalNameField; } var format = attr.FilenameFormat; if (format == null) { format = row.GetType().Name; if (format.EndsWith("Row")) { format = format.Substring(0, format.Length - 3); } format += "/~"; } this.fileNameFormat = format.Replace("~", SplittedFormat); this.uploadHelper = new UploadHelper((attr.SubFolder.IsEmptyOrNull() ? "" : (attr.SubFolder + "/")) + (this.fileNameFormat)); return(true); }
/// <summary> /// Adds the plan's steps. /// </summary> /// <param name="questBuilder">QuestBuilder.</param> /// <param name="domainName">Main target's domain.</param> /// <param name="goal">Goal step.</param> /// <param name="plan">List of steps that end with goal step.</param> /// <returns>The last node added.</returns> protected virtual QuestNode AddSteps(QuestBuilder questBuilder, string domainName, PlanStep goal, Plan plan) { var previousNode = questBuilder.GetStartNode(); var counterNames = new HashSet <string>(); for (int i = 0; i < plan.steps.Count; i++) { var step = plan.steps[i]; // Create next condition node: var targetEntity = step.fact.entityType.name; var targetDescriptor = step.fact.entityType.GetDescriptor(step.requiredCounterValue); var id = (i + 1).ToString(); var internalName = step.action.displayName + " " + targetDescriptor; var conditionNode = questBuilder.AddConditionNode(previousNode, id, internalName, ConditionCountMode.All); previousNode = conditionNode; // Variables for node text tag replacement: var counterName = string.Empty; int requiredCounterValue = 0; var completion = step.action.completion; if (completion.mode == ActionCompletion.Mode.Counter) { // Setup counter condition: counterName = goal.fact.entityType.pluralDisplayName.value + completion.baseCounterName.value; if (!counterNames.Contains(counterName)) { var counter = questBuilder.AddCounter(counterName, completion.initialValue, completion.minValue, completion.maxValue, false, completion.updateMode); foreach (var messageEvent in completion.messageEventList) { var counterMessageEvent = new QuestCounterMessageEvent(messageEvent.targetID, messageEvent.message, new StringField(StringField.GetStringValue(messageEvent.parameter).Replace("{TARGETENTITY}", targetEntity)), messageEvent.operation, messageEvent.literalValue); counter.messageEventList.Add(counterMessageEvent); } } counterName = goal.fact.entityType.pluralDisplayName.value + completion.baseCounterName.value; requiredCounterValue = Mathf.Min(step.requiredCounterValue, step.fact.count); questBuilder.AddCounterCondition(conditionNode, counterName, CounterValueConditionMode.AtLeast, requiredCounterValue); // Consider: Add action to reset counter to zero in case future nodes repeat the same counter? } else { // Setup message condition: questBuilder.AddMessageCondition(conditionNode, QuestMessageParticipant.Any, completion.senderID, QuestMessageParticipant.Any, completion.targetID, completion.message, new StringField(StringField.GetStringValue(completion.parameter).Replace("{TARGETENTITY}", targetEntity))); } var activeState = conditionNode.stateInfoList[(int)QuestNodeState.Active]; AddStepNodeText(questBuilder, conditionNode, activeState, targetEntity, targetDescriptor, domainName, counterName, requiredCounterValue, step); // Actions when active: if (!StringField.IsNullOrEmpty(step.action.actionText.activeText.alertText)) { // Alert action: var alertAction = questBuilder.CreateAlertAction(ReplaceStepTags(step.action.actionText.activeText.alertText.value, targetEntity, targetDescriptor, domainName, counterName, requiredCounterValue)); activeState.actionList.Add(alertAction); } // Send message action: if (!StringField.IsNullOrEmpty(step.action.sendMessageOnActive)) { var messageAction = questBuilder.CreateMessageAction(ReplaceStepTags(step.action.sendMessageOnActive.value, targetEntity, targetDescriptor, domainName, counterName, requiredCounterValue)); activeState.actionList.Add(messageAction); } // Actions when completed: if (!StringField.IsNullOrEmpty(step.action.sendMessageOnCompletion)) { var trueState = conditionNode.stateInfoList[(int)QuestNodeState.True]; var messageAction = questBuilder.CreateMessageAction(ReplaceStepTags(step.action.sendMessageOnCompletion.value, targetEntity, targetDescriptor, domainName, counterName, requiredCounterValue)); trueState.actionList.Add(messageAction); } } return(previousNode); }
static int Main(string[] args) { if (args.Length < 1) { Console.WriteLine("usage log_message.exe mw-id=<middleware ID>"); return(-1); } Config config = new Config(args); InitializeLogging(config); //o Set the GMSEC message specification version to be used to determine // what the structure of messages is for verification and the // construction of MistMessages config.AddValue("GMSEC-SPECIFICATION-VERSION", GMSEC_SPEC_VERSION); Log.Info(ConnectionManager.GetAPIVersion()); try { ConnectionManager connManager = new ConnectionManager(config); Log.Info("Opening the connection to the middleware server"); connManager.Initialize(); Log.Info(connManager.GetLibraryVersion()); //o Begin the steps necessary to create a GMSEC-compliant LOG // message using the ConnectionManager //o Create all of the GMSEC Message header Fields which will // be used by all GMSEC Messages // // Note: Since these Fields contain variable values which are // based on the context in which they are used, they cannot be // automatically populated using MistMessage. List <Field> definedFields = new List <Field>(); StringField missionField = new StringField("MISSION-ID", "MISSION"); // Note: SAT-ID-PHYSICAL is an optional header Field, according // to the GMSEC ISD. StringField satIdField = new StringField("SAT-ID-PHYSICAL", "SPACECRAFT"); StringField facilityField = new StringField("FACILITY", "GMSEC Lab"); StringField componentField = new StringField("COMPONENT", "device_message"); definedFields.Add(missionField); definedFields.Add(satIdField); definedFields.Add(facilityField); definedFields.Add(componentField); //o Use setStandardFields to define a set of header fields for // all messages which are created or published on the // ConnectionManager using the following functions: // createLogMessage, publishLog, createHeartbeatMessage, // startHeartbeatService, createResourceMessage, // publishResourceMessage, or startResourceMessageService connManager.SetStandardFields(definedFields); //o Determine which version of the GMSEC message specification // the ConnectionManager was initialized with uint version = connManager.GetSpecification().GetVersion(); String gmsecSpecVersion = ""; if (version == 201600) { gmsecSpecVersion = "2016.00"; } else if (version == 201400) { gmsecSpecVersion = "2014.00"; } String msgId = gmsecSpecVersion + ".GMSEC.MSG.LOG"; //o Use MistMessage to construct a GMSEC LOG message based off // of the latest XML templates provided with the GMSEC API. // This will automatically populate the Message with all of the // Fields which have specific values defined for them in the XML // template files. For more information on which Fields have // values defined for them, please review the XML template files // located in GMSEC_API/templates. // // Note: The second parameter is an identifier for the type of // GMSEC-compliant message to construct. This parameter varies // depending on the version of the GMSEC ISD that the messages // are based off of. This example shows how to handle a varying // case. using (MistMessage logMsg = new MistMessage(LOG_MESSAGE_SUBJECT, msgId, connManager.GetSpecification())) { //o Add the LOG-specific fields to the LOG message // // Note: Since these Fields contain variable values which are // based on the context in which they are used, they cannot be // automatically populated using MistMessage. String eventTime = TimeUtil.FormatTime(TimeUtil.GetCurrentTime()); logMsg.AddField(new I16Field("SEVERITY", (short)1)); logMsg.SetValue("MSG-TEXT", "Creating an example GMSEC LOG Message"); logMsg.SetValue("OCCURRENCE-TYPE", "SYS"); logMsg.SetValue("SUBCLASS", "AST"); logMsg.SetValue("EVENT-TIME", eventTime); //o Add the standard fields to the LOG message connManager.AddStandardFields(logMsg); connManager.Publish(logMsg); Log.Info("Published LOG message:\n" + logMsg.ToXML()); } connManager.Cleanup(); } catch (GMSEC_Exception e) { Log.Error(e.ToString()); return(-1); } return(0); }
/// <summary> /// Sets the quest's main info . /// </summary> /// <param name="questBuilder">QuestBuilder</param> /// <param name="questID">Quest ID.</param> /// <param name="title">Quest title.</param> /// <param name="group">Quest group.</param> /// <param name="goal">Final step to accomplish the plan.</param> protected virtual void SetMainInfo(QuestBuilder questBuilder, string questID, string title, StringField group, PlanStep goal) { questBuilder.quest.isTrackable = true; questBuilder.quest.showInTrackHUD = true; questBuilder.quest.icon = goal.fact.entityType.image; questBuilder.quest.group = new StringField(group); questBuilder.quest.goalEntityTypeName = goal.fact.entityType.name; }
private void AddFixFieldInfo(StringField f, DataDictionary.DataDictionary dic) { FixFieldInfo fi = new FixFieldInfo(); fi.Tag = f.Tag; DataDictionary.DDField field = null; if (dic != null && dic.FieldsByTag != null && dic.FieldsByTag.TryGetValue(f.Tag, out field)) { fi.Name = field.Name; } fi.Value = f.getValue(); fi.EnumValue = GetEnumValueFromField(f, field); _descriptor.Fields.Add(fi); }
public IEdmTypeReference Visit(StringField field) { return(CreatePrimitive(EdmPrimitiveTypeKind.String, field)); }
/// <summary> /// Constructs a group and stores it in this Message object /// </summary> /// <param name="grpNoFld"></param> /// <param name="msgstr"></param> /// <param name="pos"></param> /// <param name="fieldMap"></param> /// <param name="dd"></param> /// <param name="sessionDataDictionary"></param> /// <param name="appDD"></param> /// <param name="msgFactory">if this is null, then this method will use the generic Group class constructor</param> /// <returns></returns> protected int SetGroup(StringField grpNoFld, string msgstr, int pos, FieldMap fieldMap, DataDictionary.IGroupSpec dd, DataDictionary.DataDictionary sessionDataDictionary, DataDictionary.DataDictionary appDD, IMessageFactory msgFactory) { int delim = dd.Delim; int grpPos = pos; Group grp = null; while (pos < msgstr.Length) { grpPos = pos; StringField f = ExtractField(msgstr, ref pos, sessionDataDictionary, appDD); if (f.Tag == delim) { if (grp != null) { fieldMap.AddGroup(grp, false); } if (msgFactory != null) grp = msgFactory.Create(Message.ExtractBeginString(msgstr), Message.GetMsgType(msgstr), grpNoFld.Tag); //If above failed, just use a generic Group. if (grp == null) grp = new Group(grpNoFld.Tag, delim); } else if (!dd.IsField(f.Tag)) { if (grp != null) { fieldMap.AddGroup(grp, false); } return grpPos; } grp.SetField(f); if (dd.IsGroup(f.Tag)) { if (FixMessageDescriptorEnabled) { var oldCurrField = _currentGroupField; _currentGroupField = new GroupFixFieldInfo(); _currentGroupField.Tag = f.Tag; DataDictionary.DDField field = null; if (appDD != null && appDD.FieldsByTag.TryGetValue(f.Tag, out field)) { _currentGroupField.Name = field.Name; } else if (sessionDataDictionary != null && sessionDataDictionary.FieldsByTag.TryGetValue(f.Tag, out field)) { _currentGroupField.Name = field.Name; } _currentGroupField.Value = f.getValue(); _currentGroupField.EnumValue = GetEnumValueFromField(f, field); oldCurrField.Fields.Add(_currentGroupField); } pos = SetGroup(f, msgstr, pos, grp, dd.GetGroupSpec(f.Tag), sessionDataDictionary, appDD, msgFactory); } else { if (FixMessageDescriptorEnabled) { FixFieldInfo fi = new FixFieldInfo(); fi.Tag = f.Tag; DataDictionary.DDField field = null; if (appDD != null && appDD.FieldsByTag.TryGetValue(f.Tag, out field)) { _currentGroupField.Name = field.Name; } else if (sessionDataDictionary != null && sessionDataDictionary.FieldsByTag.TryGetValue(f.Tag, out field)) { _currentGroupField.Name = field.Name; } fi.Value = f.getValue(); fi.EnumValue = GetEnumValueFromField(f, field); _currentGroupField.Fields.Add(fi); } } } return grpPos; }
public void StringFieldTest_TotalAndLength() { /// <remarks> /// from quickfix/j FieldTest.java /// </remarks> StringField obj = new StringField(12, "VALUE"); Assert.That(obj.toStringField(), Is.EqualTo("12=VALUE")); Assert.That(obj.getTotal(), Is.EqualTo(542)); Assert.That(obj.getLength(), Is.EqualTo(9)); obj.Obj = "VALUF"; // F = E+1 Assert.That(obj.toStringField(), Is.EqualTo("12=VALUF")); Assert.That(obj.getTotal(), Is.EqualTo(543)); Assert.That(obj.getLength(), Is.EqualTo(9)); obj.Tag = 13; // 13 = 12+1 Assert.That(obj.toStringField(), Is.EqualTo("13=VALUF")); Assert.That(obj.getTotal(), Is.EqualTo(544)); Assert.That(obj.getLength(), Is.EqualTo(9)); }
public override string GetEditorName() { return(StringField.IsNullOrEmpty(m_message) ? "Message" : ("Message: " + m_message.value + " " + StringField.GetStringValue(m_parameter) + " " + m_value.EditorNameValue())); }
protected override void ConstructFields() { TableName = "TBL_TESTPERSON"; StoreFlag = StoreFlag.LoadAndStore; m_fldName = new StringField() { Owner = this, FieldName = "PERSON_NAME", Required = true, Size = 50 }; m_fldSex = new StringField() { Owner = this, FieldName = "SEX", Required = true, Size = 1, DataEntryType = DataEntryType.DirectEntryOrLookupWithValidation, LookupType = LookupType.Dictionary }; m_fldSex.LookupDictionary.AddRange(new string[] { "M,Male", "F,Female", "U,Unspecified" }); m_fldRating = new IntField() { Owner = this, FieldName = "RATING", MinMaxChecking = true, MinValue = 0, MaxValue = 10 }; m_fldRegistered = new BoolField() { Owner = this, FieldName = "IS_REGISTERED", Required = true }; m_fldDOB = new DateTimeField() { Owner = this, FieldName = "DOB" }; m_fldSalary = new DecimalField() { Owner = this, FieldName = "PAYROLL_VOLUME", MinMaxChecking = true, MinValue = 0M, MaxValue = Decimal.MaxValue }; //calculated field returns salary * 10 years m_fldDecadeSalary = new DecimalField() { Owner = this, FieldName = "DECADE_SALARY", StoreFlag = StoreFlag.None, DataEntryType = DataEntryType.None, Calculated = true, Formula = "850-10 +(::PAYROLL_VOLUME * 10)" }; m_fldScore = new DoubleField() { Owner = this, FieldName = "SCORE" }; m_fldMovieNames = new ListField <string>() { Owner = this, FieldName = "MOVIES", Required = true }; //ths is business logic-driven computed column for GUI m_fldBusinessCode = new StringField() { Owner = this, FieldName = "BUSINESS_CODE", StoreFlag = StoreFlag.None, DataEntryType = DataEntryType.None }; }
protected override void ConstructFields() { TableName = "TBL_TESTPERSON"; StoreFlag = StoreFlag.LoadAndStore; m_fldName = new StringField() { Owner = this, FieldName = "PERSON_NAME", Required = true, Size = 50 }; m_fldSex = new StringField() { Owner = this, FieldName = "SEX", Required = true, Size = 1, DataEntryType = DataEntryType.DirectEntryOrLookupWithValidation, LookupType = LookupType.Dictionary }; m_fldSex.LookupDictionary.AddRange(new string[]{"M,Male", "F,Female", "U,Unspecified"}); m_fldRating = new IntField() { Owner = this, FieldName = "RATING", MinMaxChecking = true, MinValue = 0, MaxValue = 10 }; m_fldRegistered = new BoolField() { Owner = this, FieldName = "IS_REGISTERED", Required = true }; m_fldDOB = new DateTimeField() { Owner = this, FieldName = "DOB" }; m_fldSalary = new DecimalField() { Owner = this, FieldName = "PAYROLL_VOLUME", MinMaxChecking = true, MinValue = 0M, MaxValue = Decimal.MaxValue }; //calculated field returns salary * 10 years m_fldDecadeSalary = new DecimalField() { Owner = this, FieldName = "DECADE_SALARY", StoreFlag = StoreFlag.None, DataEntryType = DataEntryType.None, Calculated = true, Formula = "850-10 +(::PAYROLL_VOLUME * 10)" }; m_fldScore = new DoubleField() { Owner = this, FieldName = "SCORE" }; m_fldMovieNames = new ListField<string>() { Owner = this, FieldName = "MOVIES", Required = true }; //ths is business logic-driven computed column for GUI m_fldBusinessCode = new StringField() { Owner = this, FieldName = "BUSINESS_CODE", StoreFlag = StoreFlag.None, DataEntryType = DataEntryType.None }; }
public void Format() { FormatterContext formatterContext = new FormatterContext( FormatterContext.DefaultBufferSize); StringField field = new StringField(1, "DATA"); StringFieldFormatter formatter; string formattedData; // Test fixed length formatting. formatter = new StringFieldFormatter(37, new FixedLengthManager(12), StringEncoder.GetInstance()); formatter.Format(field, ref formatterContext); formattedData = formatterContext.GetDataAsString(); Assert.IsTrue(formattedData.Equals("DATA ")); // Test variable length formatting without padding. formatterContext.Clear(); formatter = new StringFieldFormatter(48, new VariableLengthManager(0, 999, StringLengthEncoder.GetInstance(999)), StringEncoder.GetInstance()); formatter.Format(field, ref formatterContext); formattedData = formatterContext.GetDataAsString(); Assert.IsTrue(formattedData.Equals("004DATA")); formatterContext.Clear(); formatter.Format(new StringField(5, null), ref formatterContext); formattedData = formatterContext.GetDataAsString(); Assert.IsTrue(formattedData.Equals("000")); // Test variable length formatting with padding. formatterContext.Clear(); formatter = new StringFieldFormatter(48, new VariableLengthManager(10, 10, StringLengthEncoder.GetInstance(10)), StringEncoder.GetInstance(), SpacePaddingLeft.GetInstance(false), string.Empty); formatter.Format(field, ref formatterContext); formattedData = formatterContext.GetDataAsString(); Assert.IsTrue(formattedData.Equals("10 DATA")); // Test validator with fixed length formatting. formatterContext.Clear(); formatter = new StringFieldFormatter(37, new FixedLengthManager(12), StringEncoder.GetInstance(), NumericValidator.GetInstance(), string.Empty); field.FieldValue = "000000001500"; formatter.Format(field, ref formatterContext); formattedData = formatterContext.GetDataAsString(); Assert.IsTrue(formattedData.Equals("000000001500")); // Try with an invalid value. formatterContext.Clear(); field.FieldValue = "D1500"; try { formatter.Format(field, ref formatterContext); Assert.Fail(); } catch (StringValidationException) { } // Test validator with fixed length formatting and numeric padding. formatterContext.Clear(); formatter = new StringFieldFormatter(37, new FixedLengthManager(12), StringEncoder.GetInstance(), ZeroPaddingLeft.GetInstance(false, true), NumericValidator.GetInstance()); field.FieldValue = "56600"; formatter.Format(field, ref formatterContext); formattedData = formatterContext.GetDataAsString(); Assert.IsTrue(formattedData.Equals("000000056600")); // Try with an invalid value. formatterContext.Clear(); field.FieldValue = "D1500"; try { formatter.Format(field, ref formatterContext); Assert.Fail(); } catch (StringValidationException) { } }
static int Main(string[] args) { if (args.Length < 1) { Console.WriteLine("usage validation_addendum.exe mw-id=<middleware ID>"); return(-1); } Config config = new Config(args); InitializeLogging(config); //o Enable Message validation. This parameter is "false" by default. config.AddValue("GMSEC-MSG-CONTENT-VALIDATE", "true"); //o Tell the API that there is an additional layer of message schema to // validate (The 'EXAMPLE' message definitions). This value is set to // 0 (Only 'GMSEC' specification validation) by default. // // Note: These levels for validation are determined by the "LEVEL-X" // attributes defined in the .DIRECTORY.xml file contained in the XML // templates directory. In thise case, Level-0 means GMSEC and Level-1 // means EXAMPLE. // // Note: The GMSEC team envisions using message specifications in a // layered hierarchical fashion. For example, the "GMSEC" message // specification would be 'layer 0', followed by an organization-level // message specification at 'layer 1' which builds upon the message // specification outlined in the GMSEC ISD. This would be followed by // a mission-level message specification at 'layer 2' and so on. config.AddValue("GMSEC-SCHEMA-LEVEL", "1"); //o Tell the API where to find all of the schema files. // // Note: This example only demonstrates a simple usage case of this // functionality. When using this functionality, if the intent is // to use any of the GMSEC message definitions, then ALL of the XML // template files must be contained in the same directory. // e.g. GMSEC_API/templates/2016.00 (Or the location defined in // GMSEC-SCHEMA-PATH) config.AddValue("GMSEC-SCHEMA-PATH", "templates"); //o Since this example relies on the 2016.00 version of the templates, // we indicate such within the configuration object. config.AddValue("GMSEC-SPECIFICATION-VERSION", "201600"); Log.Info("API version: " + ConnectionManager.GetAPIVersion()); try { ConnectionManager connMgr = new ConnectionManager(config); Log.Info("Opening the connection to the middleware server"); connMgr.Initialize(); Log.Info("Middleware version: " + connMgr.GetLibraryVersion()); FieldList definedFields = new FieldList(); StringField missionField = new StringField("MISSION-ID", "MY-MISSION"); StringField satIdField = new StringField("SAT-ID-PHYSICAL", "MY-SPACECRAFT"); StringField facilityField = new StringField("FACILITY", "MY-FACILITY"); StringField componentField = new StringField("COMPONENT", "MY-COMPONENT-NAME"); definedFields.Add(missionField); definedFields.Add(satIdField); definedFields.Add(facilityField); definedFields.Add(componentField); connMgr.SetStandardFields(definedFields); //o Create a Message using a subject defined in the XML template // outlining our example addendum message definitions using (MistMessage message = new MistMessage(EXAMPLE_MESSAGE_SUBJECT, "MSG.LOG", connMgr.GetSpecification())) { //o Add remaining required Fields to our message message.AddField(new U16Field("NUM-OF-EVENTS", (UInt16)2)); message.SetValue("EVENT.1", AddTimeToString("AOS occurred at: ")); message.SetValue("EVENT.2", AddTimeToString("Telemetry downlink began at: ")); connMgr.AddStandardFields(message); //o Publish the message to the middleware bus connMgr.Publish(message); //o Display the XML string representation of the Message for // the sake of review Log.Info("Published message:\n" + message.ToXML()); } //o Setup a new message without some of the Required Fields and // attempt to publish it (i.e. Trigger a validation failure) using (MistMessage badMessage = new MistMessage(EXAMPLE_MESSAGE_SUBJECT, "MSG.LOG", connMgr.GetSpecification())) { try { connMgr.Publish(badMessage); } catch (GmsecException e) { Log.Error("This error is expected:\n" + e.ToString()); } } //o Disconnect from the middleware and clean up the Connection connMgr.Cleanup(); } catch (GmsecException e) { Log.Error(e.ToString()); return(-1); } return(0); }
static int RSRC_PUBLISH_RATE = 5; // in seconds static int Main(string[] args) { if (args.Length < 1) { Console.WriteLine("usage resource_service.exe mw-id=<middleware ID>"); return(-1); } Config config = new Config(args); InitializeLogging(config); Log.Info("API version: " + ConnectionManager.GetAPIVersion()); try { ConnectionManager connManager = new ConnectionManager(config); Log.Info("Opening the connection to the middleware server"); connManager.Initialize(); Log.Info("Middleware version: " + connManager.GetLibraryVersion()); //o Create all of the GMSEC Message header Fields which will // be used by all GMSEC Messages FieldList headerFields = new FieldList(); uint version = connManager.GetSpecification().GetVersion(); StringField missionField = new StringField("MISSION-ID", "MY-MISSION"); StringField facilityField = new StringField("FACILITY", "MY-FACILITY"); StringField componentField = new StringField("COMPONENT", "RESOURCE-SERVICE"); StringField domain1Field = new StringField("DOMAIN1", "MY-DOMAIN-1"); StringField domain2Field = new StringField("DOMAIN2", "MY-DOMAIN-2"); StringField msgID = new StringField("MSG-ID", "MY-MSG-ID"); headerFields.Add(missionField); headerFields.Add(facilityField); headerFields.Add(componentField); if (version == 201400) { headerFields.Add(msgID); } else if (version >= 201800) { headerFields.Add(domain1Field); headerFields.Add(domain2Field); } //o Use setStandardFields to define a set of header fields for // all messages which are created or published on the // ConnectionManager using the following functions: // createLogMessage, publishLog, createHeartbeatMessage, // startHeartbeatService, createResourceMessage, // publishResourceMessage, or startResourceMessageService connManager.SetStandardFields(headerFields); //o Create and publish a Resource message using // createResourceMessage() and publish() // // Note: This is useful for applications which may need to add // additional Fields to the Resource Messages which are not // currently added by the GMSEC API Message rsrcMsg = connManager.CreateResourceMessage(RSRC_MESSAGE_SUBJECT, 1, 10); Log.Info("Publishing the GMSEC C2CX RSRC message which was created using createResourceMessage():\n" + rsrcMsg.ToXML()); connManager.Publish(rsrcMsg); //o Kick off the Resource Service -- This will publish resource // messages automatically every X seconds, where X is the second // parameter provided to the startResourceMessageService() function. // If an interval is not provided, the service will default to // publishing a message every 60 seconds. Log.Info("Starting the Resource Message service, a message will be published every " + RSRC_PUBLISH_RATE + " seconds"); connManager.StartResourceMessageService(RSRC_MESSAGE_SUBJECT, RSRC_PUBLISH_RATE, 1, 10); //o Wait for user input to end the program Log.Info("Publishing C2CX Resource Messages indefinitely, press <enter> to exit the program"); Console.ReadLine(); //o Stop the Heartbeat Service connManager.StopResourceMessageService(); //o Cleanup connManager.Cleanup(); } catch (Exception e) { Log.Error(e.ToString()); return(-1); } return(0); }
public RowFields() : base("InvalidColumn") { Override = new StringField(this, "ManualName"); }
/// <summary> /// Constructs a group and stores it in this Message object /// </summary> /// <param name="grpNoFld"></param> /// <param name="msgstr"></param> /// <param name="pos"></param> /// <param name="fieldMap"></param> /// <param name="dd"></param> /// <param name="sessionDataDictionary"></param> /// <param name="appDD"></param> /// <param name="msgFactory">if this is null, then this method will use the generic Group class constructor</param> /// <returns></returns> protected int SetGroup(StringField grpNoFld, string msgstr, int pos, FieldMap fieldMap, DataDictionary.IGroupSpec dd, DataDictionary.DataDictionary sessionDataDictionary, DataDictionary.DataDictionary appDD, IMessageFactory msgFactory) { int delim = dd.Delim; int grpPos = pos; Group grp = null; while (pos < msgstr.Length) { grpPos = pos; StringField f = ExtractField(msgstr, ref pos, sessionDataDictionary, appDD); if (f.Tag == delim) { if (grp != null) { fieldMap.AddGroup(grp, false); } if (msgFactory != null) grp = msgFactory.Create(Message.ExtractBeginString(msgstr), Message.GetMsgType(msgstr), grpNoFld.Tag); //If above failed, just use a generic Group. if (grp == null) grp = new Group(grpNoFld.Tag, delim); } else if (!dd.IsField(f.Tag)) { if (grp != null) { fieldMap.AddGroup(grp, false); } return grpPos; } grp.SetField(f); if(dd.IsGroup(f.Tag)) { pos = SetGroup(f, msgstr, pos, grp, dd.GetGroupSpec(f.Tag), sessionDataDictionary, appDD, msgFactory); } } return grpPos; }
public void FromStringTestWithNoDataDictionary() { string str1 = "8=FIX.4.2\x01" + "9=55\x01" + "35=0\x01" + "34=3\x01" + "49=TW\x01" + "52=20000426-12:05:06\x01" + "56=ISLD\x01" + "1=acct123\x01" + "10=123\x01"; Message msg = new Message(); try { msg.FromString(str1, true, null, null, _defaultMsgFactory); } catch (InvalidMessage e) { Assert.Fail("Unexpected exception (InvalidMessage): " + e.Message); } StringField f1 = new StringField(8); StringField f2 = new StringField(9); StringField f3 = new StringField(35); StringField f4 = new StringField(34); StringField f5 = new StringField(49); StringField f6 = new StringField(52); StringField f7 = new StringField(56); StringField f8 = new StringField(10); StringField f9 = new StringField(1); msg.Header.GetField(f1); msg.Header.GetField(f2); msg.Header.GetField(f3); msg.Header.GetField(f4); msg.Header.GetField(f5); msg.Header.GetField(f6); msg.Header.GetField(f7); msg.GetField(f9); msg.Trailer.GetField(f8); Assert.That(f1.Obj, Is.EqualTo("FIX.4.2")); Assert.That(f2.Obj, Is.EqualTo("55")); Assert.That(f3.Obj, Is.EqualTo("0")); Assert.That(f4.Obj, Is.EqualTo("3")); Assert.That(f5.Obj, Is.EqualTo("TW")); Assert.That(f6.Obj, Is.EqualTo("20000426-12:05:06")); Assert.That(f7.Obj, Is.EqualTo("ISLD")); Assert.That(f8.Obj, Is.EqualTo("123")); Assert.That(f9.Obj, Is.EqualTo("acct123")); }
public static Dictionary<Int64, string> GetIdNameDictionary(IDbConnection connection, IIdRow row, StringField nameField, IEnumerable<Int64> idList) { var list = new List<Int64>(idList); var dictionary = new Dictionary<Int64, string>(); if (list.Count <= 0) return dictionary; list.Sort(); var theRow = (Row)row; Int64[] part = null; const int step = 100; var i = 0; while (i < list.Count) { var start = i; var end = start + step; if (end >= list.Count) end = list.Count - 1; var len = end - start + 1; if (part == null || len != part.Length) part = new Int64[len]; list.CopyTo(start, part, 0, len); var query = new SqlQuery().Select(((Field)row.IdField).Name).Select(nameField.Name).From(theRow.Table); query.Where(new Criteria((Field)row.IdField).In(part)); using (var reader = SqlHelper.ExecuteReader(connection, query)) while (reader.Read()) dictionary[reader.ToInt64(0).Value] = reader.AsString(1); i += step; } return dictionary; }
protected override void ConstructFields() { SupportsNotificationBinding = false; NoBuildCrosschecks = true; FieldValidationSuspended = true; TableName = "TBL_TESTPERSON"; StoreFlag = StoreFlag.LoadAndStore; m_fldName = new StringField() { Owner = this, FieldName = "PERSON_NAME", Required = true, Size = 50 }; m_fldRating = new IntField() { Owner = this, FieldName = "RATING", MinMaxChecking = true, MinValue = 0, MaxValue = 10 }; m_fldRegistered = new BoolField() { Owner = this, FieldName = "IS_REGISTERED", Required = true }; m_fldDOB = new DateTimeField() { Owner = this, FieldName = "DOB" }; m_fldScore = new DoubleField() { Owner = this, FieldName = "SCORE" }; m_fldData1 = new StringField() { Owner = this, FieldName = "Data1" }; m_fldData2 = new StringField() { Owner = this, FieldName = "Data2" }; m_fldData3 = new StringField() { Owner = this, FieldName = "Data3" }; m_fldData4 = new IntField() { Owner = this, FieldName = "Data4" }; m_fldData5 = new IntField() { Owner = this, FieldName = "Data5" }; m_fldData6 = new IntField() { Owner = this, FieldName = "Data6" }; m_fldData7 = new BoolField() { Owner = this, FieldName = "Data7" }; m_fldData8 = new BoolField() { Owner = this, FieldName = "Data8" }; m_fldData9 = new BoolField() { Owner = this, FieldName = "Data9" }; m_fldData10 = new DoubleField() { Owner = this, FieldName = "Data10" }; }
protected int SetGroup(StringField grpNoFld, string msgstr, int pos, FieldMap fieldMap, DataDictionary.IGroupSpec dd, DataDictionary.DataDictionary sessionDataDictionary, DataDictionary.DataDictionary appDD) { return SetGroup(grpNoFld, msgstr, pos, fieldMap, dd, sessionDataDictionary, appDD, null); }
private static void BuidIndex(IEnumerable<Document> hits, IndexWriter writer) { foreach (var document in hits) { var doc = new FlexLucene.Document.Document(); var idField = new StringField(Schema.StandardField.ID, document._id.ToString(), FieldStore.YES); doc.Add(idField); var fullTextField = new Field(Schema.StandardField.FULL_TEXT, document.ToLuceneFullTextString(), ExtendedTextFieldType); doc.Add(fullTextField); writer.AddDocument(doc); } writer.Commit(); }
public virtual void TestFieldSetValue() { Field field = new StringField("id", "id1", Field.Store.YES); Documents.Document doc = new Documents.Document(); doc.Add(field); doc.Add(new StringField("keyword", "test", Field.Store.YES)); Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir); writer.AddDocument(doc); field.StringValue = "id2"; writer.AddDocument(doc); field.StringValue = "id3"; writer.AddDocument(doc); IndexReader reader = writer.Reader; IndexSearcher searcher = NewSearcher(reader); Query query = new TermQuery(new Term("keyword", "test")); // ensure that queries return expected results without DateFilter first ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(3, hits.Length); int result = 0; for (int i = 0; i < 3; i++) { Documents.Document doc2 = searcher.Doc(hits[i].Doc); Field f = (Field)doc2.GetField("id"); if (f.StringValue.Equals("id1")) { result |= 1; } else if (f.StringValue.Equals("id2")) { result |= 2; } else if (f.StringValue.Equals("id3")) { result |= 4; } else { Assert.Fail("unexpected id field"); } } writer.Dispose(); reader.Dispose(); dir.Dispose(); Assert.AreEqual(7, result, "did not see all IDs"); }
static int Main(string[] args) { if (args.Length < 1) { Console.WriteLine("usage mnemonic_message.exe mw-id=<middleware ID>"); return(-1); } Config config = new Config(args); InitializeLogging(config); //o Set the GMSEC message specification version to be used to determine // what the structure of messages is for verification and the // construction of MistMessages config.AddValue("GMSEC-SPECIFICATION-VERSION", GMSEC_SPEC_VERSION); //o Enable Message validation. This parameter is "false" by default. config.AddValue("GMSEC-MSG-CONTENT-VALIDATE", "true"); Log.Info(ConnectionManager.GetAPIVersion()); try { ConnectionManager connManager = new ConnectionManager(config); Log.Info("Opening the connection to the middleware server"); connManager.Initialize(); Log.Info(connManager.GetLibraryVersion()); //o Create all of the GMSEC Message header Fields which will // be used by all GMSEC Messages // // Note: Since these Fields contain variable values which are // based on the context in which they are used, they cannot be // automatically populated using MistMessage. List <Field> definedFields = new List <Field>(); StringField missionField = new StringField("MISSION-ID", "MISSION"); // Note: SAT-ID-PHYSICAL is an optional header Field, according // to the GMSEC ISD. StringField satIdField = new StringField("SAT-ID-PHYSICAL", "SPACECRAFT"); StringField facilityField = new StringField("FACILITY", "GMSEC Lab"); StringField componentField = new StringField("COMPONENT", "device_message"); definedFields.Add(missionField); definedFields.Add(satIdField); definedFields.Add(facilityField); definedFields.Add(componentField); //o Use setStandardFields to define a set of header fields for // all messages which are created or published on the // ConnectionManager using the following functions: // createLogMessage, publishLog, createHeartbeatMessage, // startHeartbeatService, createResourceMessage, // publishResourceMessage, or startResourceMessageService connManager.SetStandardFields(definedFields); //o Populate the Mnemonic Sample(s) MnemonicSample mSample = new MnemonicSample("MS1", new I32Field("MS1", 15)); mSample.SetEUValue(new F32Field("My EU", (float)15.0)); mSample.SetFlags(1); mSample.SetLimit(MnemonicSample.LimitFlag.RED_HIGH); // Implicitly set limit enable/disable with setting of limit mSample.SetQuality(true); mSample.SetStalenessStatus(false); mSample.SetTextValue("15"); List <MnemonicSample> mnemonic_samples = new List <MnemonicSample>(); mnemonic_samples.Add(mSample); //o Add the Mnemonic values to a Mnemonic object Mnemonic mnemonic = new Mnemonic("M1", mnemonic_samples); I16Field statusField = new I16Field("status", 5); mnemonic.SetStatus(statusField); mnemonic.SetUnits("units"); //o Determine which version of the GMSEC message specification // the ConnectionManager was initialized with uint version = connManager.GetSpecification().GetVersion(); String gmsecSpecVersion = ""; if (version == 201600) { gmsecSpecVersion = "2016.00"; } else if (version == 201400) { gmsecSpecVersion = "2014.00"; } //o Build up the Schema ID -- This is used to identify the // specific type of MVAL message to construct String schemaId = gmsecSpecVersion + ".GMSEC.MSG.MVAL"; //o Construct an MVAL Message and add the Mnemonic values to it using (GMSEC.API.MIST.MESSAGE.MnemonicMessage mvalMessage = new GMSEC.API.MIST.MESSAGE.MnemonicMessage(MVAL_MESSAGE_SUBJECT, schemaId, connManager.GetSpecification())) { mvalMessage.AddMnemonic(mnemonic); //o If validating with the 2014 spec, the MSG-ID field is // required if (version == 201400) { mvalMessage.SetValue("MSG-ID", "MVAL Request MSG-ID would go here"); } //o Add the header fields to the MVAL message connManager.AddStandardFields(mvalMessage); Log.Info("Publishing MVAL message:\n" + mvalMessage.ToXML()); connManager.Publish(mvalMessage); } connManager.Cleanup(); } catch (GMSEC_Exception e) { Log.Error(e.ToString()); return(-1); } return(0); }
public void Visit(StringField component) { throw new NotImplementedException(); }
public static StringField ExtractField(string msgstr, ref int pos, DataDictionary.DataDictionary sessionDD, DataDictionary.DataDictionary appDD) { try { int tagend = msgstr.IndexOf("=", pos); int tag = Convert.ToInt32(msgstr.Substring(pos, tagend - pos)); pos = tagend + 1; int fieldvalend = msgstr.IndexOf("\u0001", pos); StringField field = new StringField(tag, msgstr.Substring(pos, fieldvalend - pos)); /** TODO data dict stuff if (((null != sessionDD) && sessionDD.IsDataField(field.Tag)) || ((null != appDD) && appDD.IsDataField(field.Tag))) { string fieldLength = ""; // Assume length field is 1 less int lenField = field.Tag - 1; // Special case for Signature which violates above assumption if (Tags.Signature.Equals(field.Tag)) lenField = Tags.SignatureLength; if ((null != group) && group.isSetField(lenField)) { fieldLength = group.GetField(lenField); soh = equalSign + 1 + atol(fieldLength.c_str()); } else if (isSetField(lenField)) { fieldLength = getField(lenField); soh = equalSign + 1 + atol(fieldLength.c_str()); } } */ pos = fieldvalend + 1; return field; } catch (System.ArgumentOutOfRangeException e) { throw new MessageParseError("Error at position (" + pos + ") while parsing msg (" + msgstr + ")", e); } catch (System.OverflowException e) { throw new MessageParseError("Error at position (" + pos + ") while parsing msg (" + msgstr + ")", e); } catch (System.FormatException e) { throw new MessageParseError("Error at position (" + pos + ") while parsing msg (" + msgstr + ")", e); } }
public virtual Quest FindQuest(StringField questID) { return(FindQuest(StringField.GetStringValue(questID))); }
/// <summary> /// Constructs a group and stores it in this Message object /// </summary> /// <param name="grpNoFld">the group's counter field</param> /// <param name="msgstr">full message string</param> /// <param name="pos">starting character position of group</param> /// <param name="fieldMap">full message as FieldMap</param> /// <param name="dd">group definition structure from dd</param> /// <param name="sessionDataDictionary"></param> /// <param name="appDD"></param> /// <param name="msgFactory">if null, then this method will use the generic Group class constructor</param> /// <returns></returns> protected int SetGroup( StringField grpNoFld, string msgstr, int pos, FieldMap fieldMap, DataDictionary.IGroupSpec dd, DataDictionary.DataDictionary sessionDataDictionary, DataDictionary.DataDictionary appDD, IMessageFactory msgFactory) { int grpEntryDelimiterTag = dd.Delim; int grpPos = pos; Group grp = null; // the group entry being constructed while (pos < msgstr.Length) { grpPos = pos; StringField f = ExtractField(msgstr, ref pos, sessionDataDictionary, appDD); if (f.Tag == grpEntryDelimiterTag) { // This is the start of a group entry. if (grp != null) { // We were already building an entry, so the delimiter means it's done. fieldMap.AddGroup(grp, false); grp = null; // prepare for new Group } // Create a new group! if (msgFactory != null) grp = msgFactory.Create(Message.ExtractBeginString(msgstr), Message.GetMsgType(msgstr), grpNoFld.Tag); //If above failed (shouldn't ever happen), just use a generic Group. if (grp == null) grp = new Group(grpNoFld.Tag, grpEntryDelimiterTag); } else if (!dd.IsField(f.Tag)) { // This field is not in the group, thus the repeating group is done. if (grp != null) { fieldMap.AddGroup(grp, false); } return grpPos; } if (grp == null) { // This means we got into the group's fields without finding a delimiter tag. throw new GroupDelimiterTagException(grpNoFld.Tag, grpEntryDelimiterTag); } // f is just a field in our group entry. Add it and iterate again. grp.SetField(f); if(dd.IsGroup(f.Tag)) { // f is a counter for a nested group. Recurse! pos = SetGroup(f, msgstr, pos, grp, dd.GetGroupSpec(f.Tag), sessionDataDictionary, appDD, msgFactory); } } return grpPos; }
public virtual bool ContainsQuest(StringField questID) { return(FindQuest(questID) != null); }