示例#1
0
        /// <summary>Updates the tree by recalculating the cumulative node information for this node and the nodes above as needed.</summary>
        /// <param name="forceUpdate">Set this to true to force that this node gets recalculated even if its IsTreeUpdateNeeded flag has not already been set.</param>
        /// <param name="issueEmitter">provides the IMesgEmitter that will be used to report issues found while updating or rebuilding the tree.</param>
        public void UpdateTree(bool forceUpdate = false, Logging.IMesgEmitter issueEmitter = null)
        {
            issueEmitter = issueEmitter ?? Logging.NullEmitter;

            if (IsTreeBuildNeeded)
                BuildTree(updateAtEnd: false, issueEmitter: issueEmitter);

            if (!IsTreeUpdateNeeded && !forceUpdate)
                return;

            IsTreeUpdateNeeded = false;

            Refresh();

            TreeContentsSize = Length;          // this is only non-zero for IsFile objects.
            TreeItemCount = 1;
            TreeFileCount = (IsFile ? 1 : 0);

            foreach (var entry in UpdateAndGetSortedDirContentsNodeArray())
            {
                if (entry.IsTreeBuildNeeded)
                    entry.BuildTree(issueEmitter: issueEmitter);
                else if (entry.IsTreeUpdateNeeded)
                    entry.UpdateTree(issueEmitter: issueEmitter);

                TreeContentsSize += entry.TreeContentsSize;
                TreeItemCount += entry.TreeItemCount;
                TreeFileCount += entry.TreeFileCount;
            }
        }
            public PerformanceCounterTracker(Logging.IBasicLogger logger, PerformanceCounterSpec pcs)
            {
                this.pcs = pcs;
                pcc      = pcs.GetPerformanceCounterCategory();

                useRawPerfCtrValue = pcs.UseRawValue;

                gpInfo = new MDRF.Writer.GroupPointInfo()
                {
                    Name     = pcs.PointName,
                    ValueCST = ContainerStorageType.None,
                };

                try
                {
                    var categorySample = pcc.ReadCategory();
                    Service(logger, categorySample, true);
                }
                catch (System.Exception ex)
                {
                    Logging.IMesgEmitter emitter = (logger == null ? Logging.NullEmitter : logger.Info);

                    emitter.Emit("{0} for '{1}' generated unexpected exception: {2}", CurrentMethodName, gpInfo.Name, ex.ToString(ExceptionFormat.TypeAndMessage));

                    isUsable = false;
                }
            }
示例#3
0
        /// <summary>
        /// Update this object's ConfigItem marked public properties from corresponingly named config keys (using the namePrefix)
        /// </summary>
        public PassiveTimers Setup(string namePrefix, Logging.IMesgEmitter issueEmitter, Logging.IMesgEmitter valueEmitter)
        {
            ConfigValueSetAdapter <PassiveTimers> adapter = new ConfigValueSetAdapter <PassiveTimers>()
            {
                ValueSet = this, SetupIssueEmitter = issueEmitter, UpdateIssueEmitter = issueEmitter, ValueNoteEmitter = valueEmitter
            }.Setup(namePrefix);

            return(this);
        }
示例#4
0
        /// <summary>
        /// Constructs a buffer of the requested <paramref name="bufferSize"/>.
        /// </summary>
        public Buffer(int bufferSize, BufferPool bufferPool = null, Logging.IMesgEmitter stateEmitter = null)
            : this(stateEmitter)
        {
            this.bufferPool = bufferPool;

            byteArray     = new byte [bufferSize];
            byteArraySize = bufferSize;

            byteCount = header.Length;
        }
示例#5
0
        /// <summary>
        /// Uses Modular.Config to Setup portions of this instance.  Requires and issueEmitter and a valueEmitter to use (use null or Logging.NullEmitter to suppress output).
        /// Prefixes this object's Name with period in front of the annotated members that can be filled in from config keys.  All such config keys are ReadOnlyOnce = true and IsOptional = true.
        /// </summary>
        public ScanEnginePartConfig Setup(Logging.IMesgEmitter issueEmitter, Logging.IMesgEmitter valueEmitter)
        {
            ConfigValueSetAdapter <ScanEnginePartConfig> adapter;

            Name = Name ?? String.Empty;

            // update values from any lpmInstanceName derived keys.
            adapter = new ConfigValueSetAdapter <ScanEnginePartConfig>()
            {
                ValueSet = this, SetupIssueEmitter = issueEmitter, UpdateIssueEmitter = issueEmitter, ValueNoteEmitter = valueEmitter
            }.Setup(Name + ".");

            return(this);
        }
