Esempio n. 1
0
        //
        // *************************************************************
        // ****                 Drop Fill Books()                   ****
        // *************************************************************
        /// <summary>
        /// Create a new complete snapshot and drop in into file.
        /// Called by the FillHub thread.
        /// </summary>
        public void DropFillBooks()
        {
            if (m_DropWriter != null)
            {
                // Drop a summary in the current file.
                string s = Stringifiable.Stringify(m_FillHub);
                m_DropWriter.RequestEnqueue(s);
                m_DropWriter.RequestFlushNow();

                // Tell the writer to copy its current file to archive directory.
                string pathName = GetArchivePath(this.DropFileStartDateTime);
                double n        = 1;
                string fileName = GetArchiveFileName(this.DropFileStartDateTime);   // name of place to store this file.
                while (n < 20 && System.IO.File.Exists(string.Format("{0}{1}", pathName, fileName)))
                {
                    fileName = GetArchiveFileName(this.DropFileStartDateTime.AddSeconds(n));
                    n++;
                }
                if (n < 20)
                {
                    m_FillHub.Log.BeginEntry(LogLevel.Minor, "DropRule.DropFillBooks: Archiving drops to {0}{1}.", pathName, fileName);
                    m_DropWriter.RequestCopyTo(pathName, fileName);            // this will copy drop file to this new name.
                }

                // Create a snapshot to start off the new drop.
                this.DropFileStartDateTime = m_FillHub.Log.GetTime();               // new start time for current drop file.
                m_DropWriter.RequestEnqueue(s);
                m_DropWriter.RequestFlushNow();
                LastBookDrop = this.DropFileStartDateTime;

                m_FillHub.Log.EndEntry();
            }
        } // DropFillBooks()
Esempio n. 2
0
        }// Start()

        //
        //
        //
        // *********************************************************
        // ****                     Enqueue()                   ****
        // *********************************************************
        /// <summary>
        /// Dropping snapshots of the fillHub or fills.
        /// </summary>
        public void Enqueue(IStringifiable iStringfiableObject)
        {
            string s = Stringifiable.Stringify(iStringfiableObject, m_StringifyOverrideTable);

            m_ArcBookWriter.RequestEnqueue(s);
            m_LocalTimeLast = m_FillHub.Log.GetTime();                              // save time stamp of this latest entry.
        }
Esempio n. 3
0
        //
        // ****             Serialize()            ****
        //
        private void Serialize()
        {
            // Create some books.
            StringBuilder msg = new StringBuilder();

            System.Random rand = new Random();
            for (int i = 0; i < 2; ++i)
            {
                InstrumentName name    = new InstrumentName(new Product("CME", "ED", ProductTypes.Spread), string.Format("#{0}", i + 1));
                double         minTick = 0.5;
                FillBookLifo   book    = new FillBookLifo(minTick, 12.50, name);
                for (int j = 0; j < 2; ++j)
                {
                    Fill aFill = Fill.Create();
                    aFill.Price        = rand.Next(20) * minTick;
                    aFill.Qty          = rand.Next(10) + 2;
                    aFill.LocalTime    = DateTime.Now.AddSeconds(-rand.NextDouble() * 100);
                    aFill.ExchangeTime = aFill.LocalTime;
                    book.Add(aFill);
                }
                m_FillBooks.Add(name, book);

                msg.AppendFormat("{0}", Stringifiable.Stringify(book));
            }// next i

            textBox1.Text = msg.ToString();
            this.Select();
        }// Serialize().
Esempio n. 4
0
 public void AddSubElement(IStringifiable subElement)
 {
     if (subElement is IntegerArray)
     {
         IntegerArray a = (IntegerArray)subElement;
         if (a.Name.Equals("A"))
         {
             this.DataIntA = a.Data;
         }
         else if (a.Name.Equals("B"))
         {
             this.DataIntB = a.Data;
         }
         else if (a.Name.Equals("C"))
         {
             this.DataIntC = a.Data;
         }
     }
     else if (subElement is DoubleArray)
     {
         DoubleArray a = (DoubleArray)subElement;
         if (a.Name.Equals("A"))
         {
             this.DataA = a.Data;
         }
         else if (a.Name.Equals("B"))
         {
             this.DataB = a.Data;
         }
         else if (a.Name.Equals("C"))
         {
             this.DataC = a.Data;
         }
     }
     else if (subElement is ObjectString)
     {
         if (this.DataObjectList == null)
         {
             this.DataObjectList = new List <object>();
         }
         ObjectString obj = (ObjectString)subElement;
         Type         type;
         if (Stringifiable.TryGetType(obj.ClassName, out type))
         {
             object o = UV.Lib.Utilities.ConvertType.ChangeType(type, obj.Data);
             this.DataObjectList.Add(o);
         }
     }
     else if (subElement is IStringifiable)      // todo storage of values
     {
         if (this.DataObjectList == null)
         {
             this.DataObjectList = new List <object>();
         }
         this.DataObjectList.Add(subElement);
     }
 }
Esempio n. 5
0
        //
        //
        //
        // *****************************************************************
        // ****                 Initialize MultiPanel()                 ****
        // *****************************************************************
        private void InitializeMultiPanel(IEngineContainer parentContainer, EngineContainerGui guiContainer)
        {
            m_EngineContainerID = parentContainer.EngineContainerID;

            // Try to create any hudpanels discovered
            List <HudPanel> newHudPanels = new List <HudPanel>();

            foreach (EngineGui engineGui in guiContainer.m_Engines)
            {
                if (string.IsNullOrEmpty(engineGui.LowerHudFullName))
                {
                    continue;
                }
                Control newControl = null;
                Type    guiType    = typeof(EngineControl);
                if (Stringifiable.TryGetType(engineGui.LowerHudFullName, out guiType))     // Check whether this control is known to us!
                {
                    if (Utilities.GuiCreator.TryCreateControl(out newControl, guiType, engineGui))
                    {   // We have successfully created the desired control.
                        if (newControl is HudPanel)
                        {
                            newHudPanels.Add((HudPanel)newControl);
                        }
                    }
                }
            }



            int maxX = 0;
            int maxY = 0;

            this.SuspendLayout();
            foreach (HudPanel control in newHudPanels)
            {
                if (control != null)                                    // each engine has entry here, even if its null. (but why?)
                {
                    m_EngineControlList.Add(control.EngineId, control);
                    control.Size     = control.SmallestSize;            // force panel to be smallest size possible.
                    control.Location = new Point(m_NextPanelXLoc, m_NextPanelYLoc);
                    // update layout control parameters.
                    m_NextPanelXLoc += control.Size.Width;
                    maxX             = Math.Max(maxX, control.Location.X + control.Width);
                    maxY             = Math.Max(maxY, control.Location.Y + control.Height);
                    this.Controls.Add(control);
                }
            }//next engine
            // Resize myself.
            this.ClientSize = new Size(maxX, maxY);     // make this as small as possible, Cluster will resize again.
            if (m_EngineControlList.Count == 0)
            {
                this.Visible = false;
            }

            this.ResumeLayout(false);
        }//InitializeMultiPanel()
        //
        // *********************************************
        // ****         SetUp Initialize()          ****
        // *********************************************
        /// <summary>
        /// </summary>
        protected override void SetupInitialize(IEngineHub myEngineHub, IEngineContainer engineContainer, int engineID, bool setupGui)
        {
            // Save information about local strategy hub.
            m_EngineContainerId = engineContainer.EngineContainerID;
            if (myEngineHub is IService)
            {
                m_LocalEngineHubName = ((IService)myEngineHub).ServiceName;
            }
            StrategyHub strategyHub = ((StrategyHub)myEngineHub);

            this.Log         = strategyHub.Log;
            m_LocalEngineHub = myEngineHub;

            // Locate our target remote hub/service.
            IEngineHub   remoteEngineHub = null;
            EventHandler del             = new EventHandler(ProcessRemoteEngineEvents);

            if (strategyHub.SubscribeToRemoteEngineHub("ExecutionHub", m_EngineContainerId, m_EngineID, del, out remoteEngineHub))
            {
                m_RemoteEngineHub = remoteEngineHub;
            }
            else
            {
                throw new Exception("Failed to locate remote hub.");
            }


            // Create the parameter table.
            Type remoteEngineType;

            if (Stringifiable.TryGetType(m_RemoteEngineClassName, out remoteEngineType))
            {
                this.m_PInfo = CreateParameterInfo(myEngineHub, engineContainer.EngineContainerID, this.EngineID, remoteEngineType);
            }

            //
            // Add sub-engines to the parent Strategy
            //
            //  They will be automatically initialized outside in StrategyHub loop
            //  that called us, since we will add new engine to the end of the list we are looping thru now.
            List <IStringifiable> subElements = m_Node.GetElements();

            if (subElements != null)
            {
                foreach (IStringifiable iObject in subElements)
                {                                       // Engines that are beneath non-engines will not be found here.
                    if (iObject is ExecutionController) // This remote engine will not need to broad its existance,
                    {
                        ExecutionController subEngine = (ExecutionController)iObject;
                        subEngine.m_IsSubEngine = true;                     // since it will be included in another engine (this one).
                        ((Strategy)engineContainer).TryAddEngine(subEngine, myEngineHub);
                    }
                }
            }
        }//SetupInitialize()
