示例#1
0
        protected virtual void ServicePortConnState(ConnState remoteEndHasBeenClosedState)
        {
            if (BaseState.IsConnected && (dataSP == null || !dataSP.Connected))
            {
                DisposeDataSocket(false);
                SetBaseState(ConnState.ConnectionFailed, "Socket is no longer connected", true);
            }

            if (BaseState.IsConnected && (lastReadResult == ActionResultEnum.ReadRemoteEndHasBeenClosed))
            {
                try
                {
                    if (dataSP != null)
                    {
                        DisposeDataSocket();
                    }

                    SetBaseState(remoteEndHasBeenClosedState, "Socket remote end has been closed", true);
                }
                catch (System.Exception ex)
                {
                    SetBaseState(ConnState.ConnectionFailed, Fcns.CheckedFormat("Unable to close data socket while handling remote end closed: {0}", ex), true);
                }
            }
        }
示例#2
0
        /// <summary>
        /// Returns the given object to the pool.  Has no effect if given the null value.  Generally the object should have been acquired from the pool.
        /// <para/>The caller is required to pass the last variable/handle to theObject to this method by reference and this method will set the referenced variable/handle to null to complete the return of the object.
        /// If the pool is already full then the object will be dropped or disposed (as appropriate) using Fcns.DisposeOfObject
        /// </summary>
        public virtual void ReturnObjectToPool(ref ObjectType objRef)
        {
            ObjectType objRefCopy = objRef;

            objRef = null;

            if (objRefCopy != null)
            {
                if (ObjectClearDelegate != null)
                {
                    ObjectClearDelegate(objRefCopy);
                }

                lock (freeObjectStackMutex)
                {
                    if (poolIsEnabled && freeObjectStack.Count < freeObjectStackCapacity)
                    {
                        freeObjectStack.Push(objRefCopy);
                        objRefCopy = null;
                    }
                }
            }

            Fcns.DisposeOfObject(ref objRefCopy);
        }
示例#3
0
        public string FmtToString(bool xmlStyle)
        {
            string handshakeStr = (handshake != System.IO.Ports.Handshake.None) ? " Handshake=\"{0}\"".CheckedFormat(handshake) : string.Empty;

            if (xmlStyle || !handshakeStr.IsNullOrEmpty())
            {
                return(Fcns.CheckedFormat("<UartConfig Baud=\"{0}\" DataBits=\"{1}\" Mode=\"{2}\" Parity=\"{3}\" StopBits=\"{4}\"{5}/>"
                                          , baudRate
                                          , StringScanner.FindTokenNameByValue(dataBits, DataBitsCharTokenValueMap, "?")
                                          , StringScanner.FindTokenNameByValue(portMode, PortModeCharTokenValueMap, "?")
                                          , StringScanner.FindTokenNameByValue(parity, ParityTokenValueMap, "?")
                                          , StringScanner.FindTokenNameByValue(stopBits, StopBitsCharTokenValueMap, "?")
                                          , handshakeStr
                                          ));
            }
            else if (portMode == PortMode.DOSMode_Default)
            {
                return(Fcns.CheckedFormat("{0},{1},{2},{3}"
                                          , baudRate
                                          , StringScanner.FindTokenNameByValue(parity, ParityCharTokenValueMap, "?")
                                          , StringScanner.FindTokenNameByValue(dataBits, DataBitsCharTokenValueMap, "?")
                                          , StringScanner.FindTokenNameByValue(stopBits, StopBitsCharTokenValueMap, "?")
                                          ));
            }
            else
            {
                return(Fcns.CheckedFormat("{0},{1},{2},{3},{4}"
                                          , baudRate
                                          , StringScanner.FindTokenNameByValue(parity, ParityCharTokenValueMap, "?")
                                          , StringScanner.FindTokenNameByValue(dataBits, DataBitsCharTokenValueMap, "?")
                                          , StringScanner.FindTokenNameByValue(stopBits, StopBitsCharTokenValueMap, "?")
                                          , StringScanner.FindTokenNameByValue(portMode, PortModeTokenValueMap, "?")
                                          ));
            }
        }