示例#6
0
        public BCRSimPartConfigBase Setup(Logging.IMesgEmitter issueEmitter, Logging.IMesgEmitter valueEmitter)
        {
            ConfigValueSetAdapter <BCRSimPartConfigBase> adapter;

            BCRName = BCRName ?? String.Empty;

            // update values from any lpmInstanceName derived keys.
            adapter = new ConfigValueSetAdapter <BCRSimPartConfigBase>()
            {
                ValueSet = this, SetupIssueEmitter = issueEmitter, UpdateIssueEmitter = issueEmitter, ValueNoteEmitter = valueEmitter
            }.Setup(BCRName + ".");

            return(this);
        }
示例#7
0
        /// <summary>
        /// This method generates log messages for each of the groups in the current table and then for the [Global] group.
        /// </summary>
        public void DumpTableToLog(string reason, Logging.IMesgEmitter dumpTableEmitter = null)
        {
            dumpTableEmitter = dumpTableEmitter ?? DefaultDumpEmitter;

            lock (mutex)
            {
                dumpTableEmitter.Emit("{0}: {1} [table size: {2}]", Fcns.CurrentMethodName, reason, groupTrackingInfoDictionary.Count);

                foreach (var tracker in groupTrackingInfoDictionary.Values)
                {
                    dumpTableEmitter.Emit("{0}", tracker);
                }

                dumpTableEmitter.Emit("{0}", globalTrackingInfo);
            }
        }
示例#8
0
        /// <summary>
        /// Attempts to delete files/directories given in the list of DirectoryEntryInfo items to prune.
        /// <para/>returns the number of items that were successfully deleted.
        /// </summary>
        /// <param name="pruneItemList">Gives the list of DirectoryEntryInfo items that are to be removed from the file system.</param>
        /// <param name="deleteEmitter">Gives the IMesgEmitter that will recieve messages about the successfull deletions</param>
        /// <param name="issueEmitter">Gives the IMesgEmitter that will receive any messages about failures while attempting to delete each item.</param>
        /// <param name="reason">Gives the string description for the reason that these items are to be deleted.  Null or Empty will be replaced with [NoReasonGiven]</param>
        /// <returns>The number of items that were successfully deleted.</returns>
        public int DeletePrunedItems(List <DirectoryEntryInfo> pruneItemList, Logging.IMesgEmitter deleteEmitter, Logging.IMesgEmitter issueEmitter, string reason = null)
        {
            int deletedItemCount = 0;           // actually the count of the number of items that we have attempted to delete

            reason = reason.MapNullOrEmptyTo("[NoReasonGiven]");

            for (int idx = 0; idx < pruneItemList.Count; idx++)
            {
                DirectoryEntryInfo entryToDelete = pruneItemList[idx];

                double ageInDays = entryToDelete.CreationAge.TotalDays;

                if (entryToDelete.IsFile)
                {
                    try
                    {
                        System.IO.File.Delete(entryToDelete.Path);
                        deletedItemCount++;
                        deleteEmitter.Emit("Pruned file:'{0}', size:{1}, age:{2:f6} days, reason:{3}", entryToDelete.Path, entryToDelete.Length, ageInDays, reason);
                    }
                    catch (System.Exception ex)
                    {
                        issueEmitter.Emit("Prune failed to delete file:'{0}', error:'{1}'", entryToDelete.Path, ex.Message);
                    }
                }
                else if (entryToDelete.IsDirectory)
                {
                    try
                    {
                        System.IO.Directory.Delete(entryToDelete.Path);
                        deletedItemCount++;
                        deleteEmitter.Emit("Pruned directory:'{0}', size:{1}, age:{2:f6} days, reason:{3}", entryToDelete.Path, entryToDelete.Length, ageInDays, reason);
                    }
                    catch (System.Exception ex)
                    {
                        issueEmitter.Emit("Prune failed to delete directory:'{0}', error:'{1}'", entryToDelete.Path, ex.Message);
                    }
                }
                else
                {
                    issueEmitter.Emit("Prune cannot delete unknown tree node at path:'{0}', reason:{1}", entryToDelete.Path, reason);
                }
            }

            return(deletedItemCount);
        }