Esempio n. 7
0
        } // TryPeriodicBookDrop()

        //
        //
        // *************************************************************
        // ****             StartNewDropArchive()                   ****
        // *************************************************************
        /// <summary>
        /// Create a new complete snapshot and drop in into file.
        /// Called by the FillHub thread, so we know no fills will be being added while we are here.
        /// </summary>
        public void StartNewDropArchive()
        {
            m_FillHub.Log.NewEntry(LogLevel.Major, "Running drop files for account/instrument {0} for {1}!", m_FillHub.Name, AppServices.GetInstance().m_AmbreUserName);

            if (m_FillHub.ListenerTradeSubscriptionFilter == null)
            {
                m_FillHub.Log.NewEntry(LogLevel.Warning, "*****Notice***** The account or instrument filter becomes corrupted because fill listener filter is null now");
                if (!string.IsNullOrEmpty(m_FillHub.m_LastListenAccountFilter))
                {
                    m_FillHub.ResetFillListener();
                }
            }
            else
            {
                if (m_FillHub.ListenerTradeSubscriptionFilter.GetType() != typeof(TradeSubscriptionAccountFilter) && m_FillHub.ListenerTradeSubscriptionFilter.GetType() != typeof(TradeSubscriptionInstrumentFilter))
                {
                    m_FillHub.Log.NewEntry(LogLevel.Warning, "*****Notice***** The account or instrument filter becomes corrupted because fill listener filter has different types from account or instrument filter");
                    if (!string.IsNullOrEmpty(m_FillHub.m_LastListenAccountFilter))
                    {
                        m_FillHub.ResetFillListener();
                    }
                }
            }
            m_FillHub.CheckMakeUpFilterArgs(m_FillHub.m_LastListenAccountFilter);
            string fillHubSnapshot = Stringifiable.Stringify(m_FillHub, m_StringifyOverrideTable);

            if (m_ArcBookWriter != null)
            {
                // Wrap up the current working file, and archive it.
                m_ArcBookWriter.RequestFlushNow();                  // Following procedure as above, make current file up to date...
                if (PushToRepository)                               // Now its up-to-date, push it to the repository group-shared drive.
                {
                    string droppath = string.Format("\\\\fileserver\\Users\\DV_Ambre\\AmbreUsers\\{0}\\Drops\\", AppServices.GetInstance().m_AmbreUserName);
                    string repoPath = DropSimple.GetArchivePath(DropFileStartDateTime, droppath);
                    m_FillHub.Log.NewEntry(LogLevel.Minor, "Sending request to copy to new drop directory:{0}.", repoPath);
                    m_ArcBookWriter.RequestCopyTo(repoPath, string.Empty);  // push current file to new repository now, keep same filename.
                    //m_ArcBookWriter.RequestCopyAllFiles(repoPath, "*FillBooks*");// try to sync all

                    // Also copy the files to old path that is \\\\fileserver\\Users\\dv_bre\\Ambre\\Drops\\ told by Mike.
                    // Temp fix to allow a smooth transition from the old approach to the new approach.
                    droppath = "\\\\fileserver\\Users\\dv_bre\\Ambre\\Drops\\";
                    repoPath = DropSimple.GetArchivePath(DropFileStartDateTime, droppath);
                    m_FillHub.Log.NewEntry(LogLevel.Minor, "Sending request to copy to old drop directory:{0}.", repoPath);
                    m_ArcBookWriter.RequestCopyTo(repoPath, string.Empty);
                }
                // Set new starting time stamp for the new archival file.
                DropFileStartDateTime = m_FillHub.Log.GetTime();                                                                              // This is time stamp of the next archive file to start.
                string archivalPath = DropSimple.GetArchivePath(DropFileStartDateTime, Misty.Lib.Application.AppInfo.GetInstance().DropPath); // Creates starting time stamp (now's date) in arcPath name.
                m_ArcBookWriter.RequestChangeFileName(archivalPath, GetArchiveFileName(DropFileStartDateTime, DropType_FillBook));            // Change current output filename to a new name (thereby ending our writes to the last one).
                m_ArcBookWriter.RequestEnqueue(fillHubSnapshot);                                                                              // initialize the new file with new snapshot
                m_ArcBookWriter.RequestFlushNow();                                                                                            // flush it just in case, so at least some entry is present in file if we crash.
            }
            LastBookDrop = m_FillHub.Log.GetTime();                                                                                           // store the time we last did a snapshot.
        } // DropFillBooks()
Esempio n. 8
0
        } // DropFillBooks()

        //
        //
        //
        //
        // *********************************************************
        // ****                 TryLoadBooks()                  ****
        // *********************************************************
        public bool TryLoadBooks()
        {
            List <IStringifiable> nodeList = ReadLocalFillBook();
            string fillHubTypeName         = m_FillHub.GetType().FullName;


            // Now convert these nodes into real objects.
            List <IStringifiable> objectList = new List <IStringifiable>();

            foreach (IStringifiable iNode in nodeList)
            {
                Node node = (Node)iNode;
                if (node.Name.Equals(fillHubTypeName))
                {   // We need to take the sub elements of the FillHub, and pull them out.
                    Dictionary <string, string> unused = new Dictionary <string, string>();
                    ((IStringifiable)m_FillHub).SetAttributes(node.Attributes, ref unused);
                    foreach (IStringifiable subElem in node.SubElements)
                    {
                        IStringifiable obj = Stringifiable.DeStringify((Node)subElem);
                        objectList.Add(obj);
                    }
                }
                else
                {   // These are fill events and other things.
                    IStringifiable obj = Stringifiable.DeStringify((Node)iNode);
                    objectList.Add(obj);
                }
            }
            //
            if (objectList != null && objectList.Count > 0)
            {
                foreach (IStringifiable obj in objectList)                          // load all InstrumentMapEntries first - needed to create books
                {
                    if (obj is InstrumentMapEntry)
                    {
                        ((IStringifiable)m_FillHub).AddSubElement(obj);
                    }
                }
                foreach (IStringifiable obj in objectList)                          // load everything else now.
                {
                    if (!(obj is InstrumentMapEntry))
                    {
                        ((IStringifiable)m_FillHub).AddSubElement(obj);
                    }
                }
                return(true);
            }
            else
            {
                return(false);
            }
        }// TryLoadBooks()
        }//SetupInitialize()

        //
        //
        //
        //
        // ************************************************
        // ****             SetupBegin()               ****
        // ************************************************
        /// <summary>
        /// </summary>
        public override void SetupBegin(IEngineHub myEngineHub, IEngineContainer engineContainer)
        {
            //
            // Master Remote-Engines must send requests to ExecutionHub now.
            //
            if (m_IsSubEngine == false)
            {
                // Count number of (master) remote engines found in this strategy.
                // Master remote engines are those connected directly to the Strategy,
                // without being held by another engine.
                // Only masters broadcast their xml to the ExecutionHub, and other sub-engine
                // engines are included as subelements of their master's broadcast.
                // (If each remote engine broadcasted separately, the ExecHub would have to know how
                // to put them all back together again... that is, who owned whom.)
                int remoteMasterEngineCount = 0;
                foreach (IEngine iEng in engineContainer.GetEngines())
                {
                    if (iEng is ExecutionController && ((ExecutionController)iEng).m_IsSubEngine == false)
                    {
                        remoteMasterEngineCount++;
                    }
                    //if (iEng is RemoteEngine)           // now count all remote engines
                    //    remoteMasterEngineCount++;
                }

                //
                // Create my engine creation request
                //
                Dictionary <Type, string[]> rules = new Dictionary <Type, string[]>();
                rules.Add(this.GetType(), new string[] { "GetClassName", string.Empty, string.Empty });
                string xmlString = Stringifiable.Stringify(this, rules);

                EngineEventArgs e = new EngineEventArgs();
                e.MsgType           = EngineEventArgs.EventType.NewEngine;
                e.Status            = EngineEventArgs.EventStatus.Request;
                e.EngineID          = m_EngineID;
                e.EngineContainerID = m_EngineContainerId;
                e.DataObjectList    = new List <object>();
                e.DataObjectList.Add(xmlString);                          // 0 - engine specs
                e.DataObjectList.Add(m_LocalEngineHubName);               // 1 - engine hub name
                e.DataObjectList.Add(remoteMasterEngineCount.ToString()); // 2 - number of engines remote hub should expect from this EngineContainer
                // Send request to remote.
                if (m_RemoteEngineHub != null && m_RemoteEngineHub.HubEventEnqueue(e))
                {
                    Log.NewEntry(LogLevel.Minor, "SetupBegin: Remote-{0} sent creation request to remote.", m_RemoteEngineClassName);
                }
                else
                {
                    Log.NewEntry(LogLevel.Minor, "SetupBegin: Remote-{0} failed to send creation request to remote.", m_RemoteEngineClassName);
                }
            } // master remote-engine sends request.
        }     //SetupBegin()
