// ***************************************************************** // **** Public Methods **** // ***************************************************************** // // //string filePath = string.Format("{0}{1}", this.Info.UserConfigPath, configFileName); // // public static bool TryCreateFromFile(string filePath, LogHub aLog, out List <Strategy> strategyList) { strategyList = new List <Strategy>(); // place to put new strategies try { List <IStringifiable> iStringObjects; using (StringifiableReader reader = new StringifiableReader(filePath)) { iStringObjects = reader.ReadToEnd(); } if (aLog != null) { aLog.NewEntry(LogLevel.Major, "StrategyMaker: Created {0} iStringifiable objects from {1}", iStringObjects.Count, filePath.Substring(filePath.LastIndexOf("\\") + 1)); } foreach (IStringifiable iStrObj in iStringObjects) { if (iStrObj is Strategy) { strategyList.Add((Strategy)iStrObj); } } } catch (Exception e) { StringBuilder msg = new StringBuilder(); msg.AppendFormat("Exception: {0}\r\nContinue? \r\n{1}", e.Message, e.StackTrace); 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); }// TryCreateFromFile()
// // //************************************************************ //**** TryCreateFromFile **** //************************************************************ /// <returns>false if faled</returns> public static bool TryCreateFromFile(string filePath, out DataHub dataHub) { dataHub = null; //DatabaseInfo dbInfo = null; try { string fullFilePath = string.Format("{0}{1}", Application.AppServices.GetInstance().Info.UserConfigPath, filePath); List <IStringifiable> iStringObjects; using (StringifiableReader reader = new StringifiableReader(fullFilePath)) { iStringObjects = reader.ReadToEnd(); } foreach (IStringifiable iStrObj in iStringObjects) { if (iStrObj is DataHub) { dataHub = (DataHub)iStrObj; } } //else if (iStrObj is DatabaseInfo) // dbInfo = (DatabaseInfo)iStrObj; } 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(), "ProductRequest.TryCreateFromFile", System.Windows.Forms.MessageBoxButtons.OKCancel); return(result == System.Windows.Forms.DialogResult.OK); } //if(dbInfo != null) // dataHub.m_DataBaseInfo = dbInfo; return(true); }
// ***************************************************************** // **** Public Methods **** // ***************************************************************** // //************************************************************ //**** TryCreateFromFile **** //************************************************************ /// <summary> /// Attempt to create a product request from a file using Istringifiable interface. /// </summary> /// <param name="filePath"></param> /// <param name="prodRequestList"></param> /// <returns>false if faled</returns> public static bool TryCreateFromFile(string filePath, out List <ProductRequest> prodRequestList) { prodRequestList = new List <ProductRequest>(); try { string fullFilePath = string.Format("{0}{1}", Application.AppServices.GetInstance().Info.UserConfigPath, filePath); List <IStringifiable> iStringObjects; using (StringifiableReader reader = new StringifiableReader(fullFilePath)) { iStringObjects = reader.ReadToEnd(); } foreach (IStringifiable iStrObj in iStringObjects) { if (iStrObj is ProductRequest) { prodRequestList.Add((ProductRequest)iStrObj); } } } 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(), "ProductRequest.TryCreateFromFile", System.Windows.Forms.MessageBoxButtons.OKCancel); return(result == System.Windows.Forms.DialogResult.OK); } return(true); }
// // Constructors // public ReadXMLBlocks() { InitializeComponent(); m_AppInfo = UV.Lib.Application.AppInfo.GetInstance(); // Example of how to use string fileName = string.Format("{0}Test.txt", m_AppInfo.UserPath); m_Reader = new StringifiableReader(fileName); List <IStringifiable> newObject = m_Reader.ReadToEnd(true); m_Reader.Close(); }
} // LoadMostRecentlySavedFillBookLoad() // private List <IStringifiable> ReadNodes(string filePath) { if (!System.IO.File.Exists(filePath)) { return(new List <IStringifiable>()); // return empty list. } // 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); return(nodeList); } // ReadNodes
}//ProcessServiceStateRequests() // // // ***************************************************************** // **** ProcessCreateStrategyRequest() **** // ***************************************************************** /// <summary> /// Process request to create new Engine. All the operations here /// are performed by the Hub thread. Once the Execution Strategy is /// ready to be launched, it is passed to its own thread, and then /// never again touched by the hub thread. /// </summary> /// <param name="eventArg">contains data</param> private void ProcessCreateStrategyRequest(EngineEventArgs eventArg) { // // Validate data in eventArg // if (eventArg.Status != EngineEventArgs.EventStatus.Request) { // I only respond to a request. return; } if (eventArg.DataObjectList == null || eventArg.DataObjectList.Count < 2) { Log.NewEntry(LogLevel.Warning, "ProcessCreateNewContainer: Failed to extract data."); return; } string xmlString = (string)eventArg.DataObjectList[0]; string strategyHubName = (string)eventArg.DataObjectList[1]; int engineCount = 0; if (!int.TryParse((string)eventArg.DataObjectList[2], out engineCount)) { engineCount = -1; } string containerTypeString = (string)eventArg.DataObjectList[3]; // // Obtain the EngineContainer // Dictionary <int, ThreadContainer> executionContainers = null; if (!m_ExecutionContainers.TryGetValue(strategyHubName, out executionContainers)) { // This is first container for this particular hub. Create a place for it. executionContainers = new Dictionary <int, ThreadContainer>(); if (string.IsNullOrEmpty(DefaultHubName)) { DefaultHubName = strategyHubName; } m_ExecutionContainers.Add(strategyHubName, executionContainers); } ThreadContainer container = null; if (!executionContainers.TryGetValue(eventArg.EngineContainerID, out container)) { Type containerType = (typeof(ThreadContainer).Assembly).GetType(containerTypeString); // convert string to exact type. container = (ThreadContainer)Activator.CreateInstance(containerType); // create instance container.EngineContainerID = eventArg.EngineContainerID; executionContainers.Add(container.EngineContainerID, container); if (engineCount >= 0) { container.TotalEngineCount = engineCount; } container.EngineContainerName = "need ContainerName"; // Locate the Strategy server this request came from IService iService; if (AppServices.GetInstance().TryGetService(strategyHubName, out iService) && iService is IEngineHub) { container.RemoteEngineHub = (IEngineHub)iService; } // TODO: Continue initializing the container } // // Create the Engine. // bool isSuccess = true; byte[] byteArray = Encoding.ASCII.GetBytes(xmlString); using (System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray)) { try { StringifiableReader stringReader = new StringifiableReader(stream); List <IStringifiable> objects = stringReader.ReadToEnd(); foreach (IStringifiable iObject in objects) { if (iObject is Engine) { if (container.TryAddEngine((Engine)iObject)) { //Engine engine = (Engine)iObject; //int engineID = engine.EngineID; // These are created via attributes (so they coincide with values set by StrategyHub). //((Engine)iObject).SetupInitialize(this, container, engineID); } else { isSuccess = false; Log.NewEntry(LogLevel.Warning, "ProcessCreateEngine: Failed to add {0} to container {1}.", iObject, container); } } } } catch (Exception ex) { isSuccess = false; Log.NewEntry(LogLevel.Warning, "ProcessCreateEngine: {0}", ex.Message); } }//using if (isSuccess == false) { return; } // Finalize if (engineCount == container.EngineList.Count && container.IOrderEngine != null) { SetupAndStartContainer(container); // finish initialization, add listener and start } else { } }//ProcessCreateEngine()
} // 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()
} // 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()
} // 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()
// ***************************************************************** // **** 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); } } }
}// 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); }
// ***************************************************************** // **** Constructors **** // ***************************************************************** public ReconcilerForm(string[] cmdLineArgs) { InitializeComponent(); AppInfo m_AppInfo = AppInfo.GetInstance("Breconcile", true); m_AppInfo.RequestShutdownAddHandler(new EventHandler(RequestShutDown)); // register my handler as the shutdown request handler. string filePath = string.Empty; if (cmdLineArgs != null && cmdLineArgs.Length > 0) { filePath = string.Format("{0}{1}", m_AppInfo.UserConfigPath, cmdLineArgs[0].Trim()); } else { filePath = string.Format("{0}ReconcilerConfig.txt", m_AppInfo.UserConfigPath); } // here is temp hard code config file address // filePath = "\\\\fileserver\\Users\\DV_Ambre\\AmbreUsers\\dvbre\\Config\\ReconcilerConfig.txt"; // Create the services defined in the config file. using (StringifiableReader reader = new StringifiableReader(filePath)) { List <IStringifiable> objectList = reader.ReadToEnd(); foreach (IStringifiable obj in objectList) { if (obj is ReconcilerTaskHub) { ReconcilerTaskHub newHub = (ReconcilerTaskHub)obj; m_ReconcilerTaskHubs.Add(newHub); if (Log == null) { Log = newHub.Log; // accept first Log as the form's log. } newHub.TaskCompleted += new EventHandler(Reconciler_RequestCompleted); newHub.Stopping += new EventHandler(Reconciler_Stopping); } } } // Log start up. if (Log != null) { Log.NewEntry(LogLevel.Minor, "ReconcilerForm: Running config file {0}", filePath); if (Log.BeginEntry(LogLevel.Minor, "ReconcilerForm: {0} TaskHubs: ", m_ReconcilerTaskHubs.Count)) { foreach (ReconcilerTaskHub hub in m_ReconcilerTaskHubs) { Log.AppendEntry("<{0}>", hub.GetAttributes()); } } } // Start hubs foreach (ReconcilerTaskHub hub in m_ReconcilerTaskHubs) { hub.Start(); } }