示例#9
0
        public Message SetState(QpcTimeStamp qpcTimeStamp, MessageState state, string reason, bool autoReleaseByState = false)
        {
            MessageState entryState = State;

            reason = reason ?? "NoReasonGiven";

            State     = state;
            TimeStamp = qpcTimeStamp;
            Reason    = reason;

            Logging.IMesgEmitter emitterToUse = StateEmitter;

            switch (state)
            {
            case MessageState.Initial:
            case MessageState.Released:
                ReturnBuffersToPool(qpcTimeStamp);
                break;

            case MessageState.Delivered:
                if (autoReleaseByState)
                {
                    ReturnBuffersToPool(qpcTimeStamp);
                }
                break;

            case MessageState.Failed:
                emitterToUse = IssueEmitter;
                break;

            case MessageState.SendPosted:
                SendPostedTimeStamp = qpcTimeStamp;
                break;

            default:
                break;
            }

            if (emitterToUse.IsEnabled)
            {
                emitterToUse.Emit("Message_{0:x4} State changed to {1} [from: {2}, reason: {3}]", instanceNum & 0x0ffff, state, entryState, reason);
            }

            return(this);
        }
示例#10
0
        /// <summary>
        /// Constructor.
        /// <para/>defaultBufferSize == 1024.  Usable space is 1024-26 == 998
        /// </summary>
        public BufferPool(string name, int maxTotalSpaceInBytes = 1024000, int bufferSize = DefaultBufferSize, bool clearBufferContentsOnRelease = false, Logging.IMesgEmitter bufferStateEmitter = null, INamedValueSet configNVS = null, string configNVSKeyPrefix = "BufferPool.")
        {
            Name = name;

            if (configNVS != null)
            {
                maxTotalSpaceInBytes = configNVS["{0}MaxTotalSpaceInBytes".CheckedFormat(configNVSKeyPrefix)].VC.GetValue(defaultValue: maxTotalSpaceInBytes, rethrow: false);
                bufferSize           = configNVS["{0}BufferSize".CheckedFormat(configNVSKeyPrefix)].VC.GetValue(defaultValue: bufferSize, rethrow: false);
            }

            MaxTotalSpaceInBytes = maxTotalSpaceInBytes;
            ChangeBufferSize(QpcTimeStamp.Now, bufferSize);
            _bufferSize = bufferSize;
            ClearBufferContentsOnRelease = clearBufferContentsOnRelease;
            BufferStateEmitter           = bufferStateEmitter;

            bufferCount = 0;
        }
示例#11
0
        /// <summary>Requests the node to build its sub-tree and allows the caller to indicate if it should be updated after being built.</summary>
        public void BuildTree(bool updateAtEnd = true, Logging.IMesgEmitter issueEmitter = null, bool forceBuildTree = false)
        {
            try
            {
                // If the tree has already need built and does not have its IsTreeBuildNeeded flag set then do not (re)build this node
                if (!IsTreeBuildNeeded && !forceBuildTree)		// this flag should only be set for directories
                    return;

                issueEmitter = issueEmitter ?? Logging.NullEmitter;

                if (!IsDirectory)
                {
                    issueEmitter.Emit("BuildTree failed: Tree Path '{0}' is neither a normal file nor a normal directory.", Path);
                }

                ClearSubTreeInformation();

                sortedDirContentsNodeArray = null;
                System.IO.Directory.GetFileSystemEntries(Path).Select(path => new DirectoryTreeEntryNode(path, this)).DoForEach(node => sortedDirContentsNodeSet.Add(node));

                SetTreeUpdateNeeded(true);

                foreach (var entry in UpdateAndGetSortedDirContentsNodeArray())
                {
                    if (entry.IsExistingDirectory)
                        entry.BuildTree(issueEmitter: issueEmitter);
                    else if (!entry.IsExistingFile)
                        issueEmitter.Emit("BuildTree issue: Sub Tree Path '{0}' is neither a normal file nor a normal directory.", entry.Path);
                }

                // we have completed the tree build for this level and the levels below it
                IsTreeBuildNeeded = false;

                // update the tree to update our summary fields - only scan the top level as the 
                if (updateAtEnd)
                    UpdateTree(issueEmitter: issueEmitter);
            }
            catch (System.Exception ex)
            {
                issueEmitter.Emit("BuiltTree failed at path:'{0}' error:{1}", path, ex);
            }
        }
            public void Service(Logging.IBasicLogger logger, InstanceDataCollectionCollection categorySample, bool rethrow = false)
            {
                if (!isUsable)
                {
                    return;
                }

                try
                {
                    InstanceDataCollection instanceDataCollection = categorySample[pcs.CounterName];
                    InstanceData           instanceData           = instanceDataCollection[pcs.InstanceName.MapNullToEmpty()]; // use empty string for counters that only have one value

                    CounterSample counterSample = instanceData.Sample;

                    if (!useRawPerfCtrValue)
                    {
                        gpInfo.VC = new ValueContainer(CounterSample.Calculate(lastCounterSample, counterSample));
                    }
                    else
                    {
                        gpInfo.VC = new ValueContainer(counterSample.RawValue);
                    }

                    lastCounterSample = counterSample;

                    logExceptionElevationHoldoffTimer.StopIfNeeded();
                }
                catch (System.Exception ex)
                {
                    bool useHighLevelMesg = (logExceptionElevationHoldoffTimer.IsTriggered || !logExceptionElevationHoldoffTimer.Started);
                    logExceptionElevationHoldoffTimer.StartIfNeeded();

                    Logging.IMesgEmitter emitter = (logger == null ? Logging.NullEmitter : (useHighLevelMesg ? logger.Info : logger.Trace));

                    emitter.Emit("{0} for '{1}' generated exception: {2}", CurrentMethodName, gpInfo.Name, ex.ToString(ExceptionFormat.TypeAndMessage));
                }
            }