Esempio n. 10
0
        }// LoadServicesFromFile()

        //
        //
        //
        //
        //
        // *************************************************************
        // ****          TrySaveServicesToFile()                    ****
        // *************************************************************
        //
        public bool TrySaveServicesToFile(string fileName, bool overWriteExisting = true)
        {
            string filePath = string.Format("{0}{1}", Info.UserConfigPath, fileName);

            if (System.IO.File.Exists(filePath))
            {
                if (overWriteExisting)
                {
                    System.IO.File.Delete(filePath);
                }
                else
                {
                    return(false);
                }
            }

            // Create string xml.
            StringBuilder s = new StringBuilder();

            lock (m_ServiceLock)
            {
                foreach (IService service in m_Services)
                {
                    Misty.Lib.IO.Xml.IStringifiable iStringObj = service as Misty.Lib.IO.Xml.IStringifiable;
                    if (iStringObj != null)
                    {
                        s.AppendFormat("{0}\r\n", Stringifiable.Stringify(iStringObj));
                    }
                    if (service.ServiceName.Equals("TTApi"))
                    {
                        Dictionary <Type, string[]> stringifyOverrideTable = new Dictionary <Type, string[]>();
                        s.AppendFormat("{0}\r\n", Stringifiable.Stringify(m_AmbreUserName, stringifyOverrideTable));
                    }
                }
            }
            // Write out file.
            try
            {
                using (System.IO.StreamWriter writer = System.IO.File.CreateText(filePath))
                {
                    writer.Write(s.ToString());
                    writer.Close();
                }
            }
            catch (Exception)
            {
                return(false);
            }
            return(true);
        }//TrySaveServicesToFile()
Esempio n. 11
0
        //
        //
        #endregion//Constructors


        #region no Properties
        // *****************************************************************
        // ****                     Properties                          ****
        // *****************************************************************
        //
        //
        #endregion//Properties


        #region Public Methods
        // *****************************************************************
        // ****                     Public Methods                      ****
        // *****************************************************************
        //
        //
        //
        // *************************************************
        // ****             SendMessage()               ****
        // *************************************************
        /// <summary>
        /// Simple method to send a Message to a specific ServiceManager
        /// on a specific socket conversation.
        /// </summary>
        /// <param name="conversationId">Conversation to send message on, -1 means all conversations.</param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool SendMessage(int conversationId, Message msg)
        {
            string s = string.Format("{0}\n", Stringifiable.Stringify(msg, null, false));

            m_Messages.Recycle(msg);
            if (conversationId >= 0)
            {
                return(m_Socket.Send(s, conversationId));
            }
            else
            {
                return(m_Socket.Send(s));
            }
        }
Esempio n. 12
0
        } // TryPeriodicBookDrop()

        //
        //
        // *************************************************************
        // ****             StartNewDropArchive()                   ****
        // *************************************************************
        /// <summary>
        /// Create a new complete snapshot and drop in into file.
        /// Called by the FillHub thread, so we know no fills will be being added while we are here.
        /// </summary>
        public void StartNewDropArchive()
        {
            string fillHubSnapshot = Stringifiable.Stringify(m_FillHub, m_StringifyOverrideTable);

            // Copy and reinitialize the local file
            if (m_LocalBookWriter != null)
            {
                m_LocalBookWriter.RequestFlushNow();                // Flush queue into the current file, making it up-to-date.
                string fileName = GetLocalFileName();               // Local drop-file name
                string path     = string.Format("{0}Previous\\", GetLocalPath());
                m_LocalBookWriter.RequestMoveTo(path, fileName);    // Move the current drop file to a safe, backup area.
                m_LocalBookWriter.RequestEnqueue(fillHubSnapshot);  // Create a new local drop file, and initialize it w/ snapshot
                m_LocalBookWriter.RequestFlushNow();                // I like to push out the first snapshot immediately...
            }

            // Archive and restart new archival files.
            if (m_ArcBookWriter != null)
            {
                m_ArcBookWriter.RequestFlushNow();                  // Following procedure as above, make current file up to date...
                if (PushToRepository)                               // Now its up-to-date, push it to the repository group-shared drive.
                {
                    string repoPath = GetRepositoryPath(DropFileStartDateTime);
                    m_ArcBookWriter.RequestCopyTo(repoPath, string.Empty);                                                           // push current file to repository now, keep same filename.
                    m_ArcBookWriter.RequestCopyAllFiles(repoPath, string.Format("*{0}", GetArchiveFileNameBase(DropType_FillBook))); // try to sync all
                }
                // Set new starting time stamp for the new archival file.
                DropFileStartDateTime = m_FillHub.Log.GetTime();                                                          // This is time stamp of the next archive file to start.
                string archivalPath = GetArchivePath(DropFileStartDateTime);                                              // Creates starting time stamp (now's date) in arcPath name.
                m_ArcBookWriter.RequestChangeFileName(archivalPath, GetArchiveFileName(DateTime.Now, DropType_FillBook)); // Change current output filename to a new name (thereby ending our writes to the last one).
                m_ArcBookWriter.RequestEnqueue(fillHubSnapshot);                                                          // initialize the new file with new snapshot
                m_ArcBookWriter.RequestFlushNow();                                                                        // flush it just in case.
            }

            // Archive
            if (m_FillWriter != null)
            {
                m_FillWriter.RequestFlushNow();
                string archivalPath = GetArchivePath(DropFileStartDateTime);// Creates starting time stamp (now's date) in arcPath name.
                m_FillWriter.RequestChangeFileName(archivalPath, GetArchiveFileName(DropFileStartDateTime, DropType_Fills));
            }

            // Store the time we did this snapshot.
            LastBookDrop = m_FillHub.Log.GetTime();                 // store the time we last did a snapshot.
        } // DropFillBooks()
Esempio n. 13
0
 void IStringifiable.SetAttributes(Dictionary <string, string> attributes)
 {
     foreach (KeyValuePair <string, string> keyVal in attributes)
     {
         bool b;
         int  n;
         Type type;
         if (keyVal.Key == "Name")
         {
             this.Name = keyVal.Value;
         }
         else if (keyVal.Key == "DisplayName")
         {
             this.DisplayName = keyVal.Value;
         }
         else if (keyVal.Key == "IsReadOnly" && bool.TryParse(keyVal.Value, out b))
         {
             this.IsReadOnly = b;
         }
         else if (keyVal.Key == "ValueType" && Stringifiable.TryGetType(keyVal.Value, out type))
         {
             this.ValueType = type;
         }
         else if (keyVal.Key == "ParameterID" && int.TryParse(keyVal.Value, out n))
         {
             this.ParameterID = n;
         }
         else if (keyVal.Key == "EngineID" && int.TryParse(keyVal.Value, out n))
         {
             this.EngineID = n;
         }
         else if (keyVal.Key == "EngineContainerID" && int.TryParse(keyVal.Value, out n))
         {
             this.EngineContainerID = n;
         }
         else if (keyVal.Key == "EngineHubName")
         {
             this.EngineHubName = keyVal.Value;
         }
     }
 }