示例#4
0
        private string InnerRunRelayAction(IBasicAction portAction, string description)
        {
            IBasicNotificationList notifyOnComplete = portAction.NotifyOnComplete;

            try
            {
                notifyOnComplete.AddItem(threadWakeupNotifier);

                string resultCode = Fcns.MapNullOrEmptyTo(portAction.Start(), null);

                while (resultCode == null)
                {
                    WaitForSomethingToDo();

                    InnerServiceFCServerAndStateRelay();

                    if (portAction.ActionState.IsComplete)
                    {
                        break;
                    }
                }

                resultCode = (portAction.ActionState.ResultCode ?? Fcns.CheckedFormat("Internal: port.{0} complete with null ResultCode", description));

                return(resultCode);
            }
            finally
            {
                notifyOnComplete.RemoveItem(threadWakeupNotifier);
            }
        }
示例#5
0
        /// <summary>
        /// Serializes the given object by calling WriteObject on the contained JsonSerializer to serialize and write the object into a String
        /// </summary>
        /// <param name="obj">Gives the object that is to be serialized</param>
        /// <returns>A string containing the serialized representation of the given object as serialized by the contained JsonSerializer</returns>
        public override string ConvertObjectToString(TObjectType obj)
        {
            if (writeMemoryStream == null)
            {
                writeMemoryStream = new MemoryStream();
                AddExplicitDisposeAction(() => Fcns.DisposeOfObject(ref writeMemoryStream));
            }

            try
            {
                WriteObject(obj, writeMemoryStream);

                byte[] buffer = writeMemoryStream.GetBuffer();
                string result = System.Text.Encoding.ASCII.GetString(buffer, 0, unchecked ((int)writeMemoryStream.Length));

                writeMemoryStream.Position = 0;
                writeMemoryStream.SetLength(0);

                return(result);
            }
            catch
            {
                Fcns.DisposeOfObject(ref writeMemoryStream);
                throw;
            }
        }
 private void Release()
 {
     isUsable = false;
     Fcns.DisposeOfObject(ref DBWIN_BUFFER_READY);
     Fcns.DisposeOfObject(ref DBWIN_DATA_READY);
     Fcns.DisposeOfObject(ref DBWIN_BUFFER_Accessor);
     Fcns.DisposeOfObject(ref DBWIN_BUFFER);
 }
        protected string PerformWritePageAction(ITagPageContents[] pages)
        {
            if (!BaseState.IsOnline)
            {
                return("Reader is not online");
            }

            if (!privateState.TagIsPresent)
            {
                return("Tag (or Antenna) is not marked as present");
            }

            String ec = null;

            foreach (ITagPageContents page in pages ?? EmptyPageContentsArray)
            {
                int pageIndex = (page != null ? page.PageIndex : 0);

                if (page == null)
                {
                    ec = "encoutered invalid null page contents object";
                }
                else if (pageIndex < 0 || pageIndex >= CurrentConfig.NumPages)
                {
                    ec = Fcns.CheckedFormat("Encoutered invalid pageIdx:{0}", pageIndex);
                }
                else if (page.ByteArray == null)
                {
                    ec = Fcns.CheckedFormat("Page at pageIdx:{0} has null data ByteArray", pageIndex);
                }
                else if (page.ByteArray.Length != CurrentConfig.PageDataSize)
                {
                    ec = Fcns.CheckedFormat("Page at pageIdx:{0} has invalid data ByteArray (length:{1} is not expected value of {2}", pageIndex, page.ByteArray.Length, CurrentConfig.PageDataSize);
                }

                if (String.IsNullOrEmpty(ec))
                {
                    int putOffset = pageIndex * CurrentConfig.PageDataSize;

                    page.ByteArray.CopyTo(privateState.ContentByteArray, putOffset);

                    if (privateState.Config.PageWriteDelayTimeSpan != TimeSpan.Zero)
                    {
                        System.Threading.Thread.Sleep(privateState.Config.PageWriteDelayTimeSpan);
                    }
                }
                else
                {
                    break;
                }
            }

            privateState.UpdateCounterPostfix();
            PublishPrivateState();

            return(Fcns.MapNullToEmpty(ec));
        }