示例#13
0
                    /// <summary>
                    /// Modular.Config helper setup method.  Constructs a FileRotationLoggingConfig from the matching contents in this object and then
                    /// calls its UpdateFromModularConfig method to fill in its values from modular config.  Finally this method updates the localy stored
                    /// values from the updated FileRotationLoggingConfig contents and reconstructs the LineFormat
                    /// </summary>
                    public Config UpdateFromModularConfig(string configKeyPrefixStr, Logging.IMesgEmitter issueEmitter = null, Logging.IMesgEmitter valueEmitter = null, IConfig configInstance = null)
                    {
                        FileRotationLoggingConfig frlConfig = new FileRotationLoggingConfig(Name, DirPath)
                        {
                            dirPath              = DirPath,
                            fileNamePrefix       = FileNamePrefix,
                            fileNameSuffix       = FileNameExtension,
                            logGate              = LogGate,
                            includeQpcTime       = IncludeQpc,
                            includeNamedValueSet = IncludeNamedValueSet,
                            includeThreadInfo    = IncludeThreadInfo,
                            advanceRules         = AdvanceRules,
                            purgeRules           = new FileRotationLoggingConfig.PurgeRules(PruneRules),
                            mesgQueueSize        = MesgQueueSize,
                        };

                        frlConfig.UpdateFromModularConfig(configKeyPrefixStr, issueEmitter: issueEmitter, valueEmitter: valueEmitter, configInstance: configInstance);

                        DirPath           = frlConfig.dirPath;
                        FileNamePrefix    = frlConfig.fileNamePrefix;
                        FileNameExtension = frlConfig.fileNameSuffix;
                        LogGate           = frlConfig.logGate;

                        IncludeQpc           = frlConfig.includeQpcTime;
                        IncludeNamedValueSet = frlConfig.includeNamedValueSet;
                        IncludeThreadInfo    = frlConfig.includeThreadInfo;

                        AdvanceRules = frlConfig.advanceRules;

                        PruneMode  = File.DirectoryTreePruningManager.PruneMode.PruneDirectories;
                        PruneRules = new File.DirectoryTreePruningManager.PruneRules(frlConfig.purgeRules);

                        MesgQueueSize = frlConfig.mesgQueueSize;

                        return(this);
                    }
示例#14
0
        /// <summary>
        /// Used to inform manager about the addition of another file or diretory which should be monitored by the manager (and which should eventually be pruned).
        /// This method may also be used to inform the manager that the file contents might have changed.
        /// </summary>
        public void NotePathAdded(string pathToAdd, Logging.IMesgEmitter issueEmitter)
        {
            try
            {
                string fullPathToAdd   = System.IO.Path.GetFullPath(pathToAdd);
                string workingRootPath = treeRootEntry.Path;

                string   relativePathPart     = String.Empty;
                string[] relativePathSegments = null;

                if (fullPathToAdd.StartsWith(workingRootPath))
                {
                    // convert the full path into a relative path
                    relativePathPart = @".{0}".CheckedFormat(fullPathToAdd.Substring(workingRootPath.Length));

                    relativePathSegments = relativePathPart.Split(new char[] { System.IO.Path.DirectorySeparatorChar, System.IO.Path.AltDirectorySeparatorChar }).Skip(1).ToArray();
                }

                string regeneratedFullPath = System.IO.Path.GetFullPath(System.IO.Path.Combine(workingRootPath, relativePathPart));

                if (!String.IsNullOrEmpty(relativePathPart) && (regeneratedFullPath == fullPathToAdd))
                {
                    treeRootEntry.AddRelativePath(relativePathSegments, issueEmitter);
                }
                else
                {
                    issueEmitter.Emit("NotePathAdded '{0}' failed: given path is a proper subpath under under the monitored path '{1}'", pathToAdd, workingRootPath);
                }

                treeRootEntry.UpdateTree(issueEmitter);
            }
            catch (System.Exception ex)
            {
                issueEmitter.Emit("NotePathAdded '{0}' failed: error:'{1}'", pathToAdd, ex);
            }
        }