Esempio n. 14
0
        } // TryPeriodicBookDrop()

        //
        //
        // *************************************************************
        // ****             StartNewDropArchive()                   ****
        // *************************************************************
        /// <summary>
        /// Create a new complete snapshot and drop in into file.
        /// Called by the FillHub thread, so we know no fills will be being added while we are here.
        /// </summary>
        public void StartNewDropArchive()
        {
            string fillHubSnapshot = Stringifiable.Stringify(m_FillHub, m_StringifyOverrideTable);

            if (m_ArcBookWriter != null)
            {
                // Wrap up the current working file, and archive it.
                m_ArcBookWriter.RequestFlushNow();                  // Following procedure as above, make current file up to date...
                if (PushToRepository)                               // Now its up-to-date, push it to the repository group-shared drive.
                {
                    string repoPath = DropSimple.GetArchivePath(DropFileStartDateTime, DropRules.BreRepositoryPath);
                    m_ArcBookWriter.RequestCopyTo(repoPath, string.Empty);  // push current file to repository now, keep same filename.
                    //m_ArcBookWriter.RequestCopyAllFiles(repoPath, "*FillBooks*");// try to sync all
                }
                // Set new starting time stamp for the new archival file.
                DropFileStartDateTime = m_FillHub.Log.GetTime();                                                                           // This is time stamp of the next archive file to start.
                string archivalPath = DropSimple.GetArchivePath(DropFileStartDateTime, UV.Lib.Application.AppInfo.GetInstance().DropPath); // Creates starting time stamp (now's date) in arcPath name.
                m_ArcBookWriter.RequestChangeFileName(archivalPath, GetArchiveFileName(DropFileStartDateTime, DropType_FillBook));         // Change current output filename to a new name (thereby ending our writes to the last one).
                m_ArcBookWriter.RequestEnqueue(fillHubSnapshot);                                                                           // initialize the new file with new snapshot
                m_ArcBookWriter.RequestFlushNow();                                                                                         // flush it just in case, so at least some entry is present in file if we crash.
            }
            LastBookDrop = m_FillHub.Log.GetTime();                                                                                        // store the time we last did a snapshot.
        } // DropFillBooks()
        }//buttonRecoveryStart_Click()

        /// <summary>
        /// When the user clicks save books button, the program copies the files to drop paths for two projects.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSaveOutput_Click(object sender, EventArgs e)
        {
            if (sender == this.buttonSaveOutput)
            {
                // Save the output of the fill hubs for this user.
                Log.NewEntry(LogLevel.Minor, "The button of save output is clicked by user.");

                // Check whether the fill hub exists and the date time is correct.
                DateTime minDateTime = new DateTime(2000, 1, 1);
                if (m_AuditTrailFillHub == null || m_UserSelectedRecoveryDropFileDateTime <= minDateTime)
                {
                    Log.NewEntry(LogLevel.Major, "The fill hub is null or the selected recovery date time is wrong.");
                    return;
                }

                Log.NewEntry(LogLevel.Minor, "The user confirms the update.");

                // Write the final state of fill hubs to the drop path. The next time when the Ambre starts, it will use these drop files.
                Dictionary <Type, string[]> stringifyOverrideTable = new Dictionary <Type, string[]>();
                stringifyOverrideTable.Add(m_AuditTrailFillHub.GetType(), new string[] { "Ambre.TTServices.Fills.FillHub", "GetAttributesDrop", "GetElementsDrop" });
                string fillHubSnapshot = Stringifiable.Stringify(m_AuditTrailFillHub, stringifyOverrideTable);

                // Generate the target file name full path.
                if (!string.IsNullOrEmpty(m_UserName) && m_AuditTrailFillHub.HubName != null)
                {
                    string targetFileName                   = null;
                    string targetFileDateDirectory          = null;
                    string targetFilePath                   = null;
                    string targetAmbreDropFileDateDirectory = null;
                    string targetAmbreDropFilePath          = null;
                    targetFileName                   = string.Format("{0}_{1}_{2}_{3}.txt", DateTime.Now.ToString("HHmmss"), "FillBooks", m_UserName, m_FillHubOrFillManagerName);
                    targetFileDateDirectory          = string.Format("{0}{1}\\", m_RepositoryDropFilePath, DateTime.Now.ToString("yyyyMMdd"));
                    targetFilePath                   = string.Format("{0}{1}\\{2}", m_RepositoryDropFilePath, DateTime.Now.ToString("yyyyMMdd"), targetFileName);
                    targetAmbreDropFileDateDirectory = string.Format("{0}{1}\\", m_ReferenceDropFilePath, DateTime.Now.ToString("yyyyMMdd"));
                    targetAmbreDropFilePath          = string.Format("{0}{1}\\{2}", m_ReferenceDropFilePath, DateTime.Now.ToString("yyyyMMdd"), targetFileName);

                    // Check whether the hub name is different from the input fill hub name.
                    StringBuilder stringBuilder = new StringBuilder();
                    if (!m_AuditTrailFillHub.HubName.Equals(string.Empty) && !m_AuditTrailFillHub.HubName.Equals(m_FillHubOrFillManagerName))
                    {
                        Log.NewEntry(LogLevel.Major, "The fill hub name is different from the input. And the names are {0} and {1}.", m_AuditTrailFillHub.HubName, m_FillHubOrFillManagerName);
                        stringBuilder.AppendFormat("The fill hub name is different from the input. And the names are {0} and {1}.", m_AuditTrailFillHub.HubName, m_FillHubOrFillManagerName);
                    }

                    // Show confirmation dialog. Ask the user whether he likes to output the final state of fill hub page out to update Ambre position.
                    stringBuilder.AppendLine("I am going to save the final state of fill account displayed in the table, Ok?");
                    stringBuilder.AppendFormat("The output drop file will be contained in the path {0} and {1}.", targetFilePath, targetAmbreDropFilePath);
                    DialogResult result = MessageBox.Show(stringBuilder.ToString(), "Output the final state of fill account", MessageBoxButtons.YesNo);
                    if (result == System.Windows.Forms.DialogResult.No)
                    {
                        Log.NewEntry(LogLevel.Major, "The user does not confirm the drop file update.");
                        return;
                    }

                    // Try create the target file path if it does not exist.
                    if (!System.IO.Directory.Exists(targetFileDateDirectory))
                    {
                        System.IO.Directory.CreateDirectory(targetFileDateDirectory);
                    }

                    // Write the stringified fill hub snapshot to the target file path.
                    using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(targetFilePath, false))
                    {
                        streamWriter.WriteLine(fillHubSnapshot);
                        streamWriter.Close();
                    }

                    // Copy the current file written to another file path again. Use try catch block to copy the file to another path as well.
                    if (!System.IO.Directory.Exists(targetAmbreDropFileDateDirectory))
                    {
                        System.IO.Directory.CreateDirectory(targetAmbreDropFileDateDirectory);
                    }
                    try
                    {
                        System.IO.File.Copy(targetFilePath, targetAmbreDropFilePath, true);
                    }
                    catch (Exception ex)
                    {
                        Log.NewEntry(LogLevel.Major, "The target file is not copied to Ambre drop path successfully with exception {0}.", ex);
                        return;
                    }
                }
                else
                {
                    Log.NewEntry(LogLevel.Major, "The target file name generated failed. The user name or hub name is null or empty.");
                    return;
                }
            }
        }//buttonSaveOutput_Click()
Esempio n. 16
0
        }        //HubEventHandler()

        //
        //
        //
        // *****************************************************************
        // ****					Process EngineEvents					****
        // *****************************************************************
        /// <summary>
        /// These are events broadcast from Engines on the StrategyHub (typically).
        /// Confirmation of parameter changes must be passed to the guis that
        /// represent them.
        /// </summary>
        /// <param name="engineEvent"></param>
        private void ProcessEngineEvents(EngineEventArgs engineEvent)
        {
            switch (engineEvent.MsgType)
            {
            case EngineEventArgs.EventType.GetControls:
                // *****************************************
                // ****			Get Controls			****
                // *****************************************
                // Processes the response from an EngineHub providing its controls & GUIs.
                if (engineEvent.Status != EngineEventArgs.EventStatus.Confirm)
                {
                    return;
                }
                // Add controls to our master list for each engine hub.
                IEngineHub iRemoteEngineHub;
                if (m_RemoteEngineHubs.TryGetValue(engineEvent.EngineHubName, out iRemoteEngineHub))
                {       // Get the EngineHub that contains the engines associated with these controls.
                        // Extract controls from the event arg.
                    List <IStringifiable> getControlsData = new List <IStringifiable>();
                    try
                    {
                        foreach (object o in engineEvent.DataObjectList)
                        {
                            if (o is string)
                            {
                                getControlsData.AddRange(Stringifiable.Create((string)o));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.NewEntry(LogLevel.Major, "ProcessEngineEvent: Exception for GetControls event. {0}", ex.Message);
                        return;
                    }
                    // Get control template for this IEngineHub (if they exist we overwrite them).
                    Dictionary <int, GuiTemplates.EngineContainerGui> hubTemplates = null;
                    if (!m_EngineHubTemplates.TryGetValue(engineEvent.EngineHubName, out hubTemplates))
                    {                                                                           // First time we've received controls from this engineHub. Create a template list for it.
                        hubTemplates = new Dictionary <int, GuiTemplates.EngineContainerGui>(); // containerId, gui template
                        m_EngineHubTemplates.Add(engineEvent.EngineHubName, hubTemplates);
                    }
                    Log.NewEntry(LogLevel.Minor, "ProcessEngineEvent: {0} for {1}.", engineEvent.MsgType, engineEvent.EngineHubName);
                    // Extract each bit of control data.
                    Dictionary <string, IEngineHub> engineHubPointers = new Dictionary <string, IEngineHub>();
                    foreach (object o in getControlsData)
                    {
                        if (o is GuiTemplates.EngineContainerGui)
                        {       // This is an engine container gui object.
                                // We will accept this as a new gui description for this EngineContainer.
                                // TODO: Why overwrite it?  How to implement new Engines appearing dynamically?
                            GuiTemplates.EngineContainerGui engContainerGui = (GuiTemplates.EngineContainerGui)o;
                            hubTemplates[engContainerGui.EngineContainerID] = engContainerGui;          // add/overwrite entries for this strategy.
                        }
                    }
                }
                break;

            default:
                // *************************************************
                // ****			Default EngineEvent			    ****
                // *************************************************
                // All other engine messages are simply routed to the display that
                // containing the appropriate IEngineHub and IEngineContainer / Cluster.
                if (engineEvent.EngineContainerID < 0)
                {
                    //Log.NewEntry(LogLevel.Warning, "ProcessEngineEvent: Warning EngineHubName={0}, EngineContainerID={1}.", engineEvent.EngineHubName, engineEvent.EngineContainerID);
                    if (engineEvent.MsgType == EngineEventArgs.EventType.SaveEngines)
                    {
                        // TODO: when receiving this event (we check that we are expecting it).
                        // If we are, then we push it to the open save engine form, so the user can analyze the nodes
                        // manipulate them etc.  This is how the user can copy strategies, and edit them on the fly.
                        // Now, we simply dump the data to a file.
                        string path = string.Format("{0}SavedStrategies.txt", AppInfo.GetInstance().UserConfigPath);
                        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, false))
                        {
                            foreach (object o in engineEvent.DataObjectList)
                            {
                                string s = (string)o;
                                sw.WriteLine(s);
                            }
                            sw.Close();
                        }
                    }
                }
                else
                {       // Update for specific EngineContainerId
                    List <int> displayList = null;
                    Dictionary <int, List <int> > clusterIdToDisplayList = null;
                    if (m_ClusterDisplayIds.TryGetValue(engineEvent.EngineHubName, out clusterIdToDisplayList) && clusterIdToDisplayList.TryGetValue(engineEvent.EngineContainerID, out displayList))
                    {
                        foreach (int displayID in displayList)
                        {
                            ClusterDisplay display;
                            if (m_ClusterDisplays.TryGetValue(displayID, out display))
                            {
                                if (display.HubEventEnqueue(engineEvent))
                                {
                                    display.RegenerateNow(this, null);
                                }
                            }
                        }
                    }
                }
                break;
            }//switch(engineEvent.MsgType)
        }        //ProcessEngineEvents()