示例#8
0
 /// <summary>Returns a convenient string version of the contents of this object for logging and debugging purposes</summary>
 public override string ToString()
 {
     if (IsSuccess)
     {
         return("Success");
     }
     else
     {
         return(Fcns.CheckedFormat("ErrCode:{0}[{1}] ErrText:'{2}'", ErrCode, unchecked ((int)ErrCode), ErrText));
     }
 }
示例#9
0
 public override string ToString()
 {
     if (!IsStopped)
     {
         return(Fcns.CheckedFormat("Time:{0:f6} Pos:{1} Vel:{2} Accel:{3} Out:{4}", TimeSpanInTrajectory.TotalSeconds, Position, Velocity, Acceleration, Output));
     }
     else
     {
         return(Fcns.CheckedFormat("Time:{0:f6} Pos:{1} Stopped Out:{2}", TimeSpanInTrajectory.TotalSeconds, Position, Output));
     }
 }
示例#10
0
 /// <summary>
 /// Generates a formatted string version of the given errorCode and errorStr.  Includes the given objID if it is neither null nor empty.
 /// </summary>
 public static string FmtStdEC(string objID, int errorCode, string errorStr)
 {
     if (string.IsNullOrEmpty(objID))
     {
         return(Fcns.CheckedFormat("Err:{0}_{1}", errorCode, errorStr));
     }
     else
     {
         return(Fcns.CheckedFormat("{0}:Err:{1}_{2}", objID, errorCode, errorStr));
     }
 }
示例#11
0
 void IVIView_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
 {
     if (e.NewValue as bool? == true)
     {
         Service(evenIfNotVisible: true);
         if (runTimerToken == null)
         {
             runTimerToken = timer.GetRunTimerToken(Fcns.CurrentClassLeafName);
         }
     }
     else if (runTimerToken != null)
     {
         Fcns.DisposeOfObject(ref runTimerToken);
     }
 }
示例#12
0
        /// <summary>Contructor</summary>
        public ModbusServerFunctionPortAdapter(string partID, SerialIO.PortConfig portConfig, IModbusFCServer fcServer, ADUType aduType, byte unitID, bool responseToAllUnits)
            : base(partID, initialSettings: SimpleActivePartBaseSettings.DefaultVersion2.Build(waitTimeLimit: (0.2).FromSeconds()))
        {
            this.fcServer = fcServer;

            Timeout = portConfig.ReadTimeout;
            portConfig.ReadTimeout = TimeSpan.FromSeconds(Math.Max(0.1, Timeout.TotalSeconds));

            port = SerialIO.Factory.CreatePort(portConfig);
            portBaseStateObserver = new SequencedRefObjectSourceObserver <IBaseState, Int32>(port.BaseStateNotifier);

            IPortBehavior portBehavior = port.PortBehavior;

            IDictionary <string, Logging.IMesgEmitter> emitters = new Dictionary <string, Logging.IMesgEmitter>()
            {
                { "Issue", Log.Error }, { "Debug", Log.Debug }, { "Trace", Log.Trace }
            };

            serverFunctionContainer = new ServerFunctionContainer()
            {
                ADUType = aduType, Emitters = emitters, UnitID = unitID, RTUAddr = unitID, MBAPUnitID = unitID, RespondToAllTargets = responseToAllUnits
            };

            FlushPeriod = (portBehavior.IsDatagramPort ? TimeSpan.FromSeconds(0.0) : TimeSpan.FromSeconds(0.1));

            portReadAction = port.CreateReadAction(portReadActionParam = new ReadActionParam()
            {
                WaitForAllBytes = false
            });
            portWriteAction        = port.CreateWriteAction(portWriteActionParam = new WriteActionParam());
            portFlushAction        = port.CreateFlushAction(FlushPeriod);
            portReinitializeAction = port.CreateGoOnlineAction(true);

            portReadAction.NotifyOnComplete.AddItem(threadWakeupNotifier);
            portWriteAction.NotifyOnComplete.AddItem(threadWakeupNotifier);
            portFlushAction.NotifyOnComplete.AddItem(threadWakeupNotifier);
            portReinitializeAction.NotifyOnComplete.AddItem(threadWakeupNotifier);

            port.BaseStateNotifier.NotificationList.AddItem(threadWakeupNotifier);

            AddMainThreadStartingAction(() => port.StartPart());
            AddMainThreadStoppingAction(() => port.StopPart());

            AddExplicitDisposeAction(() => Fcns.DisposeOfObject(ref port));
        }