示例#15
0
        public LPMSimPartConfigBase Setup(Logging.IMesgEmitter issueEmitter, Logging.IMesgEmitter valueEmitter)
        {
            ConfigValueSetAdapter <LPMSimPartConfigBase> adapter;

            LPMName = LPMName ?? String.Empty;

            // update values from any LPAll derived kesy.  We never log issues when trying to read from LPAll prefixed keys.
            adapter = new ConfigValueSetAdapter <LPMSimPartConfigBase>()
            {
                ValueSet = this, SetupIssueEmitter = Logging.NullEmitter, UpdateIssueEmitter = Logging.NullEmitter, ValueNoteEmitter = valueEmitter
            }.Setup("LPAll.");
            MapResultPattern.UpdateFromModularConfig("LPAll.MapResultPattern.", Logging.NullEmitter, valueEmitter);
            CarrierTypeSpec.UpdateFromModularConfig("LPAll.CarrierTypeSpec.", Logging.NullEmitter, valueEmitter);

            // update values from any lpmInstanceName derived keys.
            adapter = new ConfigValueSetAdapter <LPMSimPartConfigBase>()
            {
                ValueSet = this, SetupIssueEmitter = issueEmitter, UpdateIssueEmitter = issueEmitter, ValueNoteEmitter = valueEmitter
            }.Setup(LPMName + ".");
            MapResultPattern.UpdateFromModularConfig(LPMName + ".MapResultPattern.", issueEmitter, valueEmitter);
            CarrierTypeSpec.UpdateFromModularConfig(LPMName + ".CarrierTypeSpec.", issueEmitter, valueEmitter);

            return(this);
        }
示例#16
0
        public ProcessPerformancePartConfig Setup(string prefixName = "ProcessPerf.", IConfig config = null, Logging.IMesgEmitter issueEmitter = null, Logging.IMesgEmitter valueEmitter = null)
        {
            var adapter = new ConfigValueSetAdapter <ProcessPerformancePartConfig>(config)
            {
                ValueSet = this, SetupIssueEmitter = issueEmitter, UpdateIssueEmitter = issueEmitter, ValueNoteEmitter = valueEmitter
            }.Setup(prefixName);

            return(this);
        }
示例#17
0
 /// <summary>
 /// Obtains the oldest DirectoryEntryItem, or Items from the tree that are to be pruned next.
 /// Actual list returned depends on the selected PruneMode in that it will attempt to remove the oldest file when pruning Files
 /// or it will attempt to delete all of the files in the directory with the oldest file, up to the given deletion limit count.
 /// In either case it will also include any directories above the first chosen item that become empty after all prior selected items
 /// have been deleted.
 /// </summary>
 /// <param name="pruneItemList">List to which new that have been removed from the tree are added - these items must be deleted from the file system separately</param>
 /// <param name="issueEmitter">Gives the IMesgEmitter to which error messages and other Tree traversal issues are given during this process.</param>
 public void ExtractNextListOfIncrementalItemsToPrune(List <DirectoryEntryInfo> pruneItemList, Logging.IMesgEmitter issueEmitter)
 {
     if (config.PruneMode == PruneMode.PruneDirectories)
     {
         treeRootEntry.AppendAndRemoveOldestTreeDirectory(pruneItemList, config.MaxEntriesToDeletePerIteration, issueEmitter);
     }
     else
     {
         treeRootEntry.AppendAndRemoveOldestTreeItem(pruneItemList, issueEmitter);
     }
 }