Esempio n. 17
0
        } // DropFillBooks()

        //
        //
        //
        //
        // *********************************************************
        // ****                 TryLoadBooks()                  ****
        // *********************************************************
        /// <summary>
        /// Reads the local drop file at the GetLocalPath() location named
        /// GetLocalFileName(), and obtains a list of IStringifiable.Nodes in that file.
        /// This list of nodes is examined (in reverse order) until the most recent FillHub
        /// node object is found.
        /// The fillhub node is broken down into its parts, which are actually created and
        /// store in another list.  The remaining nodes are also created and loading into
        /// the list as well.  (These are usually fills that came after the fillhub snapshot.)
        /// Version 4:  This is improved because it relies on read-methods from Stringifiable namespace.
        /// </summary>
        /// <returns>True upon success</returns>
        public bool TryLoadBooks(string loadFileName = "")
        {
            string filePath = string.Empty;                 // place to store the desired book to load.

            // Find most recent book that matches unique name.
            List <string> dirPathList = new List <string>(System.IO.Directory.GetDirectories(UV.Lib.Application.AppInfo.GetInstance().DropPath, "20*")); // presumes all fills in 21st century!

            dirPathList.Sort();
            int           dirPtr       = dirPathList.Count - 1; // point to last entry.
            List <string> filePathList = new List <string>();
            string        pattern      = string.Format("*{0}*", this.GetArchiveFileNameBase(DropType_FillBook));

            while (string.IsNullOrEmpty(filePath) && dirPtr >= 0)
            {
                filePathList.Clear();
                string currentDirPath = dirPathList[dirPtr];
                filePathList.AddRange(System.IO.Directory.GetFiles(currentDirPath, pattern));
                if (filePathList.Count > 0)
                {
                    filePathList.Sort();
                    int filePtr = filePathList.Count - 1; // point to last entry
                    while (string.IsNullOrEmpty(filePath) && filePtr >= 0)
                    {                                     // We can set to checking here and validation, or use a slightly earlier drop, etc.
                        System.IO.FileInfo info = new System.IO.FileInfo(filePathList[filePtr]);
                        bool isGood             = info.Length > 0;
                        if (isGood)
                        {
                            filePath = filePathList[filePathList.Count - 1];
                        }
                        else
                        {
                            filePtr--;
                        }
                    }
                }
                else
                {
                    dirPtr--;
                }
            }// while file not found.
            if (string.IsNullOrEmpty(filePath))
            {
                m_FillHub.Log.BeginEntry(LogLevel.Major, "DropRules.TryLoadBooks: No drop file found for pattern {0}. Searched directories: ", pattern);
                foreach (string s in dirPathList)
                {
                    int n = s.LastIndexOf('\\');
                    m_FillHub.Log.AppendEntry("{0} ", s.Substring(n + 1, s.Length - (n + 1)));
                }
                m_FillHub.Log.EndEntry();
                return(false);
            }

            //
            // Load the drop file.
            //
            this.m_FillHub.Log.NewEntry(LogLevel.Major, "DropRules.TryLoadBooks: {0}", filePath);
            List <Node> nodeList;

            try
            {
                using (StringifiableReader reader = new StringifiableReader(filePath))
                {
                    nodeList = reader.ReadNodesToEnd();
                    reader.Close();
                }
            }
            catch (Exception e)
            {
                this.m_FillHub.Log.NewEntry(LogLevel.Error, "DropRules.TryLoadBooks: StrigifiableReader exception: {0}", e.Message);
                return(false);
            }
            // Go thru the nodes, looking for the last FillHub node.
            Node   hubNode         = null;
            string fillHubTypeName = m_FillHub.GetType().FullName;
            int    ptr             = nodeList.Count - 1;    // point to last element

            while (ptr >= 0)
            {
                if (hubNode != null)
                {                                           // We read backwards, and once we've passed the hub
                    nodeList.RemoveAt(ptr);                 // From here on out, we want to dump everthing!
                }
                else if (nodeList[ptr].Name == fillHubTypeName)
                {
                    hubNode = nodeList[ptr];
                    nodeList.RemoveAt(ptr);                 // remove the hub also; we already have a pointer to it.
                }
                ptr--;                                      // move backwards thru list
            }//wend ptr

            // Extract the info from the FillHub node.
            List <IStringifiable> objectList = new List <IStringifiable>();

            ((IStringifiable)m_FillHub).SetAttributes(hubNode.Attributes);  // initialize this hub!
            foreach (IStringifiable subElem in hubNode.SubElements)
            {
                IStringifiable obj = Stringifiable.Create((Node)subElem);
                objectList.Add(obj);                        // keep all the sub elements (below) we load them in specific order!
            }
            // Now create the objects we found after the hub - these are usually additional fills not in the fill hub.
            foreach (Node anode in nodeList)
            {
                IStringifiable obj = Stringifiable.Create(anode);
                objectList.Add(obj);
            }

            // Load objects we found.
            if (objectList != null && objectList.Count > 0)
            {
                foreach (IStringifiable obj in objectList)
                {
                    if (obj is InstrumentMapEntry)                      // load all InstrumentMapEntries first; needed to create fill books
                    {
                        ((IStringifiable)m_FillHub).AddSubElement(obj);
                    }
                }
                foreach (IStringifiable obj in objectList)
                {
                    if (!(obj is InstrumentMapEntry))                   // load everything else now.
                    {
                        ((IStringifiable)m_FillHub).AddSubElement(obj);
                    }
                }
                return(true);
            }
            else
            {
                return(false);
            }
        }//TryLoadBooks()