示例#13
0
        protected string PerformReadPagesAction(IProviderActionBase <NullObj, ITagPageContents[]> action, int startPageIdx, int numPages)
        {
            List <ITagPageContents> pageContentsList = new List <ITagPageContents>();

            // initialize the result to the empty array.
            action.ResultValue = pageContentsList.ToArray();

            if (!BaseState.IsOnline)
            {
                return("Reader is not online");
            }

            if (!privateState.TagIsPresent)
            {
                return("Tag (or Antenna) is not marked as present");
            }

            foreach (int pageIdx in Enumerable.Range(startPageIdx, numPages))
            {
                if (pageIdx < 0 || pageIdx >= CurrentConfig.NumPages)
                {
                    action.ResultValue = pageContentsList.ToArray();

                    return(Fcns.CheckedFormat("Reached invalid page at index:{0} [limit:{1}]", pageIdx, privateState.Config.NumPages));
                }

                int pageStartOffset           = pageIdx * privateState.Config.PageDataSize;
                ITagPageContents pageContents = new TagPageContents()
                {
                    PageIndex = pageIdx, ByteArray = privateState.ContentByteArray.SafeSubArray(pageStartOffset, privateState.Config.PageDataSize)
                };

                pageContentsList.Add(pageContents);

                if (privateState.Config.PageReadDelayTimeSpan != TimeSpan.Zero)
                {
                    System.Threading.Thread.Sleep(privateState.Config.PageReadDelayTimeSpan);
                }
            }

            action.ResultValue = pageContentsList.ToArray();

            return(String.Empty);
        }
示例#14
0
            void AbortCurrentPingRequest()
            {
                lock (mutex)
                {
                    currentUserToken = null;
                }

                try
                {
                    if (ping != null)
                    {
                        ping.SendAsyncCancel();
                    }
                }
                catch
                {}

                Fcns.DisposeOfObject(ref ping);
            }
示例#15
0
 public override string ToString()
 {
     if (Min.HasValue && Max.HasValue)
     {
         return(Fcns.CheckedFormat("[{0}, {1}]", Min, Max));
     }
     else if (Min.HasValue)
     {
         return(Fcns.CheckedFormat("[{0}, inf)", Min));
     }
     else if (Max.HasValue)
     {
         return(Fcns.CheckedFormat("(-Inf, {0}]", Max));
     }
     else
     {
         return("(-Inf, Inf)");
     }
 }
示例#16
0
        /// <summary>Debug and logging assistance method</summary>
        public override string ToString()
        {
            string fullPath = (FileSystemInfo != null ? FileSystemInfo.FullName : "");
            string typeStr = "";
            if (IsFile)
                typeStr = "File";
            else if (IsDirectory)
                typeStr = "Directory";
            else
                typeStr = "UnknownType";

            if (Exists)
                typeStr = typeStr + "+Exists";

            if (IsRootNode)
                typeStr = typeStr + "+IsRoot";

            return Fcns.CheckedFormat("'{0}' {1} Items:{2} Files:{3} Size:{4} [{5}]", Name, typeStr, TreeItemCount, TreeFileCount, TreeContentsSize, fullPath);
        }