示例#18
0
        /// <summary>
        /// Appends a list of the DirectoryEntryInfo items for the tree item's that have been removed from the memory copy of the tree.  
        /// Caller is expected to attempt to delete the actual files/directories.
        /// Performs UpdateTree prior to returning.
        /// </summary>
        public void AppendAndRemoveOldestTreeDirectory(List<DirectoryEntryInfo> pruneItemList, int maxEntriesToDeletePerIteration, Logging.IMesgEmitter issueEmitter = null)
        {
            issueEmitter = issueEmitter ?? Logging.NullEmitter;

            Stack<DirectoryTreeEntryNode> nodeStack = new Stack<DirectoryTreeEntryNode>();

			DirectoryTreeEntryNode currentEntry = this;

			// create a stack of the entries from the root down to the oldest leaf (file or directory).  
			//	Each level in the stack retains the current entry at that level, the parent entry and the index in the parent entries content vector at which you will find the current entry
			while (currentEntry != null)
			{
                DirectoryTreeEntryNode nextEntryDown = currentEntry.OldestDirContentsNodeEntry;

                if (nextEntryDown != null)
				{
					nodeStack.Push(nextEntryDown);

					currentEntry = nextEntryDown;
				}
				else if (!currentEntry.IsRootNode)
				{
					break;	// reached the bottom of the search path
				}
				else
				{
                    // 
					// we can never remove the root item - there is nothing further to prune.
					return;
				}
			}

			// start at the bottom of the stack and determine if that entry can be removed (or not).  If so then:
			//	A) added it to the list of entries to remove
			//	B) remove it from its parrent's entry content vector
			//	and then repeate for the each level up in the stack until an entry is encountered that cannot be deleted (is not an empty directory after the sub item has been removed.)

            while (nodeStack.Count != 0)
            {
                DirectoryTreeEntryNode topStackNode = nodeStack.Pop();
                DirectoryTreeEntryNode topStackNodeParentItem = topStackNode.ParentDirEntry;

                bool isFile = topStackNode.IsFile;
                bool isNormalFile = topStackNode.IsExistingFile;
                bool isNormalDirectory = topStackNode.IsExistingDirectory;
                bool isEmptyDirectory = topStackNode.IsEmptyDirectory;

                string skipReason = null;
                if (!isNormalFile && !isNormalDirectory)
                    skipReason = Fcns.CheckedFormat("Skipping non-normal node at path:'{0}'", Path);

                bool skipIt = (skipReason != null);

                if (skipIt)
                    issueEmitter.Emit(skipReason);

                bool removeIt = (isNormalFile || isEmptyDirectory) && !skipIt;
                bool removeItFromTree = removeIt;

                if (!removeIt && !skipIt)
                    break;						// once we have reached a level where nothing more can be removed (ie it is not an empty directory), we stop iterating up the stack.

                if (removeItFromTree)
                {
                    if (removeIt)
                        pruneItemList.Add(topStackNode);		// append a copy of the topStackNode as a DirectoryEntryInfo object onto the pruneItemList

                    topStackNodeParentItem.sortedDirContentsNodeArray = null;

                    topStackNodeParentItem.sortedDirContentsNodeSet.Remove(topStackNode);
                    RootDirectoryTreeEntryNodeDictionary.Remove(topStackNode.Path);

                    if (removeIt && isFile && maxEntriesToDeletePerIteration > 1)
                    {
                        // identify the other n oldest items in this directory and add them to the delete list
                        while (pruneItemList.Count < maxEntriesToDeletePerIteration)
                        {
                            DirectoryTreeEntryNode nextOldestEntryInCurrentDir = topStackNodeParentItem.OldestDirContentsNodeEntry;

                            if (nextOldestEntryInCurrentDir == null)
                                break;

                            // stop adding to the current list of items to delete once we reach any non-normal file - special cases will be covered on the next go around.
                            if (!nextOldestEntryInCurrentDir.IsExistingFile)
                                break;

                            // append a copy of the nextEntryInCurrentDir as a DirectoryEntryInfo object
                            pruneItemList.Add(nextOldestEntryInCurrentDir);

                            // remove the pointer to the entry that just got added to the delete list and then delete the entry
                            topStackNodeParentItem.sortedDirContentsNodeSet.Remove(nextOldestEntryInCurrentDir);
                            RootDirectoryTreeEntryNodeDictionary.Remove(nextOldestEntryInCurrentDir.Path);

                            if (topStackNodeParentItem.IsEmptyDirectory)
                                break;
                        }
                    }

                    topStackNodeParentItem.SetTreeUpdateNeeded(true);
                }
            }

			UpdateTree(issueEmitter);
        }