Esempio n. 18
0
        }// TryCreateFromFile()

        //
        //
        //
        // ********************************************************
        // ****              TryCreateFromDatabase             ****
        // ********************************************************
        /// <summary>
        /// Called by the strategy hub thread to create strategies for a given group id.
        /// </summary>
        /// <param name="groupId">List of groups from which strategies are to be created. If null, no groups are loaded.</param>
        /// <param name="strategyIds">List of strategy ids to be created. If null, no strategyIds added.</param>
        /// <param name="aLog"></param>
        /// <param name="dataBaseReader"></param>
        /// <param name="strategyList"></param>
        /// <returns></returns>
        public static bool TryCreateFromDatabase(List <int> groupId, List <int> strategyIds, LogHub aLog, DatabaseReaderWriter dataBaseReader, out List <Strategy> strategyList)
        {
            strategyList = new List <Strategy>();                                    // place to put new strategies
            List <int> strategyIdList = new List <int>();                            // List of strategy ids we are going to create.


            try
            {
                //
                // Request strategy Ids from groupIds provided by user.
                //
                StrategiesQuery strategyQuery = new StrategiesQuery(groupId, strategyIds);
                if (!dataBaseReader.SubmitSync(strategyQuery))
                {
                    aLog.NewEntry(LogLevel.Error, "TryCreateFromDatabase: StrategiesQuery failed, cannot create strategies.");
                    return(false);
                }
                foreach (StrategyQueryItem aStrategyResult in strategyQuery.Results)
                {
                    strategyIdList.Add(aStrategyResult.StrategyId);                 // create list of all id's we care about.
                }
                //
                // Request all engines for those strategy ids.
                //
                StrategyEnginesQuery engineQuery = new StrategyEnginesQuery(strategyIdList);
                if (!dataBaseReader.SubmitSync(engineQuery))
                {
                    aLog.NewEntry(LogLevel.Error, "TryCreateFromDatabase: query failed try to find engines for {0} strategies, cannot create strategy", strategyIdList.Count);
                    return(false);
                }

                // Workspace
                Dictionary <int, IStringifiable> enginesWithIds                = new Dictionary <int, IStringifiable>();
                List <IStringifiable>            enginesWithOutIds             = new List <IStringifiable>();
                Dictionary <IStringifiable, StrategyEnginesQueryItem> itemList = new Dictionary <IStringifiable, StrategyEnginesQueryItem>();
                Dictionary <string, string> attributes = new Dictionary <string, string>();

                //
                // Now create each strategy
                //
                foreach (StrategyQueryItem strategyItem in strategyQuery.Results)
                {
                    int strategyId = strategyItem.StrategyId;

                    //
                    // Search for its engines, create them.
                    //
                    foreach (StrategyEnginesQueryItem item in engineQuery.Results)// Now create all its engines.
                    {
                        if (item.StrategyId == strategyId)
                        {   // This is an engine for this strategy.
                            // Validate that we can create this object.
                            Type type;
                            if (!Stringifiable.TryGetType(item.EngineType, out type))
                            {
                                aLog.NewEntry(LogLevel.Error, "TryCreateFromDatabase: {0} unknown type in strategy {1}.", item.EngineType, strategyId);
                                return(false);
                            }
                            if (!typeof(IStringifiable).IsAssignableFrom(type))
                            {
                                aLog.NewEntry(LogLevel.Error, "TryCreateFromDatabase: Type {0} does not implement IStringifiable!", type.FullName);
                                return(false);
                            }
                            // Create the new engine now.
                            IStringifiable newObj = (IStringifiable)Activator.CreateInstance(type);
                            attributes.Clear();                             // empty this for next use.
                            StringifiableReader.TryAddAllAttributes(item.AttributeString, ref attributes);
                            newObj.SetAttributes(attributes);               // load its attributes.


                            // Store this engine in appropriate list.
                            if (item.EngineId >= 0)
                            {   // This engine has Id#
                                if (enginesWithIds.ContainsKey(item.EngineId))
                                {
                                    aLog.NewEntry(LogLevel.Error, "TryCreateFromDatabase: EngineIds must be unique. Found dupe engineIds in strategy #{0}.", strategyId);
                                    return(false);
                                }
                                else
                                {
                                    enginesWithIds.Add(item.EngineId, newObj);
                                    itemList.Add(newObj, item);              // store the info about this new object
                                }
                            }
                            else
                            {                               // This engine has NO Id#.  (Which only means it can't be someone's parent.)
                                enginesWithOutIds.Add(newObj);
                                itemList.Add(newObj, item); // store the info about this new object
                            }
                        }// strategyId
                    }// next engine in list

                    //
                    // Now create the strategy.
                    //
                    Strategy newStrategy = new Strategy();
                    attributes.Clear();                                                                    // empty this now
                    StringifiableReader.TryAddAllAttributes(strategyItem.AttributeString, ref attributes); // extract attributes from string.
                    ((IStringifiable)newStrategy).SetAttributes(attributes);                               // load its attributes.
                    newStrategy.QueryItem = strategyItem;                                                  // give the strategy his database row, rather than giving him its contents.
                    //newStrategy.SqlId = strategyItem.StrategyId;
                    //newStrategy.StartTime = strategyItem.StartTime;
                    //newStrategy.EndTime = strategyItem.EndTime;
                    newStrategy.Name = strategyItem.Name;

                    //
                    // Add engines to their parents.
                    //
                    // Now that we have the strategy AND collected all of its engines,
                    // add engines to their parents, and then finally add engines without parents to the strategy.
                    // Notes:
                    //      1) Engines without a parent, have strategy as its parent.
                    //      2) Parent engines NEED to have an id, otherwise we couldn't know who their children are!
                    //      3) Children can have Id numbers or not... who knows.
                    // Search both lists for children.
                    foreach (IStringifiable engine in enginesWithOutIds)
                    {
                        StrategyEnginesQueryItem item;
                        IStringifiable           parentEngine;
                        if (itemList.TryGetValue(engine, out item) && item.ParentEngineId >= 0)
                        {   // This engine has a parent.
                            if (enginesWithIds.TryGetValue(item.ParentEngineId, out parentEngine))
                            {
                                parentEngine.AddSubElement(engine);         // added child to parent!
                            }
                        }
                        else
                        {   // This engine has NO parent!  It's parent is therefore the strategy!
                            ((IStringifiable)newStrategy).AddSubElement(engine);
                        }
                    }// next engine
                    foreach (IStringifiable engine in enginesWithIds.Values)
                    {
                        StrategyEnginesQueryItem item;
                        IStringifiable           parentEngine;
                        if (itemList.TryGetValue(engine, out item) && item.ParentEngineId >= 0)
                        {   // This engine has a parent.
                            if (enginesWithIds.TryGetValue(item.ParentEngineId, out parentEngine))
                            {
                                parentEngine.AddSubElement(engine);         // added child to parent!
                            }
                        }
                        else
                        {
                            ((IStringifiable)newStrategy).AddSubElement(engine);
                        }
                    }// next engine

                    strategyList.Add(newStrategy);                          // Store new strategy for output.

                    // Clean up
                    enginesWithIds.Clear();
                    enginesWithOutIds.Clear();
                    itemList.Clear();
                }//next strategyId
            }
            catch (Exception e)
            {
                StringBuilder msg = new StringBuilder();
                msg.AppendFormat("Exception: {0}\r\nContinue?", e.Message);
                System.Windows.Forms.DialogResult result = System.Windows.Forms.MessageBox.Show(msg.ToString(),
                                                                                                "StrategyMaker.TryCreateFromFile", System.Windows.Forms.MessageBoxButtons.OKCancel);
                if (aLog != null)
                {
                    aLog.NewEntry(LogLevel.Major, "StrategyMaker: Exception {0}", e.Message);
                }
                return(result == System.Windows.Forms.DialogResult.OK);
            }
            return(true);
        }