示例#17
0
        /// <summary>Disables the pool and disposes of all objects that remain in the freeObjctStack.</summary>
        public void Shutdown()
        {
            lock (freeObjectStackMutex)
            {
                // disable the pool
                poolIsEnabled = false;

                if (freeObjectStack != null)
                {
                    // remove and dispose of all objects in the freeObjectStack
                    while (freeObjectStack.Count > 0)
                    {
                        ObjectType obj = freeObjectStack.Pop();
                        Fcns.DisposeOfObject(ref obj);
                    }

                    freeObjectStack = null;
                }
            }
        }
示例#18
0
        /// <summary>
        /// Obtains the ISharedDispatcherTimer instance from the dictionary (createing one if needed),
        /// Adds any of the optional Tick event handler signatures (as supported by the ISharedDispatchTimer's TickNotificationList)
        /// and returns an IDisposable token that will release use of the timer and will remove any given Tick event handler signatures from the underlying TickNotificationList when the token is dipsosed.
        /// </summary>
        public static IDisposable GetAndStartSharedTimer(double rate, string clientName, BasicNotificationDelegate onTickNotifyDelegate = null, INotifyable notifyableTarget = null, System.Threading.EventWaitHandle eventWaitHandle = null)
        {
            ISharedDispatcherTimer sharedDispatcherTimer = GetSharedTimer(rate);

            if (onTickNotifyDelegate != null)
            {
                sharedDispatcherTimer.TickNotificationList.OnNotify += onTickNotifyDelegate;
            }

            if (notifyableTarget != null)
            {
                sharedDispatcherTimer.TickNotificationList.AddItem(notifyableTarget);
            }

            if (eventWaitHandle != null)
            {
                sharedDispatcherTimer.TickNotificationList.AddItem(eventWaitHandle);
            }

            IDisposable token = sharedDispatcherTimer.GetRunTimerToken(clientName);

            return(new ExplicitDisposeActionList()
                   .AddItems(() => Fcns.DisposeOfGivenObject(token),
                             () =>
            {
                if (onTickNotifyDelegate != null)
                {
                    sharedDispatcherTimer.TickNotificationList.OnNotify -= onTickNotifyDelegate;
                }

                if (notifyableTarget != null)
                {
                    sharedDispatcherTimer.TickNotificationList.RemoveItem(notifyableTarget);
                }

                if (eventWaitHandle != null)
                {
                    sharedDispatcherTimer.TickNotificationList.RemoveItem(eventWaitHandle);
                }
            }));
        }
示例#19
0
        public string ToString(TagRWPageContentsStringFormat fmtToUse)
        {
            switch (fmtToUse)
            {
            case TagRWPageContentsStringFormat.DecimalPageSpaceBytesInHex:
                // version used by some drivers
                return(Fcns.CheckedFormat("{0:d2} {1}", (PageIndex + 1), ByteArrayTranscoders.HexStringTranscoderNoPadding.Encode(ByteArray)));

            case TagRWPageContentsStringFormat.DecimalPageSpaceQuotedBytesInHex:
                // version used by some drivers
                return(Fcns.CheckedFormat("{0:d2} '{1}'", (PageIndex + 1), ByteArrayTranscoders.HexStringTranscoderNoPadding.Encode(ByteArray)));

            case TagRWPageContentsStringFormat.HexAndAscii:
            default:
                // version used for screen display and logging.
            {
                StringBuilder sb = new StringBuilder();

                sb.CheckedAppendFormat("{0:d2}: {1} [", (PageIndex + 1), ByteArrayTranscoders.HexStringTranscoder.Encode(ByteArray));

                foreach (byte b in ByteArray)
                {
                    char c = unchecked ((char)b);

                    if (Char.IsLetterOrDigit(c) || Char.IsPunctuation(c) || Char.IsSymbol(c))
                    {
                        sb.Append(c);
                    }
                    else
                    {
                        sb.Append('.');
                    }
                }

                sb.Append(']');

                return(sb.ToString());
            }
            }
        }