示例#19
0
 /// <summary>
 /// Appends a list of the DirectoryEntryInfo items for the tree item's that have been removed from the memory copy of the tree.  
 /// Caller is expected to attempt to delete the actual files/directories.
 /// Performs UpdateTree prior to returning.
 /// </summary>
 public void AppendAndRemoveOldestTreeItem(List<DirectoryEntryInfo> pruneItemList, Logging.IMesgEmitter issueEmitter = null)
 {
     AppendAndRemoveOldestTreeDirectory(pruneItemList, 1, issueEmitter);
 }
示例#20
0
        /// <summary>
        /// Addes a new node in the tree at the relative location under the given node produced by iteratavely concactinating the given list of relative path elements
        /// onto the full path to this node and treversing downward until the relative path elements have been used up.  
        /// Performs UpdateTree prior to returning.
        /// </summary>
        public void AddRelativePath(IList<String> relativePathElementList, Logging.IMesgEmitter issueEmitter = null)
        {
            issueEmitter = issueEmitter ?? Logging.NullEmitter;

            int relativePathElementListSize = relativePathElementList.Count;
            if (relativePathElementListSize <= 0)
            {
                issueEmitter.Emit("AddRelativePath failed at node:'{0}': given relative path list is empty", Path);
                return;
            }

			DirectoryTreeEntryNode treeScanEntry = this;

			for (int rPathElemIdx = 0; ((treeScanEntry != null) && (rPathElemIdx < relativePathElementListSize)); rPathElemIdx++)
			{
				bool onLastRPathElement = (rPathElemIdx == (relativePathElementListSize - 1));

				string leafName = relativePathElementList[rPathElemIdx];
                string newEntryPath = System.IO.Path.Combine(treeScanEntry.Path, leafName);

                DirectoryTreeEntryNode subLeafNode = RootDirectoryTreeEntryNodeDictionary.SafeTryGetValue(newEntryPath);

                if (subLeafNode != null && subLeafNode.Name != leafName)
                    subLeafNode = treeScanEntry.UpdateAndGetSortedDirContentsNodeArray().FirstOrDefault(item => item.Name == leafName);

				if (subLeafNode == null)
				{
                    DirectoryTreeEntryNode newEntry = new DirectoryTreeEntryNode(newEntryPath, treeScanEntry);
                    subLeafNode = newEntry;

					if (newEntry == null)
					{
						issueEmitter.Emit("Allocation Failure while attempting to added entry path:{0}", newEntryPath);
					}
					else
					{
                        treeScanEntry.sortedDirContentsNodeArray = null;
                        treeScanEntry.sortedDirContentsNodeSet.Add(newEntry);

                        if (newEntry.IsExistingDirectory)
                        {
                            newEntry.BuildTree(issueEmitter: issueEmitter);
                        }
                        else if (newEntry.IsExistingFile)
                        {
                            // nothing more to do here
                        }
                        else
                        {
                            issueEmitter.Emit("Added entry path:{0} is neither a known file or directory object", newEntry.Path);
                        }
					}
				}
				else
				{
                    if (subLeafNode.IsFile)
                        subLeafNode.Refresh();

                    if (!subLeafNode.IsExistingDirectory && !onLastRPathElement)
					{
                        issueEmitter.Emit("Add relative path traverse error: partial path is not a directory at {0}", subLeafNode.Path);

						break;		 // cannot continue to go lower from this point down
					}
				}

                treeScanEntry.SetTreeUpdateNeeded(true);

                treeScanEntry = subLeafNode;
			}

            UpdateTree(issueEmitter: issueEmitter);
        }
示例#21
0
 /// <summary>
 /// Update this object's ConfigItem marked public properties from corresponingly named config keys (using the namePrefix)
 /// </summary>
 public ActiveTimers Setup(string namePrefix, Logging.IMesgEmitter issueEmitter, Logging.IMesgEmitter valueEmitter)
 {
     return(Setup(config: null, namePrefix: namePrefix, issueEmitter: issueEmitter, valueEmitter: valueEmitter));
 }
示例#22
0
 /// <summary>Updates the tree by recalculating the cumulative node information for this node and the nodes above as needed.</summary>
 public void UpdateTree(Logging.IMesgEmitter issueEmitter) 
 {
     UpdateTree(forceUpdate: false, issueEmitter: issueEmitter); 
 }