Esempio n. 19
0
        // *****************************************************************
        // ****                     Public Methods                      ****
        // *****************************************************************
        //
        //
        //
        /// <summary>
        /// Get drop file specified by user using a Ambre position recovery start date time.
        /// It loads the most recent drop file before this date time.
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="fillHubName"></param>
        /// <param name="selectedDateTime"></param>
        /// <param name="fillHub"></param>
        /// <returns></returns>
        public bool TryPlayDropFileForOneFillHub(string userName, string fillHubName, DateTime selectedDateTime, out AuditTrailFillHub fillHub)
        {
            fillHub = null;

            // Find the fill book with the closest date time to the input date time.
            string   currentFilePath    = null;
            string   pattern            = string.Format("*FillBooks_{0}_{1}.txt", userName, fillHubName);
            DateTime searchFileDateTime = DateTime.MinValue;
            bool     isBookFound        = false;

            // Get the directories with date format in the drop path.
            List <string> dirPathList = new List <string>(System.IO.Directory.GetDirectories(m_DropPath, "20*"));

            dirPathList.Sort();
            int    dirPtr = dirPathList.Count - 1;
            string currentDirPath;
            int    indexDir;

            // Create the file path list to store the searched files.
            List <string> filePathList = new List <string>();
            int           indexPath;
            int           filePtr;
            string        fileName;
            string        fileTime;
            string        fileDate;
            string        fileDateTime;

            // Start searching for the correct file. Loop through directory.
            while (!isBookFound && dirPtr >= 0)
            {
                currentDirPath = dirPathList[dirPtr];
                filePathList.Clear();
                filePathList.AddRange(System.IO.Directory.GetFiles(currentDirPath, pattern));
                if (filePathList.Count > 0)
                {
                    filePathList.Sort();
                    filePtr = filePathList.Count - 1;

                    // Loop through files in that directory.
                    while (!isBookFound && filePtr >= 0)
                    {
                        currentFilePath = filePathList[filePtr];
                        indexDir        = currentDirPath.LastIndexOf('\\');
                        indexPath       = currentFilePath.LastIndexOf('\\');
                        fileName        = currentFilePath.Substring(indexPath + 1, currentFilePath.Length - (indexPath + 1));
                        fileTime        = fileName.Substring(0, fileName.IndexOf("_"));
                        fileDate        = currentDirPath.Substring(indexDir + 1, currentDirPath.Length - (indexDir + 1));
                        fileDateTime    = string.Format("{0}{1}", fileDate, fileTime);

                        // Parse the date time out.
                        if (!DateTime.TryParseExact(fileDateTime, "yyyyMMddHHmmss", null, System.Globalization.DateTimeStyles.None, out searchFileDateTime))
                        {
                            Log.NewEntry(LogLevel.Major, "Failed to parse the file date time of {0}.", fileDateTime);
                        }
                        else
                        {
                            Log.NewEntry(LogLevel.Minor, "Successfully get the file path of {0}.", searchFileDateTime);
                            System.IO.FileInfo info = new System.IO.FileInfo(filePathList[filePtr]);
                            m_SelectedDropFileDateTime = searchFileDateTime;
                            isBookFound = searchFileDateTime <= selectedDateTime && info.Length > 0;
                        }

                        // If no desired file is found in this directory, find in the next directory.
                        filePtr--;
                        if (!isBookFound && filePtr < 0)
                        {
                            dirPtr--;
                            break;
                        }
                    }
                }
                else
                {
                    dirPtr--;
                }
            }

            // Check finally whether we have found the file.
            if (!isBookFound || string.IsNullOrEmpty(currentFilePath))
            {
                Log.NewEntry(LogLevel.Major, "Failed to locate the file before date time of {0}.", selectedDateTime);
                return(false);
            }
            else
            {
                // Start to load every element from the file.
                Log.NewEntry(LogLevel.Minor, "Start load elements from drop file.");
                List <Node> nodeList;
                try
                {
                    using (StringifiableReader reader = new StringifiableReader(currentFilePath))
                    {
                        nodeList = reader.ReadNodesToEnd();
                        reader.Close();
                    }
                }
                catch (Exception e)
                {
                    Log.NewEntry(LogLevel.Major, "TryPlayDropFileForOneFillHub: Strigifiable Reader Exception: {0}", e.Message);
                    return(false);
                }

                // Go through the node list backward, looking for the last fill hub node.
                Node   hubNode         = null;
                string fillHubTypeName = typeof(FillHub).FullName;
                int    ptr             = nodeList.Count - 1;
                while (ptr >= 0)
                {
                    if (hubNode != null)
                    {
                        nodeList.RemoveAt(ptr);
                    }
                    else if (nodeList[ptr].Name == fillHubTypeName)
                    {
                        hubNode = nodeList[ptr];
                        nodeList.RemoveAt(ptr);
                    }
                    ptr--;
                }

                // Extract the information from the fill hub node.
                fillHub = new AuditTrailFillHub(fillHubName, false);
                List <IStringifiable> objectList = new List <IStringifiable>();
                ((IStringifiable)fillHub).SetAttributes(hubNode.Attributes);
                foreach (IStringifiable subElement in hubNode.SubElements)
                {
                    IStringifiable obj = Stringifiable.Create((Node)subElement);
                    objectList.Add(obj);
                }

                foreach (Node anode in nodeList)
                {
                    IStringifiable obj = Stringifiable.Create(anode);
                    objectList.Add(obj);
                }

                // Load objects we found.
                if (objectList != null && objectList.Count > 0)
                {
                    foreach (IStringifiable obj in objectList)
                    {
                        if (obj is InstrumentMapEntry)
                        {
                            ((IStringifiable)fillHub).AddSubElement(obj);
                        }
                    }
                    foreach (IStringifiable obj in objectList)
                    {
                        if (!(obj is InstrumentMapEntry))
                        {
                            ((IStringifiable)fillHub).AddSubElement(obj);
                        }
                    }
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
        }
Esempio n. 20
0
        //
        //
        /// <summary>
        /// This should be overridden if the user does NOT want the default Gui Template.
        ///     1.) SetupGui = false will skip construction of the basic Engine Gui Template.
        /// </summary>
        protected override void SetupInitialize(IEngineHub myEngineHub, IEngineContainer engineContainer, int engineID, bool setupGui)
        {
            // Save information about local hub.
            m_EngineContainerId = engineContainer.EngineContainerID;
            if (myEngineHub is IService)
            {
                m_LocalEngineHubName = ((IService)myEngineHub).ServiceName;
            }
            m_LocalHub = (Hub)myEngineHub;

            // Locate our target remote hub/service.
            StrategyHub strategyHub = ((StrategyHub)myEngineHub);
            Hub         remoteHub   = null;

            if (strategyHub.SubscribeToRemoteEngineHub("ExecutionHub", engineContainer, out remoteHub))
            {
                m_RemoteEngineHub = remoteHub;
            }
            else
            {
                throw new Exception("Failed to locate remote hub.");
            }


            // Create the parameter table.
            Type remoteEngineType;

            if (Stringifiable.TryGetType(m_EngineClass, out remoteEngineType))
            {
                this.m_PInfo = CreateParameterInfo(myEngineHub, engineContainer.EngineContainerID, this.EngineID, remoteEngineType);
            }

            /*
             * // Create the gui specs.
             * if (setupGui)
             * {
             *  EngineGui engineGui = new EngineGui();
             *  engineGui.EngineID = this.EngineID;
             *  engineGui.DisplayName = this.EngineName;
             *  engineGui.EngineFullName = this.m_EngineClass;
             *  engineGui.ParameterList.AddRange(this.m_PInfo);
             *  m_EngineGuis.Add(engineGui);
             * }
             */
            //
            // Add sub-engines to the parent Strategy
            //
            //  They will be automatically initialized outside in StrategyHub loop
            //  that called us, since we will add new engine to the end of the list we are looping thru now.
            List <IStringifiable> subElements = m_Node.GetElements();

            if (subElements != null)
            {
                foreach (IStringifiable iObject in subElements)
                {                                // Engines that are beneath non-engines will not be found here.
                    if (iObject is RemoteEngine) // This remote engine will not need to broad its existance,
                    {
                        RemoteEngine subEngine = (RemoteEngine)iObject;
                        subEngine.m_IsSubEngine = true;                     // since it will be included in another engine (this one).
                        ((Strategy)engineContainer).TryAddEngine(subEngine, myEngineHub);
                    }
                }
            }
        }//SetupInitialize()
Esempio n. 21
0
        } // DropFillBooks()

        //
        //
        //
        //
        // *********************************************************
        // ****                 TryLoadBooks()                  ****
        // *********************************************************
        /// <summary>
        /// Reads the local drop file at the GetLocalPath() location named
        /// GetLocalFileName(), and obtains a list of IStringifiable.Nodes in that file.
        /// This list of nodes is examined (in reverse order) until the most recent FillHub
        /// node object is found.
        /// The fillhub node is broken down into its parts, which are actually created and
        /// store in another list.  The remaining nodes are also created and loading into
        /// the list as well.  (These are usually fills that came after the fillhub snapshot.)
        /// Version 4:  This is improved because it relies on read-methods from Stringifiable namespace.
        /// </summary>
        /// <returns>True upon success</returns>
        public bool TryLoadBooks(string loadFileName = "")
        {
            string filePath = string.Empty;

            if (string.IsNullOrEmpty(loadFileName))
            {
                filePath = string.Format("{0}{1}", GetLocalPath(), GetLocalFileName());
            }
            else
            {
                filePath = string.Format("{0}{1}", GetLocalPath(), loadFileName);
            }
            this.m_FillHub.Log.NewEntry(LogLevel.Major, "DropRules.TryLoadBooks: {0}", filePath);
            List <Node> nodeList;

            try
            {
                using (StringifiableReader reader = new StringifiableReader(filePath))
                {
                    nodeList = reader.ReadNodesToEnd();
                    reader.Close();
                }
            }
            catch (Exception e)
            {
                this.m_FillHub.Log.NewEntry(LogLevel.Error, "DropRules.TryLoadBooks: StrigifiableReader exception: {0}", e.Message);
                return(false);
            }
            // Go thru the nodes, looking for the last FillHub node.
            Node   hubNode         = null;
            string fillHubTypeName = m_FillHub.GetType().FullName;
            int    ptr             = nodeList.Count - 1;    // point to last element

            while (ptr >= 0)
            {
                if (hubNode != null)
                {                                           // We read backwards, and once we've passed the hub
                    nodeList.RemoveAt(ptr);                 // From here on out, we want to dump everthing!
                }
                else if (nodeList[ptr].Name == fillHubTypeName)
                {
                    hubNode = nodeList[ptr];
                    nodeList.RemoveAt(ptr);                 // remove the hub also; we already have a pointer to it.
                }
                ptr--;                                      // move backwards thru list
            }//wend ptr

            // Extract the info from the FillHub node.
            List <IStringifiable> objectList = new List <IStringifiable>();

            ((IStringifiable)m_FillHub).SetAttributes(hubNode.Attributes);  // initialize this hub!
            foreach (IStringifiable subElem in hubNode.SubElements)
            {
                IStringifiable obj = Stringifiable.Create((Node)subElem);
                objectList.Add(obj);                        // keep all the sub elements (below) we load them in specific order!
            }
            // Now create the objects we found after the hub - these are usually additional fills not in the fill hub.
            foreach (Node anode in nodeList)
            {
                IStringifiable obj = Stringifiable.Create(anode);
                objectList.Add(obj);
            }

            // Load objects we found.
            if (objectList != null && objectList.Count > 0)
            {
                foreach (IStringifiable obj in objectList)
                {
                    if (obj is InstrumentMapEntry)                      // load all InstrumentMapEntries first; needed to create fill books
                    {
                        ((IStringifiable)m_FillHub).AddSubElement(obj);
                    }
                }
                foreach (IStringifiable obj in objectList)
                {
                    if (!(obj is InstrumentMapEntry))                   // load everything else now.
                    {
                        ((IStringifiable)m_FillHub).AddSubElement(obj);
                    }
                }
                return(true);
            }
            else
            {
                return(false);
            }
        }//TryLoadBooks()
Esempio n. 22
0
 public string GetGuiTemplates()     // TODO: Add to IEngineContainer
 {
     return(Stringifiable.Stringify(m_EngineContainerGui));
 }
Esempio n. 23
0
 // *********************************************************
 // ****                     Enqueue()                   ****
 // *********************************************************
 public void Enqueue(IStringifiable iStringfiableObject)
 {
     m_DropWriter.RequestEnqueue(Stringifiable.Stringify(iStringfiableObject));
     m_LocalTimeLast = m_FillHub.Log.GetTime();                              // save time stamp of this latest entry.
 }
Esempio n. 24
0
 /// <summary>
 /// Dropping for all Raw fill events.
 /// </summary>
 public void EnqueueArchiveFill(FillEventArgs fillEventArg)
 {
     m_FillWriter.RequestEnqueue(Stringifiable.Stringify(fillEventArg, m_StringifyOverrideTable));
 }
Esempio n. 25
0
        }//ForeignServerDisconnect()

        //
        //
        #endregion // Foreign Servers Connection & Disconnection


        #region Process Incoming Socket Events
        // *********************************************************
        // ****             Process Socket Event()              ****
        // *********************************************************
        /// <summary>
        /// First stop in processing incoming socket messages.
        /// Here, we split them by "event type" and those of type "MessageReceived"
        /// are decoded, processed by ProcessRequestMessage() or ProcessConfirmMessage().
        /// </summary>
        /// <param name="eventArg"></param>
        private void ProcessSocketEvent(SocketEventArgs eventArg)
        {
            //Log.NewEntry(LogLevel.Minor, "ProcessSocketEvent: {0}", eventArg);
            int           id;
            ForeignServer fs;

            switch (eventArg.EventType)
            {
            //
            // Message Recieved
            //
            case SocketEventType.MessageReceived:
                List <IStringifiable> iStringList = null;                           // We expect msgs to be a list of Message objects.
                if (Stringifiable.TryCreate(eventArg.Message, out iStringList))
                {
                    foreach (IStringifiable istr in iStringList)
                    {
                        if (istr is Message)
                        {
                            Message msg = (Message)istr;
                            if (msg.State == MessageState.Request)
                            {
                                ProcessMessageRequests(eventArg, msg);              // requests from other servers
                            }
                            else
                            {
                                ProcessMessageResponses(eventArg, msg);             // responses to our requests
                            }
                        }
                        else
                        {
                            Log.NewEntry(LogLevel.Warning, "ProcessSocketEvent: Unknown data {0}.", istr);
                        }
                    }
                }
                else
                {
                    Log.NewEntry(LogLevel.Warning, "ProcessSocketEvent: Failed to extract Message from #{0}: {1} ", eventArg.ConversationId, eventArg.Message);
                }
                break;

            case SocketEventType.Connected:
                id = eventArg.ConversationId;
                fs = null;
                if (m_ServersConnected.TryGetValue(id, out fs))
                {       // We initiated this connection since we've already marked server as connected.
                    Log.NewEntry(LogLevel.Major, "ProcessSocketEvent: Server {1} connected to #{0}", eventArg.ConversationId, fs);
                }
                else
                {       // Initiated by foreigner, we must wait for a Credentials request to respond.
                    Log.NewEntry(LogLevel.Warning, "ProcessSocketEvent: Foreign server connecting #{0}. Waiting for his credentials.", id);
                }
                break;

            case SocketEventType.Disconnected:
                id = eventArg.ConversationId;
                fs = null;
                if (m_ServersConnected.TryGetValue(id, out fs))
                {
                    Log.NewEntry(LogLevel.Warning, "ProcessSocketEvent: Foreign server {0} disconnecting from #{1}.", fs, id);
                    ForeignServerDisconnect(fs);
                }
                else
                {
                    Log.NewEntry(LogLevel.Warning, "ProcessSocketEvent: Unknown foreign server disconnecting from #{0}.", id);
                }
                break;

            case SocketEventType.InternalMessage:
                id = eventArg.ConversationId;
                Log.NewEntry(LogLevel.Warning, "ProcessSocketEvent: Internal conversation #{0} msg: {1}.", id, eventArg.Message);
                break;

            default:
                Log.NewEntry(LogLevel.Major, "ProcessSocketEvent: Unknown event type {0}. Ignoring.", eventArg.EventType);
                break;
            }
        }//ProcessSocketEvent