示例#20
0
        /// <summary>
        /// This method attempt to return the given <paramref name="item"/> to the free list.
        /// If the given <paramref name="item"/> is null then the method has no effect.
        /// If the free list is no full then the <paramref name="item"/> will be added to the back of the free list, optionally being cleared using the ClearDelegate first.
        /// If the free list is no full then the <paramref name="item"/> will be discarded.
        /// Before discarding, If TItemType is IDisposable then the <paramref name="item"/> will be disposed using the Fcns.DisposeOfGivenObject first.
        /// <para/>This method requires reference access to the given <paramref name="item"/> and the reference will be assigned to null before the method returns.
        /// </summary>
        public void Release(ref TItemType item)
        {
            if (item == null)
            {
                return;
            }

            if (freeList.Count < MaxItemsToKeep)
            {
                Action <TItemType> clearDelegate = ClearDelegate;
                if (clearDelegate != null)
                {
                    clearDelegate(item);
                }

                freeList.Add(item);
            }
            else if (WillDispose)
            {
                Fcns.DisposeOfGivenObject(item);
            }

            item = null;
        }
示例#21
0
 void StopTimers()
 {
     Fcns.DisposeOfObject(ref runTimerToken);
 }
示例#22
0
        /// <summary>
        /// Internal method used to perform setup.
        /// Verifies that directory exists, or can be created.
        /// Builds the tree from the root path.
        /// Verifies that configuration is valid.
        /// Performs initial pruning if desired.
        /// Logs setup success or failure
        /// </summary>
        private void InnerSetup(Config configIn)
        {
            // if needed, clear the prior state.
            if (setupPerformed)
            {
                Clear();
            }

            try
            {
                // record the given configuration
                config         = configIn;
                config.DirPath = System.IO.Path.GetFullPath(config.DirPath);

                bool dirExists  = System.IO.Directory.Exists(config.DirPath);
                bool fileExists = !dirExists && System.IO.File.Exists(config.DirPath);

                if (fileExists)
                {
                    SetFaultCode(Fcns.CheckedFormat("Setup Failure: target path '{0}' exists and does not specify a directory", config.DirPath));
                }
                else if (!dirExists)
                {
                    if (config.CreateDirectoryIfNeeded)
                    {
                        System.IO.Directory.CreateDirectory(config.DirPath);
                    }
                    else
                    {
                        SetFaultCode(Fcns.CheckedFormat("Setup Failure: target directory '{0}' does not exist and could not be automatically created", config.DirPath));
                    }
                }

                if (!DidSetupFail)
                {
                    // directory exists or has been created - now scan it and record each of the entries that are found therein
                    treeRootEntry.SetPathAndGetInfo(config.DirPath);

                    treeRootEntry.BuildTree(Issue.Emitter);
                    treeRootEntry.UpdateTree(Issue.Emitter);
                }
            }
            catch (System.Exception ex)
            {
                SetFaultCode(Fcns.CheckedFormat("Setup Failure: {0}", ex));
            }

            if (!DidSetupFail)
            {
                if (config.PruneRules.TreeNumFilesLimit != 0 && config.PruneRules.TreeNumFilesLimit < ConfigPruneNumFilesMinValue)
                {
                    SetFaultCode("Setup Failure: Config: PruneRules.TreeNumFilesLimit is too small");
                }
                else if (config.PruneRules.TreeNumFilesLimit != 0 && config.PruneRules.TreeNumFilesLimit > ConfigPruneNumFilesMaxValue)
                {
                    SetFaultCode("Setup Failure: Config: PruneRules.TreeNumFilesLimit is too large");
                }
                else if (config.PruneRules.TreeTotalSizeLimit < 0)
                {
                    SetFaultCode("Setup Failure: Config: PruneRules.TreeTotalSizeLimit is negative");
                }
                else if (config.PruneRules.FileAgeLimit.TotalDays < 0.0)
                {
                    SetFaultCode("Setup Failure: Config: pruneRules.FileAgeLimitInDays is negative");
                }
            }

            if (!DidSetupFail && config.MaxInitialAutoCleanupIterations > 0)
            {
                for (int iteration = 0; (iteration < config.MaxInitialAutoCleanupIterations); iteration++)
                {
                    if (!PerformIncrementalPrune())
                    {
                        break;
                    }
                }
            }

            if (!DidSetupFail)
            {
                Info.Emitter.Emit("Directory is usable: path:'{0}' total files:{1}, items:{2}, size:{3:f3} Mb, Age:{4:f6} days",
                                  config.DirPath,
                                  treeRootEntry.TreeFileCount,
                                  treeRootEntry.TreeItemCount,
                                  (treeRootEntry.TreeContentsSize * (1.0 / (1024.0 * 1024.0))),
                                  treeRootEntry.TreeAge.TotalDays
                                  );
            }
            else
            {
                Issue.Emitter.Emit("Dirctory is not usable: path:'{0}' fault:'{1}'", config.DirPath, SetupFaultCode);
            }

            setupPerformed = true;
        }
