예제 #1
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);
            }
        }
예제 #2
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);
                }
            }
        }
예제 #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
        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));
        }
예제 #5
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));
     }
 }
예제 #6
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));
     }
 }
예제 #7
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));
     }
 }
예제 #8
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);
        }
예제 #9
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)");
     }
 }
예제 #10
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);
        }
예제 #11
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());
            }
            }
        }
예제 #12
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)));
 }
예제 #13
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);
        }
예제 #14
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);
        }
예제 #15
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);
        }
예제 #16
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;
        }