Esempio n. 26
0
        }//UpdatePeriodic()

        //
        //
        #endregion// Hub Event Processing


        #region Foreign Servers Connection & Disconnection
        // *********************************************************
        // ****         Process Request Server Connect          ****
        // *********************************************************
        /// <summary>
        /// This processes the local request to connect to a foreign server via a socket.
        /// Requirements:
        ///     Request.Data = {ForeignConnection,
        /// </summary>
        /// <param name="requestEventArg"></param>
        private void ProcessRequestServerConnect(RequestEventArg <RequestCode> requestEventArg)
        {
            // Validate request
            if (requestEventArg.Data == null || requestEventArg.Data.Count < 1)
            {
                Log.NewEntry(LogLevel.Warning, "ProcessServerConnect: Missing data.");
                return;
            }
            if ((requestEventArg.Data[0] is ForeignConnection) == false)
            {
                Log.NewEntry(LogLevel.Warning, "ProcessServerConnect: Incorrect data.");
                return;
            }
            // Extract the ip address & create a new foreign server object for this connection.
            ForeignConnection conn = (ForeignConnection)requestEventArg.Data[0];

            System.Net.IPAddress ipAddress;
            if (string.IsNullOrEmpty(conn.IpAddress) || IPAddress.TryParse(conn.IpAddress, out ipAddress) == false)
            {
                ipAddress = System.Net.IPAddress.Loopback;              // Connect locally if no address provided
            }
            int portid;

            if (!int.TryParse(conn.Port, out portid))
            {
                Log.NewEntry(LogLevel.Warning, "ProcessServerConnect: Failed to extract port for connection. Failed to connection {0}.", conn);
                return;
            }
            // On first connection attempt, we make a foreign server.
            if (conn.Server == null)
            {
                conn.Server = new ForeignServer(this);
                string baseTag = string.Empty;
                if (m_AppServices.User != null)
                {
                    baseTag = m_AppServices.User.ToString();
                }
                conn.Server.UniqueTag = ForeignServer.CreateUniqueTag(baseTag, DateTime.Now);   // Upon first connection, we must create a unique tag.
            }
            // Connect foreign server
            int conversationID;

            if (m_Socket.TryConnect(ipAddress, portid, out conversationID))
            {
                ForeignServerConnect(conn.Server, conversationID);
                // Send credentials.
                SendMessage(conn.Server.ConversationId, GetMessage(MessageType.Credentials, MessageState.Request, conn.Server));
                // Optionally load & send config files to foreign server.
                if (string.IsNullOrEmpty(conn.m_ConfigFilename) == false)
                {
                    string fn = string.Format("{0}{1}", m_AppServices.Info.UserConfigPath, conn.m_ConfigFilename);
                    string stringifiedObjects = null;
                    if (File.Exists(fn))
                    {
                        try
                        {
                            using (StreamReader sr = new StreamReader(fn))
                            {
                                stringifiedObjects = sr.ReadToEnd();
                            }
                        }
                        catch (Exception e)
                        {
                            Log.NewEntry(LogLevel.Warning, "Config file {0} failed to load. Exception {1}", fn, e.Message);
                        }
                        List <IStringifiable> nodes = null;
                        if (Stringifiable.TryCreate(stringifiedObjects, out nodes, true))
                        {
                            SendMessage(conn.Server.ConversationId, GetMessage(MessageType.CreateServices, MessageState.Request, nodes));
                        }
                    }
                    else
                    {
                        Log.NewEntry(LogLevel.Warning, "Config file cannot be found: {0}", fn);
                    }
                }
            }
            else
            {   // Failed to connect.
                Log.NewEntry(LogLevel.Warning, "ProcessForeignServiceConnect: Failed to connect to {0}", conn.Server);
                if (!m_ServersDisconnected.Contains(conn.Server))
                {
                    m_ServersDisconnected.Add(conn.Server);
                }
            }
            // Exit
            m_Requests.Recycle(requestEventArg);;
        }//ProcessForeignServiceConnect()
Esempio n. 27
0
        } // GetMostRecentDropFile()

        //
        //
        //
        //
        private List <IStringifiable> Load2(string filePath)
        {
            List <IStringifiable> objectList = null;
            // 1.  Read the file backwards until we find the last startTag for the FillBook XML.
            // Search for the last block for the object.
            List <string> lines      = new List <string>();
            string        objectName = m_FillHub.GetType().FullName;
            string        startTag   = string.Format("<{0}", m_FillHub.GetType().FullName); // leave trailing parts off to allow for attributes.

            using (BackwardReader br = new BackwardReader(filePath))
            {
                bool isContinuing = true;
                while (!br.SOF && isContinuing)
                {
                    string aLine = br.Readline();
                    if (aLine.Contains(startTag))
                    {
                        m_FillHub.Log.NewEntry(LogLevel.Major, "DropRules.Load: Loading fill hub {0}", aLine);
                        isContinuing = false;
                        // Keep everything after the startTag, dump everything on the line
                        string[] truncatedLineParts = aLine.Split(new string[] { startTag }, StringSplitOptions.RemoveEmptyEntries);
                        string   truncatedLine      = string.Format("{0}{1}", startTag, truncatedLineParts[truncatedLineParts.Length - 1]);
                        lines.Add(truncatedLine);
                    }
                    else
                    {
                        lines.Add(aLine);
                    }
                } //wend
            }     //using reader
            lines.Reverse();                                            // since I read backwards, reverse the lines now.

            // 2. Now, create a string stream of the block, create nodes.
            StringBuilder msg = new StringBuilder();

            foreach (string aLine in lines)
            {
                msg.Append(aLine);
            }
            byte[] byteBuffer               = ASCIIEncoding.ASCII.GetBytes(msg.ToString());
            System.IO.MemoryStream stream   = new System.IO.MemoryStream(byteBuffer);
            StringifiableReader    reader   = new StringifiableReader(stream);
            List <IStringifiable>  nodeList = reader.ReadToEnd(true);



            // 3. Now convert these nodes into real objects.
            objectList = new List <IStringifiable>();
            foreach (IStringifiable iNode in nodeList)
            {
                Node node = (Node)iNode;
                if (node.Name.Contains("FillHub"))
                {   // We need the sub elements of the FillHub
                    foreach (IStringifiable subElem in node.SubElements)
                    {
                        IStringifiable obj = Stringifiable.DeStringify((Node)subElem);
                        objectList.Add(obj);
                    }
                }
                else
                {   // These are fill events and other things.
                    IStringifiable obj = Stringifiable.DeStringify((Node)iNode);
                    objectList.Add(obj);
                }
            }

            return(objectList);
        }// Load2()