示例#23
0
 /// <summary>Provides the implementation of the Standard Service Action.  Runs a pass through Service action on the contained Port object.</summary>
 protected override string PerformServiceAction(string serviceName)
 {
     return(InnerRunRelayAction(port.CreateServiceAction(serviceName), Fcns.CheckedFormat("ServiceAction({0})", serviceName)));
 }
示例#24
0
 /// <summary>abstract internal Rlease method implementation.  Stops the timer and disposes of it (as well as nulling the local field that holds on to it).</summary>
 protected override void Release(string lastClientName)
 {
     timer.Stop();
     Fcns.DisposeOfObject(ref timer);
 }
示例#25
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);
        }
示例#26
0
 public void Release()
 {
     Fcns.DisposeOfObject(ref ping);
 }
示例#27
0
 void Release()
 {
     Fcns.DisposeOfObject(ref fsWriteThrough);
 }
示例#28
0
        /// <summary>
        /// Generates and returns this object as an Xml'is formated E005 data object composed of L, U1, U4 and A elements.
        /// </summary>
        public string ToXMLString()
        {
            // returns something like <L> <U1>caack<U1> <L> <L> <U4>errcode</U4> <A>errtext</A> </L> ... </L>

            StringBuilder sb = new StringBuilder();

            sb.CheckedAppendFormat(@"<L> <U1>{0}</U1> <L>", unchecked ((int)CAACK));

            foreach (StatusPair statusPair in StatusList)
            {
                sb.CheckedAppendFormat(" <L> <U4>{0}</U4> <A>{1}</A> </L>", unchecked ((int)statusPair.ErrCode), Fcns.MapNullToEmpty(statusPair.ErrText));
            }

            sb.Append(" </L> </L>");

            return(sb.ToString());
        }
示例#29
0
        public IReadPagesAction CreateReadPagesAction(int startPageIdx, int numPages)
        {
            ActionMethodDelegateActionArgStrResult <NullObj, ITagPageContents[]> method = ((providerFacet) => PerformReadPagesAction(providerFacet, startPageIdx, numPages));
            IReadPagesAction clientFacet = new ReadPagesAction(actionQ, method, new ActionLogging(Fcns.CheckedFormat("ReadPages(startPageIdx:{0}, numPages:{1})", startPageIdx, numPages), ActionLoggingReference));

            return(clientFacet);
        }
示例#30
0
        public IBasicAction CreateWritePagesAction(ITagPageContents[] pages)
        {
            string pageNumListStr = String.Join(",", pages.Select((page) => page.PageIndex).Select((pageIdx) => Fcns.CheckedFormat("${0:x2}", pageIdx + 1)).ToArray());
            ActionMethodDelegateStrResult method = (() => PerformWritePageAction(pages));
            IBasicAction clientFacet             = new BasicActionImpl(actionQ, method, Fcns.CheckedFormat("WritePages({0})", pageNumListStr), ActionLoggingReference);

            return(clientFacet);
        }