示例#23
0
 /// <summary>
 /// internal common constructor
 /// </summary>
 protected Buffer(Logging.IMesgEmitter stateEmitter)
 {
     StateEmitter = stateEmitter ?? Logging.NullMesgEmitter.Instance;
     BufferName   = "Buffer_{0:x4}".CheckedFormat(nameInstanceNum & 0xffff);
 }
示例#24
0
 public Message(Buffers.BufferPool bufferSourcePool, Logging.IMesgEmitter issueEmitter = null, Logging.IMesgEmitter stateEmitter = null)
 {
     this.bufferSourcePool = bufferSourcePool;
     StateEmitter          = stateEmitter ?? bufferSourcePool.BufferStateEmitter ?? Logging.NullMesgEmitter.Instance;
     IssueEmitter          = issueEmitter ?? StateEmitter;
 }
示例#25
0
 /// <summary>Forces the node to (re)build the sub-tree and to update it afterward</summary>
 public void RebuildTree(Logging.IMesgEmitter issueEmitter = null)
 {
     BuildTree(updateAtEnd: true, issueEmitter: issueEmitter, forceBuildTree: true);
 }
示例#26
0
 /// <summary>Requests the node to build its sub-tree and to update it afterward</summary>
 public void BuildTree(Logging.IMesgEmitter issueEmitter) 
 {
     BuildTree(updateAtEnd: true, issueEmitter: issueEmitter); 
 }
示例#27
0
        public LPMSimConfigSetAndArrayItems UpdateFromModularConfig(string prefixStr, Logging.IMesgEmitter issueEmitter = null, Logging.IMesgEmitter valueEmitter = null, IConfig configInstance = null)
        {
            ConfigValueSetAdapter <LPMSimConfigSetAndArrayItems> adapter = new ConfigValueSetAdapter <LPMSimConfigSetAndArrayItems>(configInstance)
            {
                ValueSet = this, SetupIssueEmitter = issueEmitter, UpdateIssueEmitter = issueEmitter, ValueNoteEmitter = valueEmitter
            }.Setup(prefixStr);

            return(this);
        }
        protected override void PerformMainLoopService()
        {
            int    pid  = 0;
            string mesg = null;

            bool dataReady = isUsable && DBWIN_DATA_READY.WaitOne(TimeSpan.Zero);

            if (dataReady)
            {
                pid = DBWIN_BUFFER_Accessor.ReadInt32(0);
                int readMesgBytes = DBWIN_BUFFER_Accessor.ReadArray(4, mesgByteBuffer, 0, bufferSize);

                int len = bufferSize;

                for (int idx = 0; idx < len; idx++)
                {
                    if (mesgByteBuffer[idx] == 0)
                    {
                        len = idx;
                    }
                }

                mesg = ByteArrayTranscoders.ByteStringTranscoder.Encode(mesgByteBuffer, 0, len);
                mesgByteBuffer.Clear();

                DBWIN_BUFFER_Accessor.WriteArray(0, zeroBuffer, 0, zeroBuffer.Length);

                DBWIN_DATA_READY.Reset();
                DBWIN_BUFFER_READY.Set();
            }

            if (BaseState.IsOnline && pid != 0 && !mesg.IsNullOrEmpty())
            {
                Func <System.Diagnostics.Process> func           = (() => System.Diagnostics.Process.GetProcessById(pid));
                System.Diagnostics.Process        sendingProcess = func.TryGet();

                Tuple <Logging.ILogger, Logging.IMesgEmitter> pidTuple = null;

                if (tupleDictionary.TryGetValue(pid, out pidTuple) && pidTuple != null)
                {
                    if (sendingProcess != null && !pidTuple.Item1.Name.EndsWith(sendingProcess.ProcessName))
                    {
                        pidTuple = null;
                    }
                }

                if (pidTuple == null)
                {
                    string loggerName;
                    if (sendingProcess != null)
                    {
                        loggerName = "{0}.pid{1}.{2}".CheckedFormat(PartID, pid, sendingProcess.ProcessName);
                    }
                    else
                    {
                        loggerName = "{0}.pid{1}".CheckedFormat(PartID, pid);
                    }

                    Logging.ILogger      logger  = new Logging.Logger(loggerName);
                    Logging.IMesgEmitter emitter = logger.Emitter(generateMesgType);

                    pidTuple             = Tuple.Create(logger, emitter);
                    tupleDictionary[pid] = pidTuple;
                }

                if (pidTuple != null)
                {
                    pidTuple.Item2.Emit("{0}", mesg.TrimEnd(' ', '\t', '\r', '\n'));
                }
            